Merge from trunk @217148.
[official-gcc.git] / gcc / ada / gcc-interface / trans.c
blobd0f764bbea39f96927b12c07f9f2b59799f0abde
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * T R A N S *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2014, 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 ****************************************************************************/
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "stringpool.h"
32 #include "stor-layout.h"
33 #include "stmt.h"
34 #include "varasm.h"
35 #include "flags.h"
36 #include "output.h"
37 #include "libfuncs.h" /* For set_stack_check_libfunc. */
38 #include "tree-iterator.h"
39 #include "hash-set.h"
40 #include "gimple-expr.h"
41 #include "gimplify.h"
42 #include "bitmap.h"
43 #include "hash-map.h"
44 #include "is-a.h"
45 #include "plugin-api.h"
46 #include "vec.h"
47 #include "hashtab.h"
48 #include "machmode.h"
49 #include "hard-reg-set.h"
50 #include "input.h"
51 #include "function.h"
52 #include "ipa-ref.h"
53 #include "cgraph.h"
54 #include "diagnostic.h"
55 #include "opts.h"
56 #include "target.h"
57 #include "common/common-target.h"
59 #include "ada.h"
60 #include "adadecode.h"
61 #include "types.h"
62 #include "atree.h"
63 #include "elists.h"
64 #include "namet.h"
65 #include "nlists.h"
66 #include "snames.h"
67 #include "stringt.h"
68 #include "uintp.h"
69 #include "urealp.h"
70 #include "fe.h"
71 #include "sinfo.h"
72 #include "einfo.h"
73 #include "gadaint.h"
74 #include "ada-tree.h"
75 #include "gigi.h"
77 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
78 for fear of running out of stack space. If we need more, we use xmalloc
79 instead. */
80 #define ALLOCA_THRESHOLD 1000
82 /* In configurations where blocks have no end_locus attached, just
83 sink assignments into a dummy global. */
84 #ifndef BLOCK_SOURCE_END_LOCATION
85 static location_t block_end_locus_sink;
86 #define BLOCK_SOURCE_END_LOCATION(BLOCK) block_end_locus_sink
87 #endif
89 /* Pointers to front-end tables accessed through macros. */
90 struct Node *Nodes_Ptr;
91 struct Flags *Flags_Ptr;
92 Node_Id *Next_Node_Ptr;
93 Node_Id *Prev_Node_Ptr;
94 struct Elist_Header *Elists_Ptr;
95 struct Elmt_Item *Elmts_Ptr;
96 struct String_Entry *Strings_Ptr;
97 Char_Code *String_Chars_Ptr;
98 struct List_Header *List_Headers_Ptr;
100 /* Highest number in the front-end node table. */
101 int max_gnat_nodes;
103 /* Current node being treated, in case abort called. */
104 Node_Id error_gnat_node;
106 /* True when gigi is being called on an analyzed but unexpanded
107 tree, and the only purpose of the call is to properly annotate
108 types with representation information. */
109 bool type_annotate_only;
111 /* Current filename without path. */
112 const char *ref_filename;
115 /* List of N_Validate_Unchecked_Conversion nodes in the unit. */
116 static vec<Node_Id> gnat_validate_uc_list;
118 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
119 of unconstrained array IN parameters to avoid emitting a great deal of
120 redundant instructions to recompute them each time. */
121 struct GTY (()) parm_attr_d {
122 int id; /* GTY doesn't like Entity_Id. */
123 int dim;
124 tree first;
125 tree last;
126 tree length;
129 typedef struct parm_attr_d *parm_attr;
132 struct GTY(()) language_function {
133 vec<parm_attr, va_gc> *parm_attr_cache;
134 bitmap named_ret_val;
135 vec<tree, va_gc> *other_ret_val;
136 int gnat_ret;
139 #define f_parm_attr_cache \
140 DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
142 #define f_named_ret_val \
143 DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
145 #define f_other_ret_val \
146 DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
148 #define f_gnat_ret \
149 DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
151 /* A structure used to gather together information about a statement group.
152 We use this to gather related statements, for example the "then" part
153 of a IF. In the case where it represents a lexical scope, we may also
154 have a BLOCK node corresponding to it and/or cleanups. */
156 struct GTY((chain_next ("%h.previous"))) stmt_group {
157 struct stmt_group *previous; /* Previous code group. */
158 tree stmt_list; /* List of statements for this code group. */
159 tree block; /* BLOCK for this code group, if any. */
160 tree cleanups; /* Cleanups for this code group, if any. */
163 static GTY(()) struct stmt_group *current_stmt_group;
165 /* List of unused struct stmt_group nodes. */
166 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
168 /* A structure used to record information on elaboration procedures
169 we've made and need to process.
171 ??? gnat_node should be Node_Id, but gengtype gets confused. */
173 struct GTY((chain_next ("%h.next"))) elab_info {
174 struct elab_info *next; /* Pointer to next in chain. */
175 tree elab_proc; /* Elaboration procedure. */
176 int gnat_node; /* The N_Compilation_Unit. */
179 static GTY(()) struct elab_info *elab_info_list;
181 /* Stack of exception pointer variables. Each entry is the VAR_DECL
182 that stores the address of the raised exception. Nonzero means we
183 are in an exception handler. Not used in the zero-cost case. */
184 static GTY(()) vec<tree, va_gc> *gnu_except_ptr_stack;
186 /* In ZCX case, current exception pointer. Used to re-raise it. */
187 static GTY(()) tree gnu_incoming_exc_ptr;
189 /* Stack for storing the current elaboration procedure decl. */
190 static GTY(()) vec<tree, va_gc> *gnu_elab_proc_stack;
192 /* Stack of labels to be used as a goto target instead of a return in
193 some functions. See processing for N_Subprogram_Body. */
194 static GTY(()) vec<tree, va_gc> *gnu_return_label_stack;
196 /* Stack of variable for the return value of a function with copy-in/copy-out
197 parameters. See processing for N_Subprogram_Body. */
198 static GTY(()) vec<tree, va_gc> *gnu_return_var_stack;
200 /* Structure used to record information for a range check. */
201 struct GTY(()) range_check_info_d {
202 tree low_bound;
203 tree high_bound;
204 tree type;
205 tree invariant_cond;
208 typedef struct range_check_info_d *range_check_info;
211 /* Structure used to record information for a loop. */
212 struct GTY(()) loop_info_d {
213 tree stmt;
214 tree loop_var;
215 vec<range_check_info, va_gc> *checks;
218 typedef struct loop_info_d *loop_info;
221 /* Stack of loop_info structures associated with LOOP_STMT nodes. */
222 static GTY(()) vec<loop_info, va_gc> *gnu_loop_stack;
224 /* The stacks for N_{Push,Pop}_*_Label. */
225 static GTY(()) vec<tree, va_gc> *gnu_constraint_error_label_stack;
226 static GTY(()) vec<tree, va_gc> *gnu_storage_error_label_stack;
227 static GTY(()) vec<tree, va_gc> *gnu_program_error_label_stack;
229 /* Map GNAT tree codes to GCC tree codes for simple expressions. */
230 static enum tree_code gnu_codes[Number_Node_Kinds];
232 static void init_code_table (void);
233 static void Compilation_Unit_to_gnu (Node_Id);
234 static void record_code_position (Node_Id);
235 static void insert_code_for (Node_Id);
236 static void add_cleanup (tree, Node_Id);
237 static void add_stmt_list (List_Id);
238 static void push_exception_label_stack (vec<tree, va_gc> **, Entity_Id);
239 static tree build_stmt_group (List_Id, bool);
240 static inline bool stmt_group_may_fallthru (void);
241 static enum gimplify_status gnat_gimplify_stmt (tree *);
242 static void elaborate_all_entities (Node_Id);
243 static void process_freeze_entity (Node_Id);
244 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
245 static tree emit_range_check (tree, Node_Id, Node_Id);
246 static tree emit_index_check (tree, tree, tree, tree, Node_Id);
247 static tree emit_check (tree, tree, int, Node_Id);
248 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
249 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
250 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
251 static bool addressable_p (tree, tree);
252 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
253 static tree extract_values (tree, tree);
254 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
255 static void validate_unchecked_conversion (Node_Id);
256 static tree maybe_implicit_deref (tree);
257 static void set_expr_location_from_node (tree, Node_Id);
258 static void set_expr_location_from_node1 (tree, Node_Id, bool);
259 static bool Sloc_to_locus1 (Source_Ptr, location_t *, bool);
260 static bool set_end_locus_from_node (tree, Node_Id);
261 static void set_gnu_expr_location_from_node (tree, Node_Id);
262 static int lvalue_required_p (Node_Id, tree, bool, bool, bool);
263 static tree build_raise_check (int, enum exception_info_kind);
264 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
266 /* Hooks for debug info back-ends, only supported and used in a restricted set
267 of configurations. */
268 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
269 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
271 /* This is the main program of the back-end. It sets up all the table
272 structures and then generates code. */
274 void
275 gigi (Node_Id gnat_root,
276 int max_gnat_node,
277 int number_name ATTRIBUTE_UNUSED,
278 struct Node *nodes_ptr,
279 struct Flags *flags_ptr,
280 Node_Id *next_node_ptr,
281 Node_Id *prev_node_ptr,
282 struct Elist_Header *elists_ptr,
283 struct Elmt_Item *elmts_ptr,
284 struct String_Entry *strings_ptr,
285 Char_Code *string_chars_ptr,
286 struct List_Header *list_headers_ptr,
287 Nat number_file,
288 struct File_Info_Type *file_info_ptr,
289 Entity_Id standard_boolean,
290 Entity_Id standard_integer,
291 Entity_Id standard_character,
292 Entity_Id standard_long_long_float,
293 Entity_Id standard_exception_type,
294 Int gigi_operating_mode)
296 Node_Id gnat_iter;
297 Entity_Id gnat_literal;
298 tree t, ftype, int64_type;
299 struct elab_info *info;
300 int i;
302 max_gnat_nodes = max_gnat_node;
304 Nodes_Ptr = nodes_ptr;
305 Flags_Ptr = flags_ptr;
306 Next_Node_Ptr = next_node_ptr;
307 Prev_Node_Ptr = prev_node_ptr;
308 Elists_Ptr = elists_ptr;
309 Elmts_Ptr = elmts_ptr;
310 Strings_Ptr = strings_ptr;
311 String_Chars_Ptr = string_chars_ptr;
312 List_Headers_Ptr = list_headers_ptr;
314 type_annotate_only = (gigi_operating_mode == 1);
316 for (i = 0; i < number_file; i++)
318 /* Use the identifier table to make a permanent copy of the filename as
319 the name table gets reallocated after Gigi returns but before all the
320 debugging information is output. The __gnat_to_canonical_file_spec
321 call translates filenames from pragmas Source_Reference that contain
322 host style syntax not understood by gdb. */
323 const char *filename
324 = IDENTIFIER_POINTER
325 (get_identifier
326 (__gnat_to_canonical_file_spec
327 (Get_Name_String (file_info_ptr[i].File_Name))));
329 /* We rely on the order isomorphism between files and line maps. */
330 gcc_assert ((int) LINEMAPS_ORDINARY_USED (line_table) == i);
332 /* We create the line map for a source file at once, with a fixed number
333 of columns chosen to avoid jumping over the next power of 2. */
334 linemap_add (line_table, LC_ENTER, 0, filename, 1);
335 linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
336 linemap_position_for_column (line_table, 252 - 1);
337 linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
340 gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
342 /* Declare the name of the compilation unit as the first global
343 name in order to make the middle-end fully deterministic. */
344 t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
345 first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
347 /* Initialize ourselves. */
348 init_code_table ();
349 init_gnat_decl ();
350 init_gnat_utils ();
352 /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
353 errors. */
354 if (type_annotate_only)
356 TYPE_SIZE (void_type_node) = bitsize_zero_node;
357 TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
360 /* Enable GNAT stack checking method if needed */
361 if (!Stack_Check_Probes_On_Target)
362 set_stack_check_libfunc ("_gnat_stack_check");
364 /* Retrieve alignment settings. */
365 double_float_alignment = get_target_double_float_alignment ();
366 double_scalar_alignment = get_target_double_scalar_alignment ();
368 /* Record the builtin types. Define `integer' and `character' first so that
369 dbx will output them first. */
370 record_builtin_type ("integer", integer_type_node, false);
371 record_builtin_type ("character", unsigned_char_type_node, false);
372 record_builtin_type ("boolean", boolean_type_node, false);
373 record_builtin_type ("void", void_type_node, false);
375 /* Save the type we made for integer as the type for Standard.Integer. */
376 save_gnu_tree (Base_Type (standard_integer),
377 TYPE_NAME (integer_type_node),
378 false);
380 /* Likewise for character as the type for Standard.Character. */
381 save_gnu_tree (Base_Type (standard_character),
382 TYPE_NAME (unsigned_char_type_node),
383 false);
385 /* Likewise for boolean as the type for Standard.Boolean. */
386 save_gnu_tree (Base_Type (standard_boolean),
387 TYPE_NAME (boolean_type_node),
388 false);
389 gnat_literal = First_Literal (Base_Type (standard_boolean));
390 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
391 gcc_assert (t == boolean_false_node);
392 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
393 boolean_type_node, t, true, false, false, false,
394 NULL, gnat_literal);
395 DECL_IGNORED_P (t) = 1;
396 save_gnu_tree (gnat_literal, t, false);
397 gnat_literal = Next_Literal (gnat_literal);
398 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
399 gcc_assert (t == boolean_true_node);
400 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
401 boolean_type_node, t, true, false, false, false,
402 NULL, gnat_literal);
403 DECL_IGNORED_P (t) = 1;
404 save_gnu_tree (gnat_literal, t, false);
406 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
407 ptr_void_ftype = build_pointer_type (void_ftype);
409 /* Now declare run-time functions. */
410 ftype = build_function_type_list (ptr_void_type_node, sizetype, NULL_TREE);
412 /* malloc is a function declaration tree for a function to allocate
413 memory. */
414 malloc_decl
415 = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
416 ftype, NULL_TREE, is_disabled, true, true, true,
417 NULL, Empty);
418 DECL_IS_MALLOC (malloc_decl) = 1;
420 /* free is a function declaration tree for a function to free memory. */
421 free_decl
422 = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
423 build_function_type_list (void_type_node,
424 ptr_void_type_node,
425 NULL_TREE),
426 NULL_TREE, is_disabled, true, true, true, NULL,
427 Empty);
429 /* This is used for 64-bit multiplication with overflow checking. */
430 int64_type = gnat_type_for_size (64, 0);
431 mulv64_decl
432 = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
433 build_function_type_list (int64_type, int64_type,
434 int64_type, NULL_TREE),
435 NULL_TREE, is_disabled, true, true, true, NULL,
436 Empty);
438 /* Name of the _Parent field in tagged record types. */
439 parent_name_id = get_identifier (Get_Name_String (Name_uParent));
441 /* Name of the Exception_Data type defined in System.Standard_Library. */
442 exception_data_name_id
443 = get_identifier ("system__standard_library__exception_data");
445 /* Make the types and functions used for exception processing. */
446 jmpbuf_type
447 = build_array_type (gnat_type_for_mode (Pmode, 0),
448 build_index_type (size_int (5)));
449 record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
450 jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
452 /* Functions to get and set the jumpbuf pointer for the current thread. */
453 get_jmpbuf_decl
454 = create_subprog_decl
455 (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
456 NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
457 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
458 DECL_IGNORED_P (get_jmpbuf_decl) = 1;
460 set_jmpbuf_decl
461 = create_subprog_decl
462 (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
463 NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
464 NULL_TREE),
465 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
466 DECL_IGNORED_P (set_jmpbuf_decl) = 1;
468 /* setjmp returns an integer and has one operand, which is a pointer to
469 a jmpbuf. */
470 setjmp_decl
471 = create_subprog_decl
472 (get_identifier ("__builtin_setjmp"), NULL_TREE,
473 build_function_type_list (integer_type_node, jmpbuf_ptr_type,
474 NULL_TREE),
475 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
476 DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
477 DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
479 /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
480 address. */
481 update_setjmp_buf_decl
482 = create_subprog_decl
483 (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
484 build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
485 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
486 DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
487 DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
489 /* Hooks to call when entering/leaving an exception handler. */
490 ftype
491 = build_function_type_list (void_type_node, ptr_void_type_node, NULL_TREE);
493 begin_handler_decl
494 = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
495 ftype, NULL_TREE, is_disabled, true, true, true,
496 NULL, Empty);
497 DECL_IGNORED_P (begin_handler_decl) = 1;
499 end_handler_decl
500 = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
501 ftype, NULL_TREE, is_disabled, true, true, true,
502 NULL, Empty);
503 DECL_IGNORED_P (end_handler_decl) = 1;
505 unhandled_except_decl
506 = create_subprog_decl (get_identifier ("__gnat_unhandled_except_handler"),
507 NULL_TREE,
508 ftype, NULL_TREE, is_disabled, true, true, true,
509 NULL, Empty);
510 DECL_IGNORED_P (unhandled_except_decl) = 1;
512 reraise_zcx_decl
513 = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
514 ftype, NULL_TREE, is_disabled, true, true, true,
515 NULL, Empty);
516 /* Indicate that these never return. */
517 DECL_IGNORED_P (reraise_zcx_decl) = 1;
518 TREE_THIS_VOLATILE (reraise_zcx_decl) = 1;
519 TREE_SIDE_EFFECTS (reraise_zcx_decl) = 1;
520 TREE_TYPE (reraise_zcx_decl)
521 = build_qualified_type (TREE_TYPE (reraise_zcx_decl), TYPE_QUAL_VOLATILE);
523 /* If in no exception handlers mode, all raise statements are redirected to
524 __gnat_last_chance_handler. No need to redefine raise_nodefer_decl since
525 this procedure will never be called in this mode. */
526 if (No_Exception_Handlers_Set ())
528 tree decl
529 = create_subprog_decl
530 (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
531 build_function_type_list (void_type_node,
532 build_pointer_type
533 (unsigned_char_type_node),
534 integer_type_node, NULL_TREE),
535 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
536 TREE_THIS_VOLATILE (decl) = 1;
537 TREE_SIDE_EFFECTS (decl) = 1;
538 TREE_TYPE (decl)
539 = build_qualified_type (TREE_TYPE (decl), TYPE_QUAL_VOLATILE);
540 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
541 gnat_raise_decls[i] = decl;
543 else
545 /* Otherwise, make one decl for each exception reason. */
546 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
547 gnat_raise_decls[i] = build_raise_check (i, exception_simple);
548 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
549 gnat_raise_decls_ext[i]
550 = build_raise_check (i,
551 i == CE_Index_Check_Failed
552 || i == CE_Range_Check_Failed
553 || i == CE_Invalid_Data
554 ? exception_range : exception_column);
557 /* Set the types that GCC and Gigi use from the front end. */
558 except_type_node = gnat_to_gnu_type (Base_Type (standard_exception_type));
560 /* Make other functions used for exception processing. */
561 get_excptr_decl
562 = create_subprog_decl
563 (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
564 build_function_type_list (build_pointer_type (except_type_node),
565 NULL_TREE),
566 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
567 DECL_IGNORED_P (get_excptr_decl) = 1;
569 set_exception_parameter_decl
570 = create_subprog_decl
571 (get_identifier ("__gnat_set_exception_parameter"), NULL_TREE,
572 build_function_type_list (void_type_node,
573 ptr_void_type_node,
574 ptr_void_type_node,
575 NULL_TREE),
576 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
578 raise_nodefer_decl
579 = create_subprog_decl
580 (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
581 build_function_type_list (void_type_node,
582 build_pointer_type (except_type_node),
583 NULL_TREE),
584 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
586 /* Indicate that it never returns. */
587 TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
588 TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
589 TREE_TYPE (raise_nodefer_decl)
590 = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
591 TYPE_QUAL_VOLATILE);
593 /* Build the special descriptor type and its null node if needed. */
594 if (TARGET_VTABLE_USES_DESCRIPTORS)
596 tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
597 tree field_list = NULL_TREE;
598 int j;
599 vec<constructor_elt, va_gc> *null_vec = NULL;
600 constructor_elt *elt;
602 fdesc_type_node = make_node (RECORD_TYPE);
603 vec_safe_grow (null_vec, TARGET_VTABLE_USES_DESCRIPTORS);
604 elt = (null_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
606 for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
608 tree field
609 = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
610 NULL_TREE, NULL_TREE, 0, 1);
611 DECL_CHAIN (field) = field_list;
612 field_list = field;
613 elt->index = field;
614 elt->value = null_node;
615 elt--;
618 finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
619 record_builtin_type ("descriptor", fdesc_type_node, true);
620 null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
623 longest_float_type_node
624 = get_unpadded_type (Base_Type (standard_long_long_float));
626 /* Dummy objects to materialize "others" and "all others" in the exception
627 tables. These are exported by a-exexpr-gcc.adb, so see this unit for
628 the types to use. */
629 others_decl
630 = create_var_decl (get_identifier ("OTHERS"),
631 get_identifier ("__gnat_others_value"),
632 unsigned_char_type_node,
633 NULL_TREE, true, false, true, false, NULL, Empty);
635 all_others_decl
636 = create_var_decl (get_identifier ("ALL_OTHERS"),
637 get_identifier ("__gnat_all_others_value"),
638 unsigned_char_type_node,
639 NULL_TREE, true, false, true, false, NULL, Empty);
641 unhandled_others_decl
642 = create_var_decl (get_identifier ("UNHANDLED_OTHERS"),
643 get_identifier ("__gnat_unhandled_others_value"),
644 unsigned_char_type_node,
645 NULL_TREE, true, false, true, false, NULL, Empty);
647 main_identifier_node = get_identifier ("main");
649 /* Install the builtins we might need, either internally or as
650 user available facilities for Intrinsic imports. */
651 gnat_install_builtins ();
653 vec_safe_push (gnu_except_ptr_stack, NULL_TREE);
654 vec_safe_push (gnu_constraint_error_label_stack, NULL_TREE);
655 vec_safe_push (gnu_storage_error_label_stack, NULL_TREE);
656 vec_safe_push (gnu_program_error_label_stack, NULL_TREE);
658 /* Process any Pragma Ident for the main unit. */
659 if (Present (Ident_String (Main_Unit)))
660 targetm.asm_out.output_ident
661 (TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
663 /* If we are using the GCC exception mechanism, let GCC know. */
664 if (Exception_Mechanism == Back_End_Exceptions)
665 gnat_init_gcc_eh ();
667 /* Initialize the GCC support for FP operations. */
668 gnat_init_gcc_fp ();
670 /* Now translate the compilation unit proper. */
671 Compilation_Unit_to_gnu (gnat_root);
673 /* Then process the N_Validate_Unchecked_Conversion nodes. We do this at
674 the very end to avoid having to second-guess the front-end when we run
675 into dummy nodes during the regular processing. */
676 for (i = 0; gnat_validate_uc_list.iterate (i, &gnat_iter); i++)
677 validate_unchecked_conversion (gnat_iter);
678 gnat_validate_uc_list.release ();
680 /* Finally see if we have any elaboration procedures to deal with. */
681 for (info = elab_info_list; info; info = info->next)
683 tree gnu_body = DECL_SAVED_TREE (info->elab_proc), gnu_stmts;
685 /* We should have a BIND_EXPR but it may not have any statements in it.
686 If it doesn't have any, we have nothing to do except for setting the
687 flag on the GNAT node. Otherwise, process the function as others. */
688 gnu_stmts = gnu_body;
689 if (TREE_CODE (gnu_stmts) == BIND_EXPR)
690 gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
691 if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
692 Set_Has_No_Elaboration_Code (info->gnat_node, 1);
693 else
695 begin_subprog_body (info->elab_proc);
696 end_subprog_body (gnu_body);
697 rest_of_subprog_body_compilation (info->elab_proc);
701 /* Destroy ourselves. */
702 destroy_gnat_decl ();
703 destroy_gnat_utils ();
705 /* We cannot track the location of errors past this point. */
706 error_gnat_node = Empty;
709 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
710 CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext. */
712 static tree
713 build_raise_check (int check, enum exception_info_kind kind)
715 tree result, ftype;
716 const char pfx[] = "__gnat_rcheck_";
718 strcpy (Name_Buffer, pfx);
719 Name_Len = sizeof (pfx) - 1;
720 Get_RT_Exception_Name (check);
722 if (kind == exception_simple)
724 Name_Buffer[Name_Len] = 0;
725 ftype
726 = build_function_type_list (void_type_node,
727 build_pointer_type
728 (unsigned_char_type_node),
729 integer_type_node, NULL_TREE);
731 else
733 tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
735 strcpy (Name_Buffer + Name_Len, "_ext");
736 Name_Buffer[Name_Len + 4] = 0;
737 ftype
738 = build_function_type_list (void_type_node,
739 build_pointer_type
740 (unsigned_char_type_node),
741 integer_type_node, integer_type_node,
742 t, t, NULL_TREE);
745 result
746 = create_subprog_decl (get_identifier (Name_Buffer),
747 NULL_TREE, ftype, NULL_TREE,
748 is_disabled, true, true, true, NULL, Empty);
750 /* Indicate that it never returns. */
751 TREE_THIS_VOLATILE (result) = 1;
752 TREE_SIDE_EFFECTS (result) = 1;
753 TREE_TYPE (result)
754 = build_qualified_type (TREE_TYPE (result), TYPE_QUAL_VOLATILE);
756 return result;
759 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
760 an N_Attribute_Reference. */
762 static int
763 lvalue_required_for_attribute_p (Node_Id gnat_node)
765 switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
767 case Attr_Pos:
768 case Attr_Val:
769 case Attr_Pred:
770 case Attr_Succ:
771 case Attr_First:
772 case Attr_Last:
773 case Attr_Range_Length:
774 case Attr_Length:
775 case Attr_Object_Size:
776 case Attr_Value_Size:
777 case Attr_Component_Size:
778 case Attr_Descriptor_Size:
779 case Attr_Max_Size_In_Storage_Elements:
780 case Attr_Min:
781 case Attr_Max:
782 case Attr_Null_Parameter:
783 case Attr_Passed_By_Reference:
784 case Attr_Mechanism_Code:
785 case Attr_Machine:
786 case Attr_Model:
787 return 0;
789 case Attr_Address:
790 case Attr_Access:
791 case Attr_Unchecked_Access:
792 case Attr_Unrestricted_Access:
793 case Attr_Code_Address:
794 case Attr_Pool_Address:
795 case Attr_Size:
796 case Attr_Alignment:
797 case Attr_Bit_Position:
798 case Attr_Position:
799 case Attr_First_Bit:
800 case Attr_Last_Bit:
801 case Attr_Bit:
802 case Attr_Asm_Input:
803 case Attr_Asm_Output:
804 default:
805 return 1;
809 /* Return a positive value if an lvalue is required for GNAT_NODE. GNU_TYPE
810 is the type that will be used for GNAT_NODE in the translated GNU tree.
811 CONSTANT indicates whether the underlying object represented by GNAT_NODE
812 is constant in the Ada sense. If it is, ADDRESS_OF_CONSTANT indicates
813 whether its value is the address of a constant and ALIASED whether it is
814 aliased. If it isn't, ADDRESS_OF_CONSTANT and ALIASED are ignored.
816 The function climbs up the GNAT tree starting from the node and returns 1
817 upon encountering a node that effectively requires an lvalue downstream.
818 It returns int instead of bool to facilitate usage in non-purely binary
819 logic contexts. */
821 static int
822 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
823 bool address_of_constant, bool aliased)
825 Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
827 switch (Nkind (gnat_parent))
829 case N_Reference:
830 return 1;
832 case N_Attribute_Reference:
833 return lvalue_required_for_attribute_p (gnat_parent);
835 case N_Parameter_Association:
836 case N_Function_Call:
837 case N_Procedure_Call_Statement:
838 /* If the parameter is by reference, an lvalue is required. */
839 return (!constant
840 || must_pass_by_ref (gnu_type)
841 || default_pass_by_ref (gnu_type));
843 case N_Indexed_Component:
844 /* Only the array expression can require an lvalue. */
845 if (Prefix (gnat_parent) != gnat_node)
846 return 0;
848 /* ??? Consider that referencing an indexed component with a
849 non-constant index forces the whole aggregate to memory.
850 Note that N_Integer_Literal is conservative, any static
851 expression in the RM sense could probably be accepted. */
852 for (gnat_temp = First (Expressions (gnat_parent));
853 Present (gnat_temp);
854 gnat_temp = Next (gnat_temp))
855 if (Nkind (gnat_temp) != N_Integer_Literal)
856 return 1;
858 /* ... fall through ... */
860 case N_Slice:
861 /* Only the array expression can require an lvalue. */
862 if (Prefix (gnat_parent) != gnat_node)
863 return 0;
865 aliased |= Has_Aliased_Components (Etype (gnat_node));
866 return lvalue_required_p (gnat_parent, gnu_type, constant,
867 address_of_constant, aliased);
869 case N_Selected_Component:
870 aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
871 return lvalue_required_p (gnat_parent, gnu_type, constant,
872 address_of_constant, aliased);
874 case N_Object_Renaming_Declaration:
875 /* We need to preserve addresses through a renaming. */
876 return 1;
878 case N_Object_Declaration:
879 /* We cannot use a constructor if this is an atomic object because
880 the actual assignment might end up being done component-wise. */
881 return (!constant
882 ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
883 && Is_Atomic (Defining_Entity (gnat_parent)))
884 /* We don't use a constructor if this is a class-wide object
885 because the effective type of the object is the equivalent
886 type of the class-wide subtype and it smashes most of the
887 data into an array of bytes to which we cannot convert. */
888 || Ekind ((Etype (Defining_Entity (gnat_parent))))
889 == E_Class_Wide_Subtype);
891 case N_Assignment_Statement:
892 /* We cannot use a constructor if the LHS is an atomic object because
893 the actual assignment might end up being done component-wise. */
894 return (!constant
895 || Name (gnat_parent) == gnat_node
896 || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
897 && Is_Atomic (Entity (Name (gnat_parent)))));
899 case N_Unchecked_Type_Conversion:
900 if (!constant)
901 return 1;
903 /* ... fall through ... */
905 case N_Type_Conversion:
906 case N_Qualified_Expression:
907 /* We must look through all conversions because we may need to bypass
908 an intermediate conversion that is meant to be purely formal. */
909 return lvalue_required_p (gnat_parent,
910 get_unpadded_type (Etype (gnat_parent)),
911 constant, address_of_constant, aliased);
913 case N_Allocator:
914 /* We should only reach here through the N_Qualified_Expression case.
915 Force an lvalue for composite types since a block-copy to the newly
916 allocated area of memory is made. */
917 return Is_Composite_Type (Underlying_Type (Etype (gnat_node)));
919 case N_Explicit_Dereference:
920 /* We look through dereferences for address of constant because we need
921 to handle the special cases listed above. */
922 if (constant && address_of_constant)
923 return lvalue_required_p (gnat_parent,
924 get_unpadded_type (Etype (gnat_parent)),
925 true, false, true);
927 /* ... fall through ... */
929 default:
930 return 0;
933 gcc_unreachable ();
936 /* Return true if T is a constant DECL node that can be safely replaced
937 by its initializer. */
939 static bool
940 constant_decl_with_initializer_p (tree t)
942 if (!TREE_CONSTANT (t) || !DECL_P (t) || !DECL_INITIAL (t))
943 return false;
945 /* Return false for aggregate types that contain a placeholder since
946 their initializers cannot be manipulated easily. */
947 if (AGGREGATE_TYPE_P (TREE_TYPE (t))
948 && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (t))
949 && type_contains_placeholder_p (TREE_TYPE (t)))
950 return false;
952 return true;
955 /* Return an expression equivalent to EXP but where constant DECL nodes
956 have been replaced by their initializer. */
958 static tree
959 fold_constant_decl_in_expr (tree exp)
961 enum tree_code code = TREE_CODE (exp);
962 tree op0;
964 switch (code)
966 case CONST_DECL:
967 case VAR_DECL:
968 if (!constant_decl_with_initializer_p (exp))
969 return exp;
971 return DECL_INITIAL (exp);
973 case BIT_FIELD_REF:
974 case COMPONENT_REF:
975 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
976 if (op0 == TREE_OPERAND (exp, 0))
977 return exp;
979 return fold_build3 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
980 TREE_OPERAND (exp, 2));
982 case ARRAY_REF:
983 case ARRAY_RANGE_REF:
984 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
985 if (op0 == TREE_OPERAND (exp, 0))
986 return exp;
988 return fold (build4 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
989 TREE_OPERAND (exp, 2), TREE_OPERAND (exp, 3)));
991 case VIEW_CONVERT_EXPR:
992 case REALPART_EXPR:
993 case IMAGPART_EXPR:
994 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
995 if (op0 == TREE_OPERAND (exp, 0))
996 return exp;
998 return fold_build1 (code, TREE_TYPE (exp), op0);
1000 default:
1001 return exp;
1004 gcc_unreachable ();
1007 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
1008 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer
1009 to where we should place the result type. */
1011 static tree
1012 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
1014 Node_Id gnat_temp, gnat_temp_type;
1015 tree gnu_result, gnu_result_type;
1017 /* Whether we should require an lvalue for GNAT_NODE. Needed in
1018 specific circumstances only, so evaluated lazily. < 0 means
1019 unknown, > 0 means known true, 0 means known false. */
1020 int require_lvalue = -1;
1022 /* If GNAT_NODE is a constant, whether we should use the initialization
1023 value instead of the constant entity, typically for scalars with an
1024 address clause when the parent doesn't require an lvalue. */
1025 bool use_constant_initializer = false;
1027 /* If the Etype of this node does not equal the Etype of the Entity,
1028 something is wrong with the entity map, probably in generic
1029 instantiation. However, this does not apply to types. Since we sometime
1030 have strange Ekind's, just do this test for objects. Also, if the Etype of
1031 the Entity is private, the Etype of the N_Identifier is allowed to be the
1032 full type and also we consider a packed array type to be the same as the
1033 original type. Similarly, a class-wide type is equivalent to a subtype of
1034 itself. Finally, if the types are Itypes, one may be a copy of the other,
1035 which is also legal. */
1036 gnat_temp = (Nkind (gnat_node) == N_Defining_Identifier
1037 ? gnat_node : Entity (gnat_node));
1038 gnat_temp_type = Etype (gnat_temp);
1040 gcc_assert (Etype (gnat_node) == gnat_temp_type
1041 || (Is_Packed (gnat_temp_type)
1042 && (Etype (gnat_node)
1043 == Packed_Array_Impl_Type (gnat_temp_type)))
1044 || (Is_Class_Wide_Type (Etype (gnat_node)))
1045 || (IN (Ekind (gnat_temp_type), Private_Kind)
1046 && Present (Full_View (gnat_temp_type))
1047 && ((Etype (gnat_node) == Full_View (gnat_temp_type))
1048 || (Is_Packed (Full_View (gnat_temp_type))
1049 && (Etype (gnat_node)
1050 == Packed_Array_Impl_Type
1051 (Full_View (gnat_temp_type))))))
1052 || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
1053 || !(Ekind (gnat_temp) == E_Variable
1054 || Ekind (gnat_temp) == E_Component
1055 || Ekind (gnat_temp) == E_Constant
1056 || Ekind (gnat_temp) == E_Loop_Parameter
1057 || IN (Ekind (gnat_temp), Formal_Kind)));
1059 /* If this is a reference to a deferred constant whose partial view is an
1060 unconstrained private type, the proper type is on the full view of the
1061 constant, not on the full view of the type, which may be unconstrained.
1063 This may be a reference to a type, for example in the prefix of the
1064 attribute Position, generated for dispatching code (see Make_DT in
1065 exp_disp,adb). In that case we need the type itself, not is parent,
1066 in particular if it is a derived type */
1067 if (Ekind (gnat_temp) == E_Constant
1068 && Is_Private_Type (gnat_temp_type)
1069 && (Has_Unknown_Discriminants (gnat_temp_type)
1070 || (Present (Full_View (gnat_temp_type))
1071 && Has_Discriminants (Full_View (gnat_temp_type))))
1072 && Present (Full_View (gnat_temp)))
1074 gnat_temp = Full_View (gnat_temp);
1075 gnat_temp_type = Etype (gnat_temp);
1077 else
1079 /* We want to use the Actual_Subtype if it has already been elaborated,
1080 otherwise the Etype. Avoid using Actual_Subtype for packed arrays to
1081 simplify things. */
1082 if ((Ekind (gnat_temp) == E_Constant
1083 || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
1084 && !(Is_Array_Type (Etype (gnat_temp))
1085 && Present (Packed_Array_Impl_Type (Etype (gnat_temp))))
1086 && Present (Actual_Subtype (gnat_temp))
1087 && present_gnu_tree (Actual_Subtype (gnat_temp)))
1088 gnat_temp_type = Actual_Subtype (gnat_temp);
1089 else
1090 gnat_temp_type = Etype (gnat_node);
1093 /* Expand the type of this identifier first, in case it is an enumeral
1094 literal, which only get made when the type is expanded. There is no
1095 order-of-elaboration issue here. */
1096 gnu_result_type = get_unpadded_type (gnat_temp_type);
1098 /* If this is a non-imported elementary constant with an address clause,
1099 retrieve the value instead of a pointer to be dereferenced unless
1100 an lvalue is required. This is generally more efficient and actually
1101 required if this is a static expression because it might be used
1102 in a context where a dereference is inappropriate, such as a case
1103 statement alternative or a record discriminant. There is no possible
1104 volatile-ness short-circuit here since Volatile constants must be
1105 imported per C.6. */
1106 if (Ekind (gnat_temp) == E_Constant
1107 && Is_Elementary_Type (gnat_temp_type)
1108 && !Is_Imported (gnat_temp)
1109 && Present (Address_Clause (gnat_temp)))
1111 require_lvalue = lvalue_required_p (gnat_node, gnu_result_type, true,
1112 false, Is_Aliased (gnat_temp));
1113 use_constant_initializer = !require_lvalue;
1116 if (use_constant_initializer)
1118 /* If this is a deferred constant, the initializer is attached to
1119 the full view. */
1120 if (Present (Full_View (gnat_temp)))
1121 gnat_temp = Full_View (gnat_temp);
1123 gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
1125 else
1126 gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
1128 /* Some objects (such as parameters passed by reference, globals of
1129 variable size, and renamed objects) actually represent the address
1130 of the object. In that case, we must do the dereference. Likewise,
1131 deal with parameters to foreign convention subprograms. */
1132 if (DECL_P (gnu_result)
1133 && (DECL_BY_REF_P (gnu_result)
1134 || (TREE_CODE (gnu_result) == PARM_DECL
1135 && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1137 const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1139 /* If it's a PARM_DECL to foreign convention subprogram, convert it. */
1140 if (TREE_CODE (gnu_result) == PARM_DECL
1141 && DECL_BY_COMPONENT_PTR_P (gnu_result))
1142 gnu_result
1143 = convert (build_pointer_type (gnu_result_type), gnu_result);
1145 /* If it's a CONST_DECL, return the underlying constant like below. */
1146 else if (TREE_CODE (gnu_result) == CONST_DECL
1147 && !(DECL_CONST_ADDRESS_P (gnu_result)
1148 && lvalue_required_p (gnat_node, gnu_result_type, true,
1149 true, false)))
1150 gnu_result = DECL_INITIAL (gnu_result);
1152 /* If it's a renaming pointer and, either the renamed object is constant
1153 or we are at the right binding level, we can reference the renamed
1154 object directly, since it is constant or has been protected against
1155 multiple evaluations. */
1156 if (TREE_CODE (gnu_result) == VAR_DECL
1157 && !DECL_LOOP_PARM_P (gnu_result)
1158 && DECL_RENAMED_OBJECT (gnu_result)
1159 && (TREE_CONSTANT (DECL_RENAMED_OBJECT (gnu_result))
1160 || !DECL_RENAMING_GLOBAL_P (gnu_result)
1161 || global_bindings_p ()))
1162 gnu_result = DECL_RENAMED_OBJECT (gnu_result);
1164 /* Otherwise, do the final dereference. */
1165 else
1167 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1169 if ((TREE_CODE (gnu_result) == INDIRECT_REF
1170 || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1171 && No (Address_Clause (gnat_temp)))
1172 TREE_THIS_NOTRAP (gnu_result) = 1;
1174 if (read_only)
1175 TREE_READONLY (gnu_result) = 1;
1179 /* If we have a constant declaration and its initializer, try to return the
1180 latter to avoid the need to call fold in lots of places and the need for
1181 elaboration code if this identifier is used as an initializer itself. */
1182 if (constant_decl_with_initializer_p (gnu_result))
1184 bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1185 && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1186 bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1187 && DECL_CONST_ADDRESS_P (gnu_result));
1189 /* If there is a (corresponding) variable or this is the address of a
1190 constant, we only want to return the initializer if an lvalue isn't
1191 required. Evaluate this now if we have not already done so. */
1192 if ((!constant_only || address_of_constant) && require_lvalue < 0)
1193 require_lvalue
1194 = lvalue_required_p (gnat_node, gnu_result_type, true,
1195 address_of_constant, Is_Aliased (gnat_temp));
1197 /* Finally retrieve the initializer if this is deemed valid. */
1198 if ((constant_only && !address_of_constant) || !require_lvalue)
1199 gnu_result = DECL_INITIAL (gnu_result);
1202 /* But for a constant renaming we couldn't do that incrementally for its
1203 definition because of the need to return an lvalue so, if the present
1204 context doesn't itself require an lvalue, we try again here. */
1205 else if (Ekind (gnat_temp) == E_Constant
1206 && Is_Elementary_Type (gnat_temp_type)
1207 && Present (Renamed_Object (gnat_temp)))
1209 if (require_lvalue < 0)
1210 require_lvalue
1211 = lvalue_required_p (gnat_node, gnu_result_type, true, false,
1212 Is_Aliased (gnat_temp));
1213 if (!require_lvalue)
1214 gnu_result = fold_constant_decl_in_expr (gnu_result);
1217 /* The GNAT tree has the type of a function set to its result type, so we
1218 adjust here. Also use the type of the result if the Etype is a subtype
1219 that is nominally unconstrained. Likewise if this is a deferred constant
1220 of a discriminated type whose full view can be elaborated statically, to
1221 avoid problematic conversions to the nominal subtype. But remove any
1222 padding from the resulting type. */
1223 if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
1224 || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type)
1225 || (Ekind (gnat_temp) == E_Constant
1226 && Present (Full_View (gnat_temp))
1227 && Has_Discriminants (gnat_temp_type)
1228 && TREE_CODE (gnu_result) == CONSTRUCTOR))
1230 gnu_result_type = TREE_TYPE (gnu_result);
1231 if (TYPE_IS_PADDING_P (gnu_result_type))
1232 gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1235 *gnu_result_type_p = gnu_result_type;
1237 return gnu_result;
1240 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma. Return
1241 any statements we generate. */
1243 static tree
1244 Pragma_to_gnu (Node_Id gnat_node)
1246 tree gnu_result = alloc_stmt_list ();
1247 unsigned char pragma_id;
1248 Node_Id gnat_temp;
1250 /* Do nothing if we are just annotating types and check for (and ignore)
1251 unrecognized pragmas. */
1252 if (type_annotate_only
1253 || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1254 return gnu_result;
1256 pragma_id = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
1257 switch (pragma_id)
1259 case Pragma_Inspection_Point:
1260 /* Do nothing at top level: all such variables are already viewable. */
1261 if (global_bindings_p ())
1262 break;
1264 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1265 Present (gnat_temp);
1266 gnat_temp = Next (gnat_temp))
1268 Node_Id gnat_expr = Expression (gnat_temp);
1269 tree gnu_expr = gnat_to_gnu (gnat_expr);
1270 int use_address;
1271 machine_mode mode;
1272 tree asm_constraint = NULL_TREE;
1273 #ifdef ASM_COMMENT_START
1274 char *comment;
1275 #endif
1277 if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
1278 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1280 /* Use the value only if it fits into a normal register,
1281 otherwise use the address. */
1282 mode = TYPE_MODE (TREE_TYPE (gnu_expr));
1283 use_address = ((GET_MODE_CLASS (mode) != MODE_INT
1284 && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
1285 || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
1287 if (use_address)
1288 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
1290 #ifdef ASM_COMMENT_START
1291 comment = concat (ASM_COMMENT_START,
1292 " inspection point: ",
1293 Get_Name_String (Chars (gnat_expr)),
1294 use_address ? " address" : "",
1295 " is in %0",
1296 NULL);
1297 asm_constraint = build_string (strlen (comment), comment);
1298 free (comment);
1299 #endif
1300 gnu_expr = build5 (ASM_EXPR, void_type_node,
1301 asm_constraint,
1302 NULL_TREE,
1303 tree_cons
1304 (build_tree_list (NULL_TREE,
1305 build_string (1, "g")),
1306 gnu_expr, NULL_TREE),
1307 NULL_TREE, NULL_TREE);
1308 ASM_VOLATILE_P (gnu_expr) = 1;
1309 set_expr_location_from_node (gnu_expr, gnat_node);
1310 append_to_statement_list (gnu_expr, &gnu_result);
1312 break;
1314 case Pragma_Loop_Optimize:
1315 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1316 Present (gnat_temp);
1317 gnat_temp = Next (gnat_temp))
1319 tree gnu_loop_stmt = gnu_loop_stack->last ()->stmt;
1321 switch (Chars (Expression (gnat_temp)))
1323 case Name_Ivdep:
1324 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
1325 break;
1327 case Name_No_Unroll:
1328 LOOP_STMT_NO_UNROLL (gnu_loop_stmt) = 1;
1329 break;
1331 case Name_Unroll:
1332 LOOP_STMT_UNROLL (gnu_loop_stmt) = 1;
1333 break;
1335 case Name_No_Vector:
1336 LOOP_STMT_NO_VECTOR (gnu_loop_stmt) = 1;
1337 break;
1339 case Name_Vector:
1340 LOOP_STMT_VECTOR (gnu_loop_stmt) = 1;
1341 break;
1343 default:
1344 gcc_unreachable ();
1347 break;
1349 case Pragma_Optimize:
1350 switch (Chars (Expression
1351 (First (Pragma_Argument_Associations (gnat_node)))))
1353 case Name_Off:
1354 if (optimize)
1355 post_error ("must specify -O0?", gnat_node);
1356 break;
1358 case Name_Space:
1359 if (!optimize_size)
1360 post_error ("must specify -Os?", gnat_node);
1361 break;
1363 case Name_Time:
1364 if (!optimize)
1365 post_error ("insufficient -O value?", gnat_node);
1366 break;
1368 default:
1369 gcc_unreachable ();
1371 break;
1373 case Pragma_Reviewable:
1374 if (write_symbols == NO_DEBUG)
1375 post_error ("must specify -g?", gnat_node);
1376 break;
1378 case Pragma_Warning_As_Error:
1379 case Pragma_Warnings:
1381 Node_Id gnat_expr;
1382 /* Preserve the location of the pragma. */
1383 const location_t location = input_location;
1384 struct cl_option_handlers handlers;
1385 unsigned int option_index;
1386 diagnostic_t kind;
1387 bool imply;
1389 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1391 /* This is the String form: pragma Warning{s|_As_Error}(String). */
1392 if (Nkind (Expression (gnat_temp)) == N_String_Literal)
1394 switch (pragma_id)
1396 case Pragma_Warning_As_Error:
1397 kind = DK_ERROR;
1398 imply = false;
1399 break;
1401 case Pragma_Warnings:
1402 kind = DK_WARNING;
1403 imply = true;
1404 break;
1406 default:
1407 gcc_unreachable ();
1410 gnat_expr = Expression (gnat_temp);
1413 /* This is the On/Off form: pragma Warnings (On | Off [,String]). */
1414 else if (Nkind (Expression (gnat_temp)) == N_Identifier)
1416 switch (Chars (Expression (gnat_temp)))
1418 case Name_Off:
1419 kind = DK_IGNORED;
1420 break;
1422 case Name_On:
1423 kind = DK_WARNING;
1424 break;
1426 default:
1427 gcc_unreachable ();
1430 /* Deal with optional pattern (but ignore Reason => "..."). */
1431 if (Present (Next (gnat_temp)) && No (Chars (Next (gnat_temp))))
1433 /* pragma Warnings (On | Off, Name) is handled differently. */
1434 if (Nkind (Expression (Next (gnat_temp))) != N_String_Literal)
1435 break;
1437 gnat_expr = Expression (Next (gnat_temp));
1439 else
1440 gnat_expr = Empty;
1442 imply = false;
1445 else
1446 gcc_unreachable ();
1448 /* This is the same implementation as in the C family of compilers. */
1449 if (Present (gnat_expr))
1451 tree gnu_expr = gnat_to_gnu (gnat_expr);
1452 const char *opt_string = TREE_STRING_POINTER (gnu_expr);
1453 const int len = TREE_STRING_LENGTH (gnu_expr);
1454 if (len < 3 || opt_string[0] != '-' || opt_string[1] != 'W')
1455 break;
1456 for (option_index = 0;
1457 option_index < cl_options_count;
1458 option_index++)
1459 if (strcmp (cl_options[option_index].opt_text, opt_string) == 0)
1460 break;
1461 if (option_index == cl_options_count)
1463 post_error ("unknown -W switch", gnat_node);
1464 break;
1467 else
1468 option_index = 0;
1470 set_default_handlers (&handlers);
1471 control_warning_option (option_index, (int) kind, imply, location,
1472 CL_Ada, &handlers, &global_options,
1473 &global_options_set, global_dc);
1475 break;
1477 default:
1478 break;
1481 return gnu_result;
1484 /* Return an expression for the length of TYPE, an integral type, computed in
1485 RESULT_TYPE, another integral type.
1487 We used to compute the length as MAX (hb - lb + 1, 0) which could overflow
1488 when lb == TYPE'First. We now compute it as (hb >= lb) ? hb - lb + 1 : 0
1489 which would only overflow in much rarer cases, for extremely large arrays
1490 we expect never to encounter in practice. Besides, the former computation
1491 required the use of potentially constraining signed arithmetics while the
1492 latter does not. Note that the comparison must be done in the original
1493 base index type in order to avoid any overflow during the conversion. */
1495 static tree
1496 get_type_length (tree type, tree result_type)
1498 tree comp_type = get_base_type (result_type);
1499 tree base_type = get_base_type (type);
1500 tree lb = convert (base_type, TYPE_MIN_VALUE (type));
1501 tree hb = convert (base_type, TYPE_MAX_VALUE (type));
1502 tree length
1503 = build_binary_op (PLUS_EXPR, comp_type,
1504 build_binary_op (MINUS_EXPR, comp_type,
1505 convert (comp_type, hb),
1506 convert (comp_type, lb)),
1507 convert (comp_type, integer_one_node));
1508 length
1509 = build_cond_expr (result_type,
1510 build_binary_op (GE_EXPR, boolean_type_node, hb, lb),
1511 convert (result_type, length),
1512 convert (result_type, integer_zero_node));
1513 return length;
1516 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
1517 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to
1518 where we should place the result type. ATTRIBUTE is the attribute ID. */
1520 static tree
1521 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1523 const Node_Id gnat_prefix = Prefix (gnat_node);
1524 tree gnu_prefix, gnu_type, gnu_expr;
1525 tree gnu_result_type, gnu_result = error_mark_node;
1526 bool prefix_unused = false;
1528 /* ??? If this is an access attribute for a public subprogram to be used in
1529 a dispatch table, do not translate its type as it's useless there and the
1530 parameter types might be incomplete types coming from a limited with. */
1531 if (Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
1532 && Is_Dispatch_Table_Entity (Etype (gnat_node))
1533 && Nkind (gnat_prefix) == N_Identifier
1534 && Is_Subprogram (Entity (gnat_prefix))
1535 && Is_Public (Entity (gnat_prefix))
1536 && !present_gnu_tree (Entity (gnat_prefix)))
1537 gnu_prefix = get_minimal_subprog_decl (Entity (gnat_prefix));
1538 else
1539 gnu_prefix = gnat_to_gnu (gnat_prefix);
1540 gnu_type = TREE_TYPE (gnu_prefix);
1542 /* If the input is a NULL_EXPR, make a new one. */
1543 if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1545 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1546 *gnu_result_type_p = gnu_result_type;
1547 return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1550 switch (attribute)
1552 case Attr_Pos:
1553 case Attr_Val:
1554 /* These are just conversions since representation clauses for
1555 enumeration types are handled in the front-end. */
1557 bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
1558 gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
1559 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1560 gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
1561 checkp, checkp, true, gnat_node);
1563 break;
1565 case Attr_Pred:
1566 case Attr_Succ:
1567 /* These just add or subtract the constant 1 since representation
1568 clauses for enumeration types are handled in the front-end. */
1569 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1570 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1572 if (Do_Range_Check (First (Expressions (gnat_node))))
1574 gnu_expr = gnat_protect_expr (gnu_expr);
1575 gnu_expr
1576 = emit_check
1577 (build_binary_op (EQ_EXPR, boolean_type_node,
1578 gnu_expr,
1579 attribute == Attr_Pred
1580 ? TYPE_MIN_VALUE (gnu_result_type)
1581 : TYPE_MAX_VALUE (gnu_result_type)),
1582 gnu_expr, CE_Range_Check_Failed, gnat_node);
1585 gnu_result
1586 = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1587 gnu_result_type, gnu_expr,
1588 convert (gnu_result_type, integer_one_node));
1589 break;
1591 case Attr_Address:
1592 case Attr_Unrestricted_Access:
1593 /* Conversions don't change addresses but can cause us to miss the
1594 COMPONENT_REF case below, so strip them off. */
1595 gnu_prefix = remove_conversions (gnu_prefix,
1596 !Must_Be_Byte_Aligned (gnat_node));
1598 /* If we are taking 'Address of an unconstrained object, this is the
1599 pointer to the underlying array. */
1600 if (attribute == Attr_Address)
1601 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1603 /* If we are building a static dispatch table, we have to honor
1604 TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1605 with the C++ ABI. We do it in the non-static case as well,
1606 see gnat_to_gnu_entity, case E_Access_Subprogram_Type. */
1607 else if (TARGET_VTABLE_USES_DESCRIPTORS
1608 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1610 tree gnu_field, t;
1611 /* Descriptors can only be built here for top-level functions. */
1612 bool build_descriptor = (global_bindings_p () != 0);
1613 int i;
1614 vec<constructor_elt, va_gc> *gnu_vec = NULL;
1615 constructor_elt *elt;
1617 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1619 /* If we're not going to build the descriptor, we have to retrieve
1620 the one which will be built by the linker (or by the compiler
1621 later if a static chain is requested). */
1622 if (!build_descriptor)
1624 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1625 gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1626 gnu_result);
1627 gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1630 vec_safe_grow (gnu_vec, TARGET_VTABLE_USES_DESCRIPTORS);
1631 elt = (gnu_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
1632 for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1633 i < TARGET_VTABLE_USES_DESCRIPTORS;
1634 gnu_field = DECL_CHAIN (gnu_field), i++)
1636 if (build_descriptor)
1638 t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1639 build_int_cst (NULL_TREE, i));
1640 TREE_CONSTANT (t) = 1;
1642 else
1643 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1644 gnu_field, NULL_TREE);
1646 elt->index = gnu_field;
1647 elt->value = t;
1648 elt--;
1651 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
1652 break;
1655 /* ... fall through ... */
1657 case Attr_Access:
1658 case Attr_Unchecked_Access:
1659 case Attr_Code_Address:
1660 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1661 gnu_result
1662 = build_unary_op (((attribute == Attr_Address
1663 || attribute == Attr_Unrestricted_Access)
1664 && !Must_Be_Byte_Aligned (gnat_node))
1665 ? ATTR_ADDR_EXPR : ADDR_EXPR,
1666 gnu_result_type, gnu_prefix);
1668 /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1669 don't try to build a trampoline. */
1670 if (attribute == Attr_Code_Address)
1672 gnu_expr = remove_conversions (gnu_result, false);
1674 if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1675 TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1678 /* For 'Access, issue an error message if the prefix is a C++ method
1679 since it can use a special calling convention on some platforms,
1680 which cannot be propagated to the access type. */
1681 else if (attribute == Attr_Access
1682 && Nkind (gnat_prefix) == N_Identifier
1683 && is_cplusplus_method (Entity (gnat_prefix)))
1684 post_error ("access to C++ constructor or member function not allowed",
1685 gnat_node);
1687 /* For other address attributes applied to a nested function,
1688 find an inner ADDR_EXPR and annotate it so that we can issue
1689 a useful warning with -Wtrampolines. */
1690 else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
1692 gnu_expr = remove_conversions (gnu_result, false);
1694 if (TREE_CODE (gnu_expr) == ADDR_EXPR
1695 && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1697 set_expr_location_from_node (gnu_expr, gnat_node);
1699 /* Check that we're not violating the No_Implicit_Dynamic_Code
1700 restriction. Be conservative if we don't know anything
1701 about the trampoline strategy for the target. */
1702 Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1705 break;
1707 case Attr_Pool_Address:
1709 tree gnu_ptr = gnu_prefix;
1710 tree gnu_obj_type;
1712 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1714 /* If this is fat pointer, the object must have been allocated with the
1715 template in front of the array. So compute the template address; do
1716 it by converting to a thin pointer. */
1717 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1718 gnu_ptr
1719 = convert (build_pointer_type
1720 (TYPE_OBJECT_RECORD_TYPE
1721 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1722 gnu_ptr);
1724 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1726 /* If this is a thin pointer, the object must have been allocated with
1727 the template in front of the array. So compute the template address
1728 and return it. */
1729 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
1730 gnu_ptr
1731 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
1732 gnu_ptr,
1733 fold_build1 (NEGATE_EXPR, sizetype,
1734 byte_position
1735 (DECL_CHAIN
1736 TYPE_FIELDS ((gnu_obj_type)))));
1738 gnu_result = convert (gnu_result_type, gnu_ptr);
1740 break;
1742 case Attr_Size:
1743 case Attr_Object_Size:
1744 case Attr_Value_Size:
1745 case Attr_Max_Size_In_Storage_Elements:
1746 gnu_expr = gnu_prefix;
1748 /* Remove NOPs and conversions between original and packable version
1749 from GNU_EXPR, and conversions from GNU_PREFIX. We use GNU_EXPR
1750 to see if a COMPONENT_REF was involved. */
1751 while (TREE_CODE (gnu_expr) == NOP_EXPR
1752 || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
1753 && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1754 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
1755 == RECORD_TYPE
1756 && TYPE_NAME (TREE_TYPE (gnu_expr))
1757 == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
1758 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1760 gnu_prefix = remove_conversions (gnu_prefix, true);
1761 prefix_unused = true;
1762 gnu_type = TREE_TYPE (gnu_prefix);
1764 /* Replace an unconstrained array type with the type of the underlying
1765 array. We can't do this with a call to maybe_unconstrained_array
1766 since we may have a TYPE_DECL. For 'Max_Size_In_Storage_Elements,
1767 use the record type that will be used to allocate the object and its
1768 template. */
1769 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1771 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1772 if (attribute != Attr_Max_Size_In_Storage_Elements)
1773 gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
1776 /* If we're looking for the size of a field, return the field size. */
1777 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1778 gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1780 /* Otherwise, if the prefix is an object, or if we are looking for
1781 'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1782 GCC size of the type. We make an exception for padded objects,
1783 as we do not take into account alignment promotions for the size.
1784 This is in keeping with the object case of gnat_to_gnu_entity. */
1785 else if ((TREE_CODE (gnu_prefix) != TYPE_DECL
1786 && !(TYPE_IS_PADDING_P (gnu_type)
1787 && TREE_CODE (gnu_expr) == COMPONENT_REF))
1788 || attribute == Attr_Object_Size
1789 || attribute == Attr_Max_Size_In_Storage_Elements)
1791 /* If this is a dereference and we have a special dynamic constrained
1792 subtype on the prefix, use it to compute the size; otherwise, use
1793 the designated subtype. */
1794 if (Nkind (gnat_prefix) == N_Explicit_Dereference)
1796 Node_Id gnat_actual_subtype
1797 = Actual_Designated_Subtype (gnat_prefix);
1798 tree gnu_ptr_type
1799 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_prefix)));
1801 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1802 && Present (gnat_actual_subtype))
1804 tree gnu_actual_obj_type
1805 = gnat_to_gnu_type (gnat_actual_subtype);
1806 gnu_type
1807 = build_unc_object_type_from_ptr (gnu_ptr_type,
1808 gnu_actual_obj_type,
1809 get_identifier ("SIZE"),
1810 false);
1814 gnu_result = TYPE_SIZE (gnu_type);
1817 /* Otherwise, the result is the RM size of the type. */
1818 else
1819 gnu_result = rm_size (gnu_type);
1821 /* Deal with a self-referential size by returning the maximum size for
1822 a type and by qualifying the size with the object otherwise. */
1823 if (CONTAINS_PLACEHOLDER_P (gnu_result))
1825 if (TREE_CODE (gnu_prefix) == TYPE_DECL)
1826 gnu_result = max_size (gnu_result, true);
1827 else
1828 gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1831 /* If the type contains a template, subtract its size. */
1832 if (TREE_CODE (gnu_type) == RECORD_TYPE
1833 && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1834 gnu_result = size_binop (MINUS_EXPR, gnu_result,
1835 DECL_SIZE (TYPE_FIELDS (gnu_type)));
1837 /* For 'Max_Size_In_Storage_Elements, adjust the unit. */
1838 if (attribute == Attr_Max_Size_In_Storage_Elements)
1839 gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
1841 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1842 break;
1844 case Attr_Alignment:
1846 unsigned int align;
1848 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1849 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1850 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1852 gnu_type = TREE_TYPE (gnu_prefix);
1853 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1854 prefix_unused = true;
1856 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1857 align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
1858 else
1860 Entity_Id gnat_type = Etype (gnat_prefix);
1861 unsigned int double_align;
1862 bool is_capped_double, align_clause;
1864 /* If the default alignment of "double" or larger scalar types is
1865 specifically capped and there is an alignment clause neither
1866 on the type nor on the prefix itself, return the cap. */
1867 if ((double_align = double_float_alignment) > 0)
1868 is_capped_double
1869 = is_double_float_or_array (gnat_type, &align_clause);
1870 else if ((double_align = double_scalar_alignment) > 0)
1871 is_capped_double
1872 = is_double_scalar_or_array (gnat_type, &align_clause);
1873 else
1874 is_capped_double = align_clause = false;
1876 if (is_capped_double
1877 && Nkind (gnat_prefix) == N_Identifier
1878 && Present (Alignment_Clause (Entity (gnat_prefix))))
1879 align_clause = true;
1881 if (is_capped_double && !align_clause)
1882 align = double_align;
1883 else
1884 align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
1887 gnu_result = size_int (align);
1889 break;
1891 case Attr_First:
1892 case Attr_Last:
1893 case Attr_Range_Length:
1894 prefix_unused = true;
1896 if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1898 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1900 if (attribute == Attr_First)
1901 gnu_result = TYPE_MIN_VALUE (gnu_type);
1902 else if (attribute == Attr_Last)
1903 gnu_result = TYPE_MAX_VALUE (gnu_type);
1904 else
1905 gnu_result = get_type_length (gnu_type, gnu_result_type);
1906 break;
1909 /* ... fall through ... */
1911 case Attr_Length:
1913 int Dimension = (Present (Expressions (gnat_node))
1914 ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1915 : 1), i;
1916 struct parm_attr_d *pa = NULL;
1917 Entity_Id gnat_param = Empty;
1918 bool unconstrained_ptr_deref = false;
1920 /* Make sure any implicit dereference gets done. */
1921 gnu_prefix = maybe_implicit_deref (gnu_prefix);
1922 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1924 /* We treat unconstrained array In parameters specially. We also note
1925 whether we are dereferencing a pointer to unconstrained array. */
1926 if (!Is_Constrained (Etype (gnat_prefix)))
1927 switch (Nkind (gnat_prefix))
1929 case N_Identifier:
1930 /* This is the direct case. */
1931 if (Ekind (Entity (gnat_prefix)) == E_In_Parameter)
1932 gnat_param = Entity (gnat_prefix);
1933 break;
1935 case N_Explicit_Dereference:
1936 /* This is the indirect case. Note that we need to be sure that
1937 the access value cannot be null as we'll hoist the load. */
1938 if (Nkind (Prefix (gnat_prefix)) == N_Identifier
1939 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter)
1941 if (Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
1942 gnat_param = Entity (Prefix (gnat_prefix));
1944 else
1945 unconstrained_ptr_deref = true;
1946 break;
1948 default:
1949 break;
1952 /* If the prefix is the view conversion of a constrained array to an
1953 unconstrained form, we retrieve the constrained array because we
1954 might not be able to substitute the PLACEHOLDER_EXPR coming from
1955 the conversion. This can occur with the 'Old attribute applied
1956 to a parameter with an unconstrained type, which gets rewritten
1957 into a constrained local variable very late in the game. */
1958 if (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
1959 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (gnu_prefix)))
1960 && !CONTAINS_PLACEHOLDER_P
1961 (TYPE_SIZE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
1962 gnu_type = TREE_TYPE (TREE_OPERAND (gnu_prefix, 0));
1963 else
1964 gnu_type = TREE_TYPE (gnu_prefix);
1966 prefix_unused = true;
1967 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1969 if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
1971 int ndim;
1972 tree gnu_type_temp;
1974 for (ndim = 1, gnu_type_temp = gnu_type;
1975 TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
1976 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
1977 ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
1980 Dimension = ndim + 1 - Dimension;
1983 for (i = 1; i < Dimension; i++)
1984 gnu_type = TREE_TYPE (gnu_type);
1986 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1988 /* When not optimizing, look up the slot associated with the parameter
1989 and the dimension in the cache and create a new one on failure.
1990 Don't do this when the actual subtype needs debug info (this happens
1991 with -gnatD): in elaborate_expression_1, we create variables that
1992 hold the bounds, so caching attributes isn't very interesting and
1993 causes dependency issues between these variables and cached
1994 expressions. */
1995 if (!optimize
1996 && Present (gnat_param)
1997 && !(Present (Actual_Subtype (gnat_param))
1998 && Needs_Debug_Info (Actual_Subtype (gnat_param))))
2000 FOR_EACH_VEC_SAFE_ELT (f_parm_attr_cache, i, pa)
2001 if (pa->id == gnat_param && pa->dim == Dimension)
2002 break;
2004 if (!pa)
2006 pa = ggc_cleared_alloc<parm_attr_d> ();
2007 pa->id = gnat_param;
2008 pa->dim = Dimension;
2009 vec_safe_push (f_parm_attr_cache, pa);
2013 /* Return the cached expression or build a new one. */
2014 if (attribute == Attr_First)
2016 if (pa && pa->first)
2018 gnu_result = pa->first;
2019 break;
2022 gnu_result
2023 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2026 else if (attribute == Attr_Last)
2028 if (pa && pa->last)
2030 gnu_result = pa->last;
2031 break;
2034 gnu_result
2035 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2038 else /* attribute == Attr_Range_Length || attribute == Attr_Length */
2040 if (pa && pa->length)
2042 gnu_result = pa->length;
2043 break;
2046 gnu_result
2047 = get_type_length (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)),
2048 gnu_result_type);
2051 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2052 handling. Note that these attributes could not have been used on
2053 an unconstrained array type. */
2054 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2056 /* Cache the expression we have just computed. Since we want to do it
2057 at run time, we force the use of a SAVE_EXPR and let the gimplifier
2058 create the temporary in the outermost binding level. We will make
2059 sure in Subprogram_Body_to_gnu that it is evaluated on all possible
2060 paths by forcing its evaluation on entry of the function. */
2061 if (pa)
2063 gnu_result
2064 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2065 switch (attribute)
2067 case Attr_First:
2068 pa->first = gnu_result;
2069 break;
2071 case Attr_Last:
2072 pa->last = gnu_result;
2073 break;
2075 case Attr_Length:
2076 case Attr_Range_Length:
2077 pa->length = gnu_result;
2078 break;
2080 default:
2081 gcc_unreachable ();
2085 /* Otherwise, evaluate it each time it is referenced. */
2086 else
2087 switch (attribute)
2089 case Attr_First:
2090 case Attr_Last:
2091 /* If we are dereferencing a pointer to unconstrained array, we
2092 need to capture the value because the pointed-to bounds may
2093 subsequently be released. */
2094 if (unconstrained_ptr_deref)
2095 gnu_result
2096 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2097 break;
2099 case Attr_Length:
2100 case Attr_Range_Length:
2101 /* Set the source location onto the predicate of the condition
2102 but not if the expression is cached to avoid messing up the
2103 debug info. */
2104 if (TREE_CODE (gnu_result) == COND_EXPR
2105 && EXPR_P (TREE_OPERAND (gnu_result, 0)))
2106 set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
2107 gnat_node);
2108 break;
2110 default:
2111 gcc_unreachable ();
2114 break;
2117 case Attr_Bit_Position:
2118 case Attr_Position:
2119 case Attr_First_Bit:
2120 case Attr_Last_Bit:
2121 case Attr_Bit:
2123 HOST_WIDE_INT bitsize;
2124 HOST_WIDE_INT bitpos;
2125 tree gnu_offset;
2126 tree gnu_field_bitpos;
2127 tree gnu_field_offset;
2128 tree gnu_inner;
2129 machine_mode mode;
2130 int unsignedp, reversep, volatilep;
2132 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2133 gnu_prefix = remove_conversions (gnu_prefix, true);
2134 prefix_unused = true;
2136 /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
2137 the result is 0. Don't allow 'Bit on a bare component, though. */
2138 if (attribute == Attr_Bit
2139 && TREE_CODE (gnu_prefix) != COMPONENT_REF
2140 && TREE_CODE (gnu_prefix) != FIELD_DECL)
2142 gnu_result = integer_zero_node;
2143 break;
2146 else
2147 gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
2148 || (attribute == Attr_Bit_Position
2149 && TREE_CODE (gnu_prefix) == FIELD_DECL));
2151 get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
2152 &mode, &unsignedp, &reversep, &volatilep, false);
2154 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2156 gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
2157 gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
2159 for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
2160 TREE_CODE (gnu_inner) == COMPONENT_REF
2161 && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
2162 gnu_inner = TREE_OPERAND (gnu_inner, 0))
2164 gnu_field_bitpos
2165 = size_binop (PLUS_EXPR, gnu_field_bitpos,
2166 bit_position (TREE_OPERAND (gnu_inner, 1)));
2167 gnu_field_offset
2168 = size_binop (PLUS_EXPR, gnu_field_offset,
2169 byte_position (TREE_OPERAND (gnu_inner, 1)));
2172 else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
2174 gnu_field_bitpos = bit_position (gnu_prefix);
2175 gnu_field_offset = byte_position (gnu_prefix);
2177 else
2179 gnu_field_bitpos = bitsize_zero_node;
2180 gnu_field_offset = size_zero_node;
2183 switch (attribute)
2185 case Attr_Position:
2186 gnu_result = gnu_field_offset;
2187 break;
2189 case Attr_First_Bit:
2190 case Attr_Bit:
2191 gnu_result = size_int (bitpos % BITS_PER_UNIT);
2192 break;
2194 case Attr_Last_Bit:
2195 gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
2196 gnu_result = size_binop (PLUS_EXPR, gnu_result,
2197 TYPE_SIZE (TREE_TYPE (gnu_prefix)));
2198 /* ??? Avoid a large unsigned result that will overflow when
2199 converted to the signed universal_integer. */
2200 if (integer_zerop (gnu_result))
2201 gnu_result = integer_minus_one_node;
2202 else
2203 gnu_result
2204 = size_binop (MINUS_EXPR, gnu_result, bitsize_one_node);
2205 break;
2207 case Attr_Bit_Position:
2208 gnu_result = gnu_field_bitpos;
2209 break;
2212 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2213 handling. */
2214 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2215 break;
2218 case Attr_Min:
2219 case Attr_Max:
2221 tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
2222 tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
2224 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2225 gnu_result = build_binary_op (attribute == Attr_Min
2226 ? MIN_EXPR : MAX_EXPR,
2227 gnu_result_type, gnu_lhs, gnu_rhs);
2229 break;
2231 case Attr_Passed_By_Reference:
2232 gnu_result = size_int (default_pass_by_ref (gnu_type)
2233 || must_pass_by_ref (gnu_type));
2234 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2235 break;
2237 case Attr_Component_Size:
2238 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2239 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2240 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2242 gnu_prefix = maybe_implicit_deref (gnu_prefix);
2243 gnu_type = TREE_TYPE (gnu_prefix);
2245 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2246 gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
2248 while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
2249 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
2250 gnu_type = TREE_TYPE (gnu_type);
2252 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2254 /* Note this size cannot be self-referential. */
2255 gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
2256 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2257 prefix_unused = true;
2258 break;
2260 case Attr_Descriptor_Size:
2261 gnu_type = TREE_TYPE (gnu_prefix);
2262 gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
2264 /* What we want is the offset of the ARRAY field in the record
2265 that the thin pointer designates. */
2266 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2267 gnu_result = bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2268 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2269 prefix_unused = true;
2270 break;
2272 case Attr_Null_Parameter:
2273 /* This is just a zero cast to the pointer type for our prefix and
2274 dereferenced. */
2275 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2276 gnu_result
2277 = build_unary_op (INDIRECT_REF, NULL_TREE,
2278 convert (build_pointer_type (gnu_result_type),
2279 integer_zero_node));
2280 TREE_PRIVATE (gnu_result) = 1;
2281 break;
2283 case Attr_Mechanism_Code:
2285 Entity_Id gnat_obj = Entity (gnat_prefix);
2286 int code;
2288 prefix_unused = true;
2289 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2290 if (Present (Expressions (gnat_node)))
2292 int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
2294 for (gnat_obj = First_Formal (gnat_obj); i > 1;
2295 i--, gnat_obj = Next_Formal (gnat_obj))
2299 code = Mechanism (gnat_obj);
2300 if (code == Default)
2301 code = ((present_gnu_tree (gnat_obj)
2302 && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
2303 || ((TREE_CODE (get_gnu_tree (gnat_obj))
2304 == PARM_DECL)
2305 && (DECL_BY_COMPONENT_PTR_P
2306 (get_gnu_tree (gnat_obj))))))
2307 ? By_Reference : By_Copy);
2308 gnu_result = convert (gnu_result_type, size_int (- code));
2310 break;
2312 case Attr_Model:
2313 /* We treat Model as identical to Machine. This is true for at least
2314 IEEE and some other nice floating-point systems. */
2316 /* ... fall through ... */
2318 case Attr_Machine:
2319 /* The trick is to force the compiler to store the result in memory so
2320 that we do not have extra precision used. But do this only when this
2321 is necessary, i.e. if FP_ARITH_MAY_WIDEN is true and the precision of
2322 the type is lower than that of the longest floating-point type. */
2323 prefix_unused = true;
2324 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2325 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2326 gnu_result = convert (gnu_result_type, gnu_expr);
2328 if (fp_arith_may_widen
2329 && TYPE_PRECISION (gnu_result_type)
2330 < TYPE_PRECISION (longest_float_type_node))
2332 tree rec_type = make_node (RECORD_TYPE);
2333 tree field
2334 = create_field_decl (get_identifier ("OBJ"), gnu_result_type,
2335 rec_type, NULL_TREE, NULL_TREE, 0, 0);
2336 tree rec_val, asm_expr;
2338 finish_record_type (rec_type, field, 0, false);
2340 rec_val = build_constructor_single (rec_type, field, gnu_result);
2341 rec_val = save_expr (rec_val);
2343 asm_expr
2344 = build5 (ASM_EXPR, void_type_node,
2345 build_string (0, ""),
2346 tree_cons (build_tree_list (NULL_TREE,
2347 build_string (2, "=m")),
2348 rec_val, NULL_TREE),
2349 tree_cons (build_tree_list (NULL_TREE,
2350 build_string (1, "m")),
2351 rec_val, NULL_TREE),
2352 NULL_TREE, NULL_TREE);
2353 ASM_VOLATILE_P (asm_expr) = 1;
2355 gnu_result
2356 = build_compound_expr (gnu_result_type, asm_expr,
2357 build_component_ref (rec_val, NULL_TREE,
2358 field, false));
2360 break;
2362 default:
2363 /* This abort means that we have an unimplemented attribute. */
2364 gcc_unreachable ();
2367 /* If this is an attribute where the prefix was unused, force a use of it if
2368 it has a side-effect. But don't do it if the prefix is just an entity
2369 name. However, if an access check is needed, we must do it. See second
2370 example in AARM 11.6(5.e). */
2371 if (prefix_unused
2372 && TREE_SIDE_EFFECTS (gnu_prefix)
2373 && !Is_Entity_Name (gnat_prefix))
2374 gnu_result
2375 = build_compound_expr (TREE_TYPE (gnu_result), gnu_prefix, gnu_result);
2377 *gnu_result_type_p = gnu_result_type;
2378 return gnu_result;
2381 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
2382 to a GCC tree, which is returned. */
2384 static tree
2385 Case_Statement_to_gnu (Node_Id gnat_node)
2387 tree gnu_result, gnu_expr, gnu_label;
2388 Node_Id gnat_when;
2389 location_t end_locus;
2390 bool may_fallthru = false;
2392 gnu_expr = gnat_to_gnu (Expression (gnat_node));
2393 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2395 /* The range of values in a case statement is determined by the rules in
2396 RM 5.4(7-9). In almost all cases, this range is represented by the Etype
2397 of the expression. One exception arises in the case of a simple name that
2398 is parenthesized. This still has the Etype of the name, but since it is
2399 not a name, para 7 does not apply, and we need to go to the base type.
2400 This is the only case where parenthesization affects the dynamic
2401 semantics (i.e. the range of possible values at run time that is covered
2402 by the others alternative).
2404 Another exception is if the subtype of the expression is non-static. In
2405 that case, we also have to use the base type. */
2406 if (Paren_Count (Expression (gnat_node)) != 0
2407 || !Is_OK_Static_Subtype (Underlying_Type
2408 (Etype (Expression (gnat_node)))))
2409 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2411 /* We build a SWITCH_EXPR that contains the code with interspersed
2412 CASE_LABEL_EXPRs for each label. */
2413 if (!Sloc_to_locus (End_Location (gnat_node), &end_locus))
2414 end_locus = input_location;
2415 gnu_label = create_artificial_label (end_locus);
2416 start_stmt_group ();
2418 for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
2419 Present (gnat_when);
2420 gnat_when = Next_Non_Pragma (gnat_when))
2422 bool choices_added_p = false;
2423 Node_Id gnat_choice;
2425 /* First compile all the different case choices for the current WHEN
2426 alternative. */
2427 for (gnat_choice = First (Discrete_Choices (gnat_when));
2428 Present (gnat_choice);
2429 gnat_choice = Next (gnat_choice))
2431 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2432 tree label = create_artificial_label (input_location);
2434 switch (Nkind (gnat_choice))
2436 case N_Range:
2437 gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
2438 gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
2439 break;
2441 case N_Subtype_Indication:
2442 gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
2443 (Constraint (gnat_choice))));
2444 gnu_high = gnat_to_gnu (High_Bound (Range_Expression
2445 (Constraint (gnat_choice))));
2446 break;
2448 case N_Identifier:
2449 case N_Expanded_Name:
2450 /* This represents either a subtype range or a static value of
2451 some kind; Ekind says which. */
2452 if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
2454 tree gnu_type = get_unpadded_type (Entity (gnat_choice));
2456 gnu_low = TYPE_MIN_VALUE (gnu_type);
2457 gnu_high = TYPE_MAX_VALUE (gnu_type);
2458 break;
2461 /* ... fall through ... */
2463 case N_Character_Literal:
2464 case N_Integer_Literal:
2465 gnu_low = gnat_to_gnu (gnat_choice);
2466 break;
2468 case N_Others_Choice:
2469 break;
2471 default:
2472 gcc_unreachable ();
2475 /* Everything should be folded into constants at this point. */
2476 gcc_assert (!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST);
2477 gcc_assert (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST);
2479 add_stmt_with_node (build_case_label (gnu_low, gnu_high, label),
2480 gnat_choice);
2481 choices_added_p = true;
2484 /* This construct doesn't define a scope so we shouldn't push a binding
2485 level around the statement list. Except that we have always done so
2486 historically and this makes it possible to reduce stack usage. As a
2487 compromise, we keep doing it for case statements, for which this has
2488 never been problematic, but not for case expressions in Ada 2012. */
2489 if (choices_added_p)
2491 const bool is_case_expression
2492 = (Nkind (Parent (gnat_node)) == N_Expression_With_Actions);
2493 tree group
2494 = build_stmt_group (Statements (gnat_when), !is_case_expression);
2495 bool group_may_fallthru = block_may_fallthru (group);
2496 add_stmt (group);
2497 if (group_may_fallthru)
2499 tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
2500 SET_EXPR_LOCATION (stmt, end_locus);
2501 add_stmt (stmt);
2502 may_fallthru = true;
2507 /* Now emit a definition of the label the cases branch to, if any. */
2508 if (may_fallthru)
2509 add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
2510 gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
2511 end_stmt_group (), NULL_TREE);
2513 return gnu_result;
2516 /* Find out whether VAR is an iteration variable of an enclosing loop in the
2517 current function. If so, push a range_check_info structure onto the stack
2518 of this enclosing loop and return it. Otherwise, return NULL. */
2520 static struct range_check_info_d *
2521 push_range_check_info (tree var)
2523 struct loop_info_d *iter = NULL;
2524 unsigned int i;
2526 if (vec_safe_is_empty (gnu_loop_stack))
2527 return NULL;
2529 var = remove_conversions (var, false);
2531 if (TREE_CODE (var) != VAR_DECL)
2532 return NULL;
2534 if (decl_function_context (var) != current_function_decl)
2535 return NULL;
2537 for (i = vec_safe_length (gnu_loop_stack) - 1;
2538 vec_safe_iterate (gnu_loop_stack, i, &iter);
2539 i--)
2540 if (var == iter->loop_var)
2541 break;
2543 if (iter)
2545 struct range_check_info_d *rci = ggc_alloc<range_check_info_d> ();
2546 vec_safe_push (iter->checks, rci);
2547 return rci;
2550 return NULL;
2553 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
2554 false, or the maximum value if MAX is true, of TYPE. */
2556 static bool
2557 can_equal_min_or_max_val_p (tree val, tree type, bool max)
2559 tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
2561 if (TREE_CODE (min_or_max_val) != INTEGER_CST)
2562 return true;
2564 if (TREE_CODE (val) == NOP_EXPR)
2565 val = (max
2566 ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
2567 : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
2569 if (TREE_CODE (val) != INTEGER_CST)
2570 return true;
2572 if (max)
2573 return tree_int_cst_lt (val, min_or_max_val) == 0;
2574 else
2575 return tree_int_cst_lt (min_or_max_val, val) == 0;
2578 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
2579 If REVERSE is true, minimum value is taken as maximum value. */
2581 static inline bool
2582 can_equal_min_val_p (tree val, tree type, bool reverse)
2584 return can_equal_min_or_max_val_p (val, type, reverse);
2587 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
2588 If REVERSE is true, maximum value is taken as minimum value. */
2590 static inline bool
2591 can_equal_max_val_p (tree val, tree type, bool reverse)
2593 return can_equal_min_or_max_val_p (val, type, !reverse);
2596 /* Return true if VAL1 can be lower than VAL2. */
2598 static bool
2599 can_be_lower_p (tree val1, tree val2)
2601 if (TREE_CODE (val1) == NOP_EXPR)
2602 val1 = TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val1, 0)));
2604 if (TREE_CODE (val1) != INTEGER_CST)
2605 return true;
2607 if (TREE_CODE (val2) == NOP_EXPR)
2608 val2 = TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val2, 0)));
2610 if (TREE_CODE (val2) != INTEGER_CST)
2611 return true;
2613 return tree_int_cst_lt (val1, val2);
2616 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
2617 to a GCC tree, which is returned. */
2619 static tree
2620 Loop_Statement_to_gnu (Node_Id gnat_node)
2622 const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2623 struct loop_info_d *gnu_loop_info = ggc_cleared_alloc<loop_info_d> ();
2624 tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
2625 NULL_TREE, NULL_TREE, NULL_TREE);
2626 tree gnu_loop_label = create_artificial_label (input_location);
2627 tree gnu_cond_expr = NULL_TREE, gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2628 tree gnu_result;
2630 /* Push the loop_info structure associated with the LOOP_STMT. */
2631 vec_safe_push (gnu_loop_stack, gnu_loop_info);
2633 /* Set location information for statement and end label. */
2634 set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2635 Sloc_to_locus (Sloc (End_Label (gnat_node)),
2636 &DECL_SOURCE_LOCATION (gnu_loop_label));
2637 LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
2639 /* Save the statement for later reuse. */
2640 gnu_loop_info->stmt = gnu_loop_stmt;
2642 /* Set the condition under which the loop must keep going.
2643 For the case "LOOP .... END LOOP;" the condition is always true. */
2644 if (No (gnat_iter_scheme))
2647 /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate. */
2648 else if (Present (Condition (gnat_iter_scheme)))
2649 LOOP_STMT_COND (gnu_loop_stmt)
2650 = gnat_to_gnu (Condition (gnat_iter_scheme));
2652 /* Otherwise we have an iteration scheme and the condition is given by the
2653 bounds of the subtype of the iteration variable. */
2654 else
2656 Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
2657 Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
2658 Entity_Id gnat_type = Etype (gnat_loop_var);
2659 tree gnu_type = get_unpadded_type (gnat_type);
2660 tree gnu_base_type = get_base_type (gnu_type);
2661 tree gnu_one_node = convert (gnu_base_type, integer_one_node);
2662 tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
2663 enum tree_code update_code, test_code, shift_code;
2664 bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
2666 gnu_low = convert (gnu_base_type, TYPE_MIN_VALUE (gnu_type));
2667 gnu_high = convert (gnu_base_type, TYPE_MAX_VALUE (gnu_type));
2669 /* We must disable modulo reduction for the iteration variable, if any,
2670 in order for the loop comparison to be effective. */
2671 if (reverse)
2673 gnu_first = gnu_high;
2674 gnu_last = gnu_low;
2675 update_code = MINUS_NOMOD_EXPR;
2676 test_code = GE_EXPR;
2677 shift_code = PLUS_NOMOD_EXPR;
2679 else
2681 gnu_first = gnu_low;
2682 gnu_last = gnu_high;
2683 update_code = PLUS_NOMOD_EXPR;
2684 test_code = LE_EXPR;
2685 shift_code = MINUS_NOMOD_EXPR;
2688 /* We use two different strategies to translate the loop, depending on
2689 whether optimization is enabled.
2691 If it is, we generate the canonical loop form expected by the loop
2692 optimizer and the loop vectorizer, which is the do-while form:
2694 ENTRY_COND
2695 loop:
2696 TOP_UPDATE
2697 BODY
2698 BOTTOM_COND
2699 GOTO loop
2701 This avoids an implicit dependency on loop header copying and makes
2702 it possible to turn BOTTOM_COND into an inequality test.
2704 If optimization is disabled, loop header copying doesn't come into
2705 play and we try to generate the loop form with the fewer conditional
2706 branches. First, the default form, which is:
2708 loop:
2709 TOP_COND
2710 BODY
2711 BOTTOM_UPDATE
2712 GOTO loop
2714 It should catch most loops with constant ending point. Then, if we
2715 cannot, we try to generate the shifted form:
2717 loop:
2718 TOP_COND
2719 TOP_UPDATE
2720 BODY
2721 GOTO loop
2723 which should catch loops with constant starting point. Otherwise, if
2724 we cannot, we generate the fallback form:
2726 ENTRY_COND
2727 loop:
2728 BODY
2729 BOTTOM_COND
2730 BOTTOM_UPDATE
2731 GOTO loop
2733 which works in all cases. */
2735 if (optimize)
2737 /* We can use the do-while form directly if GNU_FIRST-1 doesn't
2738 overflow. */
2739 if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
2742 /* Otherwise, use the do-while form with the help of a special
2743 induction variable in the unsigned version of the base type
2744 or the unsigned version of the size type, whichever is the
2745 largest, in order to have wrap-around arithmetics for it. */
2746 else
2748 if (TYPE_PRECISION (gnu_base_type)
2749 > TYPE_PRECISION (size_type_node))
2750 gnu_base_type
2751 = gnat_type_for_size (TYPE_PRECISION (gnu_base_type), 1);
2752 else
2753 gnu_base_type = size_type_node;
2755 gnu_first = convert (gnu_base_type, gnu_first);
2756 gnu_last = convert (gnu_base_type, gnu_last);
2757 gnu_one_node = convert (gnu_base_type, integer_one_node);
2758 use_iv = true;
2761 gnu_first
2762 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2763 gnu_one_node);
2764 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2765 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2767 else
2769 /* We can use the default form if GNU_LAST+1 doesn't overflow. */
2770 if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
2773 /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
2774 GNU_LAST-1 does. */
2775 else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
2776 && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
2778 gnu_first
2779 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2780 gnu_one_node);
2781 gnu_last
2782 = build_binary_op (shift_code, gnu_base_type, gnu_last,
2783 gnu_one_node);
2784 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2787 /* Otherwise, use the fallback form. */
2788 else
2789 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2792 /* If we use the BOTTOM_COND, we can turn the test into an inequality
2793 test but we may have to add ENTRY_COND to protect the empty loop. */
2794 if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
2796 test_code = NE_EXPR;
2797 if (can_be_lower_p (gnu_high, gnu_low))
2799 gnu_cond_expr
2800 = build3 (COND_EXPR, void_type_node,
2801 build_binary_op (LE_EXPR, boolean_type_node,
2802 gnu_low, gnu_high),
2803 NULL_TREE, alloc_stmt_list ());
2804 set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
2808 /* Open a new nesting level that will surround the loop to declare the
2809 iteration variable. */
2810 start_stmt_group ();
2811 gnat_pushlevel ();
2813 /* If we use the special induction variable, create it and set it to
2814 its initial value. Morever, the regular iteration variable cannot
2815 itself be initialized, lest the initial value wrapped around. */
2816 if (use_iv)
2818 gnu_loop_iv
2819 = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
2820 add_stmt (gnu_stmt);
2821 gnu_first = NULL_TREE;
2823 else
2824 gnu_loop_iv = NULL_TREE;
2826 /* Declare the iteration variable and set it to its initial value. */
2827 gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
2828 if (DECL_BY_REF_P (gnu_loop_var))
2829 gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
2830 else if (use_iv)
2832 gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
2833 SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
2835 gnu_loop_info->loop_var = gnu_loop_var;
2837 /* Do all the arithmetics in the base type. */
2838 gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
2840 /* Set either the top or bottom exit condition. */
2841 if (use_iv)
2842 LOOP_STMT_COND (gnu_loop_stmt)
2843 = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
2844 gnu_last);
2845 else
2846 LOOP_STMT_COND (gnu_loop_stmt)
2847 = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
2848 gnu_last);
2850 /* Set either the top or bottom update statement and give it the source
2851 location of the iteration for better coverage info. */
2852 if (use_iv)
2854 gnu_stmt
2855 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
2856 build_binary_op (update_code, gnu_base_type,
2857 gnu_loop_iv, gnu_one_node));
2858 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2859 append_to_statement_list (gnu_stmt,
2860 &LOOP_STMT_UPDATE (gnu_loop_stmt));
2861 gnu_stmt
2862 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2863 gnu_loop_iv);
2864 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2865 append_to_statement_list (gnu_stmt,
2866 &LOOP_STMT_UPDATE (gnu_loop_stmt));
2868 else
2870 gnu_stmt
2871 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2872 build_binary_op (update_code, gnu_base_type,
2873 gnu_loop_var, gnu_one_node));
2874 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2875 LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
2879 /* If the loop was named, have the name point to this loop. In this case,
2880 the association is not a DECL node, but the end label of the loop. */
2881 if (Present (Identifier (gnat_node)))
2882 save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
2884 /* Make the loop body into its own block, so any allocated storage will be
2885 released every iteration. This is needed for stack allocation. */
2886 LOOP_STMT_BODY (gnu_loop_stmt)
2887 = build_stmt_group (Statements (gnat_node), true);
2888 TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
2890 /* If we have an iteration scheme, then we are in a statement group. Add
2891 the LOOP_STMT to it, finish it and make it the "loop". */
2892 if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
2894 struct range_check_info_d *rci;
2895 unsigned n_checks = vec_safe_length (gnu_loop_info->checks);
2896 unsigned int i;
2898 /* First, if we have computed a small number of invariant conditions for
2899 range checks applied to the iteration variable, then initialize these
2900 conditions in front of the loop. Otherwise, leave them set to true.
2902 ??? The heuristics need to be improved, by taking into account the
2903 following datapoints:
2904 - loop unswitching is disabled for big loops. The cap is the
2905 parameter PARAM_MAX_UNSWITCH_INSNS (50).
2906 - loop unswitching can only be applied a small number of times
2907 to a given loop. The cap is PARAM_MAX_UNSWITCH_LEVEL (3).
2908 - the front-end quickly generates useless or redundant checks
2909 that can be entirely optimized away in the end. */
2910 if (1 <= n_checks && n_checks <= 4)
2911 for (i = 0;
2912 vec_safe_iterate (gnu_loop_info->checks, i, &rci);
2913 i++)
2915 tree low_ok
2916 = rci->low_bound
2917 ? build_binary_op (GE_EXPR, boolean_type_node,
2918 convert (rci->type, gnu_low),
2919 rci->low_bound)
2920 : boolean_true_node;
2922 tree high_ok
2923 = rci->high_bound
2924 ? build_binary_op (LE_EXPR, boolean_type_node,
2925 convert (rci->type, gnu_high),
2926 rci->high_bound)
2927 : boolean_true_node;
2929 tree range_ok
2930 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
2931 low_ok, high_ok);
2933 TREE_OPERAND (rci->invariant_cond, 0)
2934 = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
2936 add_stmt_with_node_force (rci->invariant_cond, gnat_node);
2939 add_stmt (gnu_loop_stmt);
2940 gnat_poplevel ();
2941 gnu_loop_stmt = end_stmt_group ();
2944 /* If we have an outer COND_EXPR, that's our result and this loop is its
2945 "true" statement. Otherwise, the result is the LOOP_STMT. */
2946 if (gnu_cond_expr)
2948 COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
2949 TREE_SIDE_EFFECTS (gnu_cond_expr) = 1;
2950 gnu_result = gnu_cond_expr;
2952 else
2953 gnu_result = gnu_loop_stmt;
2955 gnu_loop_stack->pop ();
2957 return gnu_result;
2960 /* This page implements a form of Named Return Value optimization modelled
2961 on the C++ optimization of the same name. The main difference is that
2962 we disregard any semantical considerations when applying it here, the
2963 counterpart being that we don't try to apply it to semantically loaded
2964 return types, i.e. types with the TYPE_BY_REFERENCE_P flag set.
2966 We consider a function body of the following GENERIC form:
2968 return_type R1;
2969 [...]
2970 RETURN_EXPR [<retval> = ...]
2971 [...]
2972 RETURN_EXPR [<retval> = R1]
2973 [...]
2974 return_type Ri;
2975 [...]
2976 RETURN_EXPR [<retval> = ...]
2977 [...]
2978 RETURN_EXPR [<retval> = Ri]
2979 [...]
2981 and we try to fulfill a simple criterion that would make it possible to
2982 replace one or several Ri variables with the RESULT_DECL of the function.
2984 The first observation is that RETURN_EXPRs that don't directly reference
2985 any of the Ri variables on the RHS of their assignment are transparent wrt
2986 the optimization. This is because the Ri variables aren't addressable so
2987 any transformation applied to them doesn't affect the RHS; moreover, the
2988 assignment writes the full <retval> object so existing values are entirely
2989 discarded.
2991 This property can be extended to some forms of RETURN_EXPRs that reference
2992 the Ri variables, for example CONSTRUCTORs, but isn't true in the general
2993 case, in particular when function calls are involved.
2995 Therefore the algorithm is as follows:
2997 1. Collect the list of candidates for a Named Return Value (Ri variables
2998 on the RHS of assignments of RETURN_EXPRs) as well as the list of the
2999 other expressions on the RHS of such assignments.
3001 2. Prune the members of the first list (candidates) that are referenced
3002 by a member of the second list (expressions).
3004 3. Extract a set of candidates with non-overlapping live ranges from the
3005 first list. These are the Named Return Values.
3007 4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
3008 Named Return Values in the function with the RESULT_DECL.
3010 If the function returns an unconstrained type, things are a bit different
3011 because the anonymous return object is allocated on the secondary stack
3012 and RESULT_DECL is only a pointer to it. Each return object can be of a
3013 different size and is allocated separately so we need not care about the
3014 aforementioned overlapping issues. Therefore, we don't collect the other
3015 expressions and skip step #2 in the algorithm. */
3017 struct nrv_data
3019 bitmap nrv;
3020 tree result;
3021 Node_Id gnat_ret;
3022 hash_set<tree> *visited;
3025 /* Return true if T is a Named Return Value. */
3027 static inline bool
3028 is_nrv_p (bitmap nrv, tree t)
3030 return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
3033 /* Helper function for walk_tree, used by finalize_nrv below. */
3035 static tree
3036 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
3038 struct nrv_data *dp = (struct nrv_data *)data;
3039 tree t = *tp;
3041 /* No need to walk into types or decls. */
3042 if (IS_TYPE_OR_DECL_P (t))
3043 *walk_subtrees = 0;
3045 if (is_nrv_p (dp->nrv, t))
3046 bitmap_clear_bit (dp->nrv, DECL_UID (t));
3048 return NULL_TREE;
3051 /* Prune Named Return Values in BLOCK and return true if there is still a
3052 Named Return Value in BLOCK or one of its sub-blocks. */
3054 static bool
3055 prune_nrv_in_block (bitmap nrv, tree block)
3057 bool has_nrv = false;
3058 tree t;
3060 /* First recurse on the sub-blocks. */
3061 for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
3062 has_nrv |= prune_nrv_in_block (nrv, t);
3064 /* Then make sure to keep at most one NRV per block. */
3065 for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
3066 if (is_nrv_p (nrv, t))
3068 if (has_nrv)
3069 bitmap_clear_bit (nrv, DECL_UID (t));
3070 else
3071 has_nrv = true;
3074 return has_nrv;
3077 /* Helper function for walk_tree, used by finalize_nrv below. */
3079 static tree
3080 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
3082 struct nrv_data *dp = (struct nrv_data *)data;
3083 tree t = *tp;
3085 /* No need to walk into types. */
3086 if (TYPE_P (t))
3087 *walk_subtrees = 0;
3089 /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
3090 nop, but differs from using NULL_TREE in that it indicates that we care
3091 about the value of the RESULT_DECL. */
3092 else if (TREE_CODE (t) == RETURN_EXPR
3093 && TREE_CODE (TREE_OPERAND (t, 0)) == MODIFY_EXPR)
3095 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1), init_expr;
3097 /* If this is the temporary created for a return value with variable
3098 size in Call_to_gnu, we replace the RHS with the init expression. */
3099 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3100 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3101 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3102 == TREE_OPERAND (ret_val, 1))
3104 init_expr = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3105 ret_val = TREE_OPERAND (ret_val, 1);
3107 else
3108 init_expr = NULL_TREE;
3110 /* Strip useless conversions around the return value. */
3111 if (gnat_useless_type_conversion (ret_val))
3112 ret_val = TREE_OPERAND (ret_val, 0);
3114 if (is_nrv_p (dp->nrv, ret_val))
3116 if (init_expr)
3117 TREE_OPERAND (TREE_OPERAND (t, 0), 1) = init_expr;
3118 else
3119 TREE_OPERAND (t, 0) = dp->result;
3123 /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
3124 if needed. */
3125 else if (TREE_CODE (t) == DECL_EXPR
3126 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3128 tree var = DECL_EXPR_DECL (t), init;
3130 if (DECL_INITIAL (var))
3132 init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
3133 DECL_INITIAL (var));
3134 SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
3135 DECL_INITIAL (var) = NULL_TREE;
3137 else
3138 init = build_empty_stmt (EXPR_LOCATION (t));
3139 *tp = init;
3141 /* Identify the NRV to the RESULT_DECL for debugging purposes. */
3142 SET_DECL_VALUE_EXPR (var, dp->result);
3143 DECL_HAS_VALUE_EXPR_P (var) = 1;
3144 /* ??? Kludge to avoid an assertion failure during inlining. */
3145 DECL_SIZE (var) = bitsize_unit_node;
3146 DECL_SIZE_UNIT (var) = size_one_node;
3149 /* And replace all uses of NRVs with the RESULT_DECL. */
3150 else if (is_nrv_p (dp->nrv, t))
3151 *tp = convert (TREE_TYPE (t), dp->result);
3153 /* Avoid walking into the same tree more than once. Unfortunately, we
3154 can't just use walk_tree_without_duplicates because it would only
3155 call us for the first occurrence of NRVs in the function body. */
3156 if (dp->visited->add (*tp))
3157 *walk_subtrees = 0;
3159 return NULL_TREE;
3162 /* Likewise, but used when the function returns an unconstrained type. */
3164 static tree
3165 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
3167 struct nrv_data *dp = (struct nrv_data *)data;
3168 tree t = *tp;
3170 /* No need to walk into types. */
3171 if (TYPE_P (t))
3172 *walk_subtrees = 0;
3174 /* We need to see the DECL_EXPR of NRVs before any other references so we
3175 walk the body of BIND_EXPR before walking its variables. */
3176 else if (TREE_CODE (t) == BIND_EXPR)
3177 walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
3179 /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
3180 return value built by the allocator instead of the whole construct. */
3181 else if (TREE_CODE (t) == RETURN_EXPR
3182 && TREE_CODE (TREE_OPERAND (t, 0)) == MODIFY_EXPR)
3184 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
3186 /* This is the construct returned by the allocator. */
3187 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3188 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
3190 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
3191 ret_val
3192 = (*CONSTRUCTOR_ELTS (TREE_OPERAND (TREE_OPERAND (ret_val, 0),
3193 1)))[1].value;
3194 else
3195 ret_val = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3198 /* Strip useless conversions around the return value. */
3199 if (gnat_useless_type_conversion (ret_val)
3200 || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
3201 ret_val = TREE_OPERAND (ret_val, 0);
3203 /* Strip unpadding around the return value. */
3204 if (TREE_CODE (ret_val) == COMPONENT_REF
3205 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
3206 ret_val = TREE_OPERAND (ret_val, 0);
3208 /* Assign the new return value to the RESULT_DECL. */
3209 if (is_nrv_p (dp->nrv, ret_val))
3210 TREE_OPERAND (TREE_OPERAND (t, 0), 1)
3211 = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
3214 /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
3215 into a new variable. */
3216 else if (TREE_CODE (t) == DECL_EXPR
3217 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3219 tree saved_current_function_decl = current_function_decl;
3220 tree var = DECL_EXPR_DECL (t);
3221 tree alloc, p_array, new_var, new_ret;
3222 vec<constructor_elt, va_gc> *v;
3223 vec_alloc (v, 2);
3225 /* Create an artificial context to build the allocation. */
3226 current_function_decl = decl_function_context (var);
3227 start_stmt_group ();
3228 gnat_pushlevel ();
3230 /* This will return a COMPOUND_EXPR with the allocation in the first
3231 arm and the final return value in the second arm. */
3232 alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
3233 TREE_TYPE (dp->result),
3234 Procedure_To_Call (dp->gnat_ret),
3235 Storage_Pool (dp->gnat_ret),
3236 Empty, false);
3238 /* The new variable is built as a reference to the allocated space. */
3239 new_var
3240 = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
3241 build_reference_type (TREE_TYPE (var)));
3242 DECL_BY_REFERENCE (new_var) = 1;
3244 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
3246 /* The new initial value is a COMPOUND_EXPR with the allocation in
3247 the first arm and the value of P_ARRAY in the second arm. */
3248 DECL_INITIAL (new_var)
3249 = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
3250 TREE_OPERAND (alloc, 0),
3251 (*CONSTRUCTOR_ELTS (TREE_OPERAND (alloc, 1)))[0].value);
3253 /* Build a modified CONSTRUCTOR that references NEW_VAR. */
3254 p_array = TYPE_FIELDS (TREE_TYPE (alloc));
3255 CONSTRUCTOR_APPEND_ELT (v, p_array,
3256 fold_convert (TREE_TYPE (p_array), new_var));
3257 CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
3258 (*CONSTRUCTOR_ELTS (
3259 TREE_OPERAND (alloc, 1)))[1].value);
3260 new_ret = build_constructor (TREE_TYPE (alloc), v);
3262 else
3264 /* The new initial value is just the allocation. */
3265 DECL_INITIAL (new_var) = alloc;
3266 new_ret = fold_convert (TREE_TYPE (alloc), new_var);
3269 gnat_pushdecl (new_var, Empty);
3271 /* Destroy the artificial context and insert the new statements. */
3272 gnat_zaplevel ();
3273 *tp = end_stmt_group ();
3274 current_function_decl = saved_current_function_decl;
3276 /* Chain NEW_VAR immediately after VAR and ignore the latter. */
3277 DECL_CHAIN (new_var) = DECL_CHAIN (var);
3278 DECL_CHAIN (var) = new_var;
3279 DECL_IGNORED_P (var) = 1;
3281 /* Save the new return value and the dereference of NEW_VAR. */
3282 DECL_INITIAL (var)
3283 = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
3284 build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
3285 /* ??? Kludge to avoid messing up during inlining. */
3286 DECL_CONTEXT (var) = NULL_TREE;
3289 /* And replace all uses of NRVs with the dereference of NEW_VAR. */
3290 else if (is_nrv_p (dp->nrv, t))
3291 *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
3293 /* Avoid walking into the same tree more than once. Unfortunately, we
3294 can't just use walk_tree_without_duplicates because it would only
3295 call us for the first occurrence of NRVs in the function body. */
3296 if (dp->visited->add (*tp))
3297 *walk_subtrees = 0;
3299 return NULL_TREE;
3302 /* Finalize the Named Return Value optimization for FNDECL. The NRV bitmap
3303 contains the candidates for Named Return Value and OTHER is a list of
3304 the other return values. GNAT_RET is a representative return node. */
3306 static void
3307 finalize_nrv (tree fndecl, bitmap nrv, vec<tree, va_gc> *other, Node_Id gnat_ret)
3309 struct cgraph_node *node;
3310 struct nrv_data data;
3311 walk_tree_fn func;
3312 unsigned int i;
3313 tree iter;
3315 /* We shouldn't be applying the optimization to return types that we aren't
3316 allowed to manipulate freely. */
3317 gcc_assert (!TYPE_IS_BY_REFERENCE_P (TREE_TYPE (TREE_TYPE (fndecl))));
3319 /* Prune the candidates that are referenced by other return values. */
3320 data.nrv = nrv;
3321 data.result = NULL_TREE;
3322 data.visited = NULL;
3323 for (i = 0; vec_safe_iterate (other, i, &iter); i++)
3324 walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
3325 if (bitmap_empty_p (nrv))
3326 return;
3328 /* Prune also the candidates that are referenced by nested functions. */
3329 node = cgraph_node::get_create (fndecl);
3330 for (node = node->nested; node; node = node->next_nested)
3331 walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), prune_nrv_r,
3332 &data);
3333 if (bitmap_empty_p (nrv))
3334 return;
3336 /* Extract a set of NRVs with non-overlapping live ranges. */
3337 if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
3338 return;
3340 /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs. */
3341 data.nrv = nrv;
3342 data.result = DECL_RESULT (fndecl);
3343 data.gnat_ret = gnat_ret;
3344 data.visited = new hash_set<tree>;
3345 if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
3346 func = finalize_nrv_unc_r;
3347 else
3348 func = finalize_nrv_r;
3349 walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
3350 delete data.visited;
3353 /* Return true if RET_VAL can be used as a Named Return Value for the
3354 anonymous return object RET_OBJ. */
3356 static bool
3357 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
3359 if (TREE_CODE (ret_val) != VAR_DECL)
3360 return false;
3362 if (TREE_THIS_VOLATILE (ret_val))
3363 return false;
3365 if (DECL_CONTEXT (ret_val) != current_function_decl)
3366 return false;
3368 if (TREE_STATIC (ret_val))
3369 return false;
3371 if (TREE_ADDRESSABLE (ret_val))
3372 return false;
3374 if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
3375 return false;
3377 return true;
3380 /* Build a RETURN_EXPR. If RET_VAL is non-null, build a RETURN_EXPR around
3381 the assignment of RET_VAL to RET_OBJ. Otherwise build a bare RETURN_EXPR
3382 around RESULT_OBJ, which may be null in this case. */
3384 static tree
3385 build_return_expr (tree ret_obj, tree ret_val)
3387 tree result_expr;
3389 if (ret_val)
3391 /* The gimplifier explicitly enforces the following invariant:
3393 RETURN_EXPR
3395 MODIFY_EXPR
3398 RET_OBJ ...
3400 As a consequence, type consistency dictates that we use the type
3401 of the RET_OBJ as the operation type. */
3402 tree operation_type = TREE_TYPE (ret_obj);
3404 /* Convert the right operand to the operation type. Note that it's the
3405 same transformation as in the MODIFY_EXPR case of build_binary_op,
3406 with the assumption that the type cannot involve a placeholder. */
3407 if (operation_type != TREE_TYPE (ret_val))
3408 ret_val = convert (operation_type, ret_val);
3410 result_expr = build2 (MODIFY_EXPR, void_type_node, ret_obj, ret_val);
3412 /* If the function returns an aggregate type, find out whether this is
3413 a candidate for Named Return Value. If so, record it. Otherwise,
3414 if this is an expression of some kind, record it elsewhere. */
3415 if (optimize
3416 && AGGREGATE_TYPE_P (operation_type)
3417 && !TYPE_IS_FAT_POINTER_P (operation_type)
3418 && TYPE_MODE (operation_type) == BLKmode
3419 && aggregate_value_p (operation_type, current_function_decl))
3421 /* Recognize the temporary created for a return value with variable
3422 size in Call_to_gnu. We want to eliminate it if possible. */
3423 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3424 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3425 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3426 == TREE_OPERAND (ret_val, 1))
3427 ret_val = TREE_OPERAND (ret_val, 1);
3429 /* Strip useless conversions around the return value. */
3430 if (gnat_useless_type_conversion (ret_val))
3431 ret_val = TREE_OPERAND (ret_val, 0);
3433 /* Now apply the test to the return value. */
3434 if (return_value_ok_for_nrv_p (ret_obj, ret_val))
3436 if (!f_named_ret_val)
3437 f_named_ret_val = BITMAP_GGC_ALLOC ();
3438 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
3441 /* Note that we need not care about CONSTRUCTORs here, as they are
3442 totally transparent given the read-compose-write semantics of
3443 assignments from CONSTRUCTORs. */
3444 else if (EXPR_P (ret_val))
3445 vec_safe_push (f_other_ret_val, ret_val);
3448 else
3449 result_expr = ret_obj;
3451 return build1 (RETURN_EXPR, void_type_node, result_expr);
3454 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body. We
3455 don't return anything. */
3457 static void
3458 Subprogram_Body_to_gnu (Node_Id gnat_node)
3460 /* Defining identifier of a parameter to the subprogram. */
3461 Entity_Id gnat_param;
3462 /* The defining identifier for the subprogram body. Note that if a
3463 specification has appeared before for this body, then the identifier
3464 occurring in that specification will also be a defining identifier and all
3465 the calls to this subprogram will point to that specification. */
3466 Entity_Id gnat_subprog_id
3467 = (Present (Corresponding_Spec (gnat_node))
3468 ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
3469 /* The FUNCTION_DECL node corresponding to the subprogram spec. */
3470 tree gnu_subprog_decl;
3471 /* Its RESULT_DECL node. */
3472 tree gnu_result_decl;
3473 /* Its FUNCTION_TYPE node. */
3474 tree gnu_subprog_type;
3475 /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any. */
3476 tree gnu_cico_list;
3477 /* The entry in the CI_CO_LIST that represents a function return, if any. */
3478 tree gnu_return_var_elmt = NULL_TREE;
3479 tree gnu_result;
3480 location_t locus;
3481 struct language_function *gnu_subprog_language;
3482 vec<parm_attr, va_gc> *cache;
3484 /* If this is a generic object or if it has been eliminated,
3485 ignore it. */
3486 if (Ekind (gnat_subprog_id) == E_Generic_Procedure
3487 || Ekind (gnat_subprog_id) == E_Generic_Function
3488 || Is_Eliminated (gnat_subprog_id))
3489 return;
3491 /* If this subprogram acts as its own spec, define it. Otherwise, just get
3492 the already-elaborated tree node. However, if this subprogram had its
3493 elaboration deferred, we will already have made a tree node for it. So
3494 treat it as not being defined in that case. Such a subprogram cannot
3495 have an address clause or a freeze node, so this test is safe, though it
3496 does disable some otherwise-useful error checking. */
3497 gnu_subprog_decl
3498 = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
3499 Acts_As_Spec (gnat_node)
3500 && !present_gnu_tree (gnat_subprog_id));
3501 gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
3502 gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
3503 gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3504 if (gnu_cico_list)
3505 gnu_return_var_elmt = value_member (void_type_node, gnu_cico_list);
3507 /* If the function returns by invisible reference, make it explicit in the
3508 function body. See gnat_to_gnu_entity, E_Subprogram_Type case.
3509 Handle the explicit case here and the copy-in/copy-out case below. */
3510 if (TREE_ADDRESSABLE (gnu_subprog_type) && !gnu_return_var_elmt)
3512 TREE_TYPE (gnu_result_decl)
3513 = build_reference_type (TREE_TYPE (gnu_result_decl));
3514 relayout_decl (gnu_result_decl);
3517 /* Set the line number in the decl to correspond to that of the body. */
3518 Sloc_to_locus (Sloc (gnat_node), &locus);
3519 DECL_SOURCE_LOCATION (gnu_subprog_decl) = locus;
3521 /* Initialize the information structure for the function. */
3522 allocate_struct_function (gnu_subprog_decl, false);
3523 gnu_subprog_language = ggc_cleared_alloc<language_function> ();
3524 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language = gnu_subprog_language;
3525 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_start_locus = locus;
3526 set_cfun (NULL);
3528 begin_subprog_body (gnu_subprog_decl);
3530 /* If there are In Out or Out parameters, we need to ensure that the return
3531 statement properly copies them out. We do this by making a new block and
3532 converting any return into a goto to a label at the end of the block. */
3533 if (gnu_cico_list)
3535 tree gnu_return_var = NULL_TREE;
3537 vec_safe_push (gnu_return_label_stack,
3538 create_artificial_label (input_location));
3540 start_stmt_group ();
3541 gnat_pushlevel ();
3543 /* If this is a function with In Out or Out parameters, we also need a
3544 variable for the return value to be placed. */
3545 if (gnu_return_var_elmt)
3547 tree gnu_return_type
3548 = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
3550 /* If the function returns by invisible reference, make it
3551 explicit in the function body. See gnat_to_gnu_entity,
3552 E_Subprogram_Type case. */
3553 if (TREE_ADDRESSABLE (gnu_subprog_type))
3554 gnu_return_type = build_reference_type (gnu_return_type);
3556 gnu_return_var
3557 = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
3558 gnu_return_type, NULL_TREE, false, false,
3559 false, false, NULL, gnat_subprog_id);
3560 TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
3563 vec_safe_push (gnu_return_var_stack, gnu_return_var);
3565 /* See whether there are parameters for which we don't have a GCC tree
3566 yet. These must be Out parameters. Make a VAR_DECL for them and
3567 put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
3568 We can match up the entries because TYPE_CI_CO_LIST is in the order
3569 of the parameters. */
3570 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3571 Present (gnat_param);
3572 gnat_param = Next_Formal_With_Extras (gnat_param))
3573 if (!present_gnu_tree (gnat_param))
3575 tree gnu_cico_entry = gnu_cico_list;
3576 tree gnu_decl;
3578 /* Skip any entries that have been already filled in; they must
3579 correspond to In Out parameters. */
3580 while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
3581 gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
3583 /* Do any needed dereferences for by-ref objects. */
3584 gnu_decl = gnat_to_gnu_entity (gnat_param, NULL_TREE, 1);
3585 gcc_assert (DECL_P (gnu_decl));
3586 if (DECL_BY_REF_P (gnu_decl))
3587 gnu_decl = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_decl);
3589 /* Do any needed references for padded types. */
3590 TREE_VALUE (gnu_cico_entry)
3591 = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)), gnu_decl);
3594 else
3595 vec_safe_push (gnu_return_label_stack, NULL_TREE);
3597 /* Get a tree corresponding to the code for the subprogram. */
3598 start_stmt_group ();
3599 gnat_pushlevel ();
3601 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
3603 /* Generate the code of the subprogram itself. A return statement will be
3604 present and any Out parameters will be handled there. */
3605 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
3606 gnat_poplevel ();
3607 gnu_result = end_stmt_group ();
3609 /* If we populated the parameter attributes cache, we need to make sure that
3610 the cached expressions are evaluated on all the possible paths leading to
3611 their uses. So we force their evaluation on entry of the function. */
3612 cache = gnu_subprog_language->parm_attr_cache;
3613 if (cache)
3615 struct parm_attr_d *pa;
3616 int i;
3618 start_stmt_group ();
3620 FOR_EACH_VEC_ELT (*cache, i, pa)
3622 if (pa->first)
3623 add_stmt_with_node_force (pa->first, gnat_node);
3624 if (pa->last)
3625 add_stmt_with_node_force (pa->last, gnat_node);
3626 if (pa->length)
3627 add_stmt_with_node_force (pa->length, gnat_node);
3630 add_stmt (gnu_result);
3631 gnu_result = end_stmt_group ();
3633 gnu_subprog_language->parm_attr_cache = NULL;
3636 /* If we are dealing with a return from an Ada procedure with parameters
3637 passed by copy-in/copy-out, we need to return a record containing the
3638 final values of these parameters. If the list contains only one entry,
3639 return just that entry though.
3641 For a full description of the copy-in/copy-out parameter mechanism, see
3642 the part of the gnat_to_gnu_entity routine dealing with the translation
3643 of subprograms.
3645 We need to make a block that contains the definition of that label and
3646 the copying of the return value. It first contains the function, then
3647 the label and copy statement. */
3648 if (gnu_cico_list)
3650 tree gnu_retval;
3652 gnu_return_var_stack->pop ();
3654 add_stmt (gnu_result);
3655 add_stmt (build1 (LABEL_EXPR, void_type_node,
3656 gnu_return_label_stack->last ()));
3658 if (list_length (gnu_cico_list) == 1)
3659 gnu_retval = TREE_VALUE (gnu_cico_list);
3660 else
3661 gnu_retval = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
3662 gnu_cico_list);
3664 add_stmt_with_node (build_return_expr (gnu_result_decl, gnu_retval),
3665 End_Label (Handled_Statement_Sequence (gnat_node)));
3666 gnat_poplevel ();
3667 gnu_result = end_stmt_group ();
3670 gnu_return_label_stack->pop ();
3672 /* Attempt setting the end_locus of our GCC body tree, typically a
3673 BIND_EXPR or STATEMENT_LIST, then the end_locus of our GCC subprogram
3674 declaration tree. */
3675 set_end_locus_from_node (gnu_result, gnat_node);
3676 set_end_locus_from_node (gnu_subprog_decl, gnat_node);
3678 /* On SEH targets, install an exception handler around the main entry
3679 point to catch unhandled exceptions. */
3680 if (DECL_NAME (gnu_subprog_decl) == main_identifier_node
3681 && targetm_common.except_unwind_info (&global_options) == UI_SEH)
3683 tree t;
3684 tree etype;
3686 t = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
3687 1, integer_zero_node);
3688 t = build_call_n_expr (unhandled_except_decl, 1, t);
3690 etype = build_unary_op (ADDR_EXPR, NULL_TREE, unhandled_others_decl);
3691 etype = tree_cons (NULL_TREE, etype, NULL_TREE);
3693 t = build2 (CATCH_EXPR, void_type_node, etype, t);
3694 gnu_result = build2 (TRY_CATCH_EXPR, TREE_TYPE (gnu_result),
3695 gnu_result, t);
3698 end_subprog_body (gnu_result);
3700 /* Finally annotate the parameters and disconnect the trees for parameters
3701 that we have turned into variables since they are now unusable. */
3702 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3703 Present (gnat_param);
3704 gnat_param = Next_Formal_With_Extras (gnat_param))
3706 tree gnu_param = get_gnu_tree (gnat_param);
3707 bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
3709 annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
3710 DECL_BY_REF_P (gnu_param));
3712 if (is_var_decl)
3713 save_gnu_tree (gnat_param, NULL_TREE, false);
3716 /* Disconnect the variable created for the return value. */
3717 if (gnu_return_var_elmt)
3718 TREE_VALUE (gnu_return_var_elmt) = void_type_node;
3720 /* If the function returns an aggregate type and we have candidates for
3721 a Named Return Value, finalize the optimization. */
3722 if (optimize && gnu_subprog_language->named_ret_val)
3724 finalize_nrv (gnu_subprog_decl,
3725 gnu_subprog_language->named_ret_val,
3726 gnu_subprog_language->other_ret_val,
3727 gnu_subprog_language->gnat_ret);
3728 gnu_subprog_language->named_ret_val = NULL;
3729 gnu_subprog_language->other_ret_val = NULL;
3732 rest_of_subprog_body_compilation (gnu_subprog_decl);
3735 /* Return true if GNAT_NODE requires atomic synchronization. */
3737 static bool
3738 atomic_sync_required_p (Node_Id gnat_node)
3740 const Node_Id gnat_parent = Parent (gnat_node);
3741 Node_Kind kind;
3742 unsigned char attr_id;
3744 /* First, scan the node to find the Atomic_Sync_Required flag. */
3745 kind = Nkind (gnat_node);
3746 if (kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
3748 gnat_node = Expression (gnat_node);
3749 kind = Nkind (gnat_node);
3752 switch (kind)
3754 case N_Expanded_Name:
3755 case N_Explicit_Dereference:
3756 case N_Identifier:
3757 case N_Indexed_Component:
3758 case N_Selected_Component:
3759 if (!Atomic_Sync_Required (gnat_node))
3760 return false;
3761 break;
3763 default:
3764 return false;
3767 /* Then, scan the parent to find out cases where the flag is irrelevant. */
3768 kind = Nkind (gnat_parent);
3769 switch (kind)
3771 case N_Attribute_Reference:
3772 attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
3773 /* Do not mess up machine code insertions. */
3774 if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
3775 return false;
3776 break;
3778 case N_Object_Renaming_Declaration:
3779 /* Do not generate a function call as a renamed object. */
3780 return false;
3782 default:
3783 break;
3786 return true;
3789 /* Create a temporary variable with PREFIX and TYPE, and return it. */
3791 static tree
3792 create_temporary (const char *prefix, tree type)
3794 tree gnu_temp = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
3795 type, NULL_TREE, false, false, false, false,
3796 NULL, Empty);
3797 DECL_ARTIFICIAL (gnu_temp) = 1;
3798 DECL_IGNORED_P (gnu_temp) = 1;
3800 return gnu_temp;
3803 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
3804 Put the initialization statement into GNU_INIT_STMT and annotate it with
3805 the SLOC of GNAT_NODE. Return the temporary variable. */
3807 static tree
3808 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
3809 Node_Id gnat_node)
3811 tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
3813 *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
3814 set_expr_location_from_node (*gnu_init_stmt, gnat_node);
3816 return gnu_temp;
3819 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
3820 or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
3821 GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
3822 If GNU_TARGET is non-null, this must be a function call on the RHS of a
3823 N_Assignment_Statement and the result is to be placed into that object.
3824 If, in addition, ATOMIC_SYNC is true, then the assignment to GNU_TARGET
3825 requires atomic synchronization. */
3827 static tree
3828 Call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
3829 bool atomic_sync)
3831 const bool function_call = (Nkind (gnat_node) == N_Function_Call);
3832 const bool returning_value = (function_call && !gnu_target);
3833 /* The GCC node corresponding to the GNAT subprogram name. This can either
3834 be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
3835 or an indirect reference expression (an INDIRECT_REF node) pointing to a
3836 subprogram. */
3837 tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
3838 /* The FUNCTION_TYPE node giving the GCC type of the subprogram. */
3839 tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
3840 /* The return type of the FUNCTION_TYPE. */
3841 tree gnu_result_type = TREE_TYPE (gnu_subprog_type);
3842 tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
3843 vec<tree, va_gc> *gnu_actual_vec = NULL;
3844 tree gnu_name_list = NULL_TREE;
3845 tree gnu_stmt_list = NULL_TREE;
3846 tree gnu_after_list = NULL_TREE;
3847 tree gnu_retval = NULL_TREE;
3848 tree gnu_call, gnu_result;
3849 bool went_into_elab_proc = false;
3850 bool pushed_binding_level = false;
3851 Entity_Id gnat_formal;
3852 Node_Id gnat_actual;
3854 gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
3856 /* If we are calling a stubbed function, raise Program_Error, but Elaborate
3857 all our args first. */
3858 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
3860 tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
3861 gnat_node, N_Raise_Program_Error);
3863 for (gnat_actual = First_Actual (gnat_node);
3864 Present (gnat_actual);
3865 gnat_actual = Next_Actual (gnat_actual))
3866 add_stmt (gnat_to_gnu (gnat_actual));
3868 if (returning_value)
3870 *gnu_result_type_p = gnu_result_type;
3871 return build1 (NULL_EXPR, gnu_result_type, call_expr);
3874 return call_expr;
3877 /* The only way we can be making a call via an access type is if Name is an
3878 explicit dereference. In that case, get the list of formal args from the
3879 type the access type is pointing to. Otherwise, get the formals from the
3880 entity being called. */
3881 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
3882 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
3883 else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
3884 /* Assume here that this must be 'Elab_Body or 'Elab_Spec. */
3885 gnat_formal = Empty;
3886 else
3887 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
3889 /* The lifetime of the temporaries created for the call ends right after the
3890 return value is copied, so we can give them the scope of the elaboration
3891 routine at top level. */
3892 if (!current_function_decl)
3894 current_function_decl = get_elaboration_procedure ();
3895 went_into_elab_proc = true;
3898 /* First, create the temporary for the return value when:
3900 1. There is no target and the function has copy-in/copy-out parameters,
3901 because we need to preserve the return value before copying back the
3902 parameters.
3904 2. There is no target and this is not an object declaration, and the
3905 return type has variable size, because in these cases the gimplifier
3906 cannot create the temporary.
3908 3. There is a target and it is a slice or an array with fixed size,
3909 and the return type has variable size, because the gimplifier
3910 doesn't handle these cases.
3912 This must be done before we push a binding level around the call, since
3913 we will pop it before copying the return value. */
3914 if (function_call
3915 && ((!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))
3916 || (!gnu_target
3917 && Nkind (Parent (gnat_node)) != N_Object_Declaration
3918 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)
3919 || (gnu_target
3920 && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
3921 || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
3922 && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
3923 == INTEGER_CST))
3924 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)))
3925 gnu_retval = create_temporary ("R", gnu_result_type);
3927 /* Create the list of the actual parameters as GCC expects it, namely a
3928 chain of TREE_LIST nodes in which the TREE_VALUE field of each node
3929 is an expression and the TREE_PURPOSE field is null. But skip Out
3930 parameters not passed by reference and that need not be copied in. */
3931 for (gnat_actual = First_Actual (gnat_node);
3932 Present (gnat_actual);
3933 gnat_formal = Next_Formal_With_Extras (gnat_formal),
3934 gnat_actual = Next_Actual (gnat_actual))
3936 tree gnu_formal = present_gnu_tree (gnat_formal)
3937 ? get_gnu_tree (gnat_formal) : NULL_TREE;
3938 tree gnu_formal_type = gnat_to_gnu_type (Etype (gnat_formal));
3939 const bool is_true_formal_parm
3940 = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
3941 const bool is_by_ref_formal_parm
3942 = is_true_formal_parm
3943 && (DECL_BY_REF_P (gnu_formal)
3944 || DECL_BY_COMPONENT_PTR_P (gnu_formal));
3945 /* In the Out or In Out case, we must suppress conversions that yield
3946 an lvalue but can nevertheless cause the creation of a temporary,
3947 because we need the real object in this case, either to pass its
3948 address if it's passed by reference or as target of the back copy
3949 done after the call if it uses the copy-in/copy-out mechanism.
3950 We do it in the In case too, except for an unchecked conversion
3951 because it alone can cause the actual to be misaligned and the
3952 addressability test is applied to the real object. */
3953 const bool suppress_type_conversion
3954 = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
3955 && Ekind (gnat_formal) != E_In_Parameter)
3956 || (Nkind (gnat_actual) == N_Type_Conversion
3957 && Is_Composite_Type (Underlying_Type (Etype (gnat_formal)))));
3958 Node_Id gnat_name = suppress_type_conversion
3959 ? Expression (gnat_actual) : gnat_actual;
3960 tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
3961 tree gnu_actual;
3963 /* If it's possible we may need to use this expression twice, make sure
3964 that any side-effects are handled via SAVE_EXPRs; likewise if we need
3965 to force side-effects before the call.
3966 ??? This is more conservative than we need since we don't need to do
3967 this for pass-by-ref with no conversion. */
3968 if (Ekind (gnat_formal) != E_In_Parameter)
3969 gnu_name = gnat_stabilize_reference (gnu_name, true, NULL);
3971 /* If we are passing a non-addressable parameter by reference, pass the
3972 address of a copy. In the Out or In Out case, set up to copy back
3973 out after the call. */
3974 if (is_by_ref_formal_parm
3975 && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
3976 && !addressable_p (gnu_name, gnu_name_type))
3978 bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
3979 tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
3981 /* Do not issue warnings for CONSTRUCTORs since this is not a copy
3982 but sort of an instantiation for them. */
3983 if (TREE_CODE (gnu_name) == CONSTRUCTOR)
3986 /* If the type is passed by reference, a copy is not allowed. */
3987 else if (TYPE_IS_BY_REFERENCE_P (gnu_formal_type))
3988 post_error ("misaligned actual cannot be passed by reference",
3989 gnat_actual);
3991 /* For users of Starlet we issue a warning because the interface
3992 apparently assumes that by-ref parameters outlive the procedure
3993 invocation. The code still will not work as intended, but we
3994 cannot do much better since low-level parts of the back-end
3995 would allocate temporaries at will because of the misalignment
3996 if we did not do so here. */
3997 else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
3999 post_error
4000 ("?possible violation of implicit assumption", gnat_actual);
4001 post_error_ne
4002 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
4003 Entity (Name (gnat_node)));
4004 post_error_ne ("?because of misalignment of &", gnat_actual,
4005 gnat_formal);
4008 /* If the actual type of the object is already the nominal type,
4009 we have nothing to do, except if the size is self-referential
4010 in which case we'll remove the unpadding below. */
4011 if (TREE_TYPE (gnu_name) == gnu_name_type
4012 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
4015 /* Otherwise remove the unpadding from all the objects. */
4016 else if (TREE_CODE (gnu_name) == COMPONENT_REF
4017 && TYPE_IS_PADDING_P
4018 (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
4019 gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
4021 /* Otherwise convert to the nominal type of the object if needed.
4022 There are several cases in which we need to make the temporary
4023 using this type instead of the actual type of the object when
4024 they are distinct, because the expectations of the callee would
4025 otherwise not be met:
4026 - if it's a justified modular type,
4027 - if the actual type is a smaller form of it,
4028 - if it's a smaller form of the actual type. */
4029 else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
4030 && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
4031 || smaller_form_type_p (TREE_TYPE (gnu_name),
4032 gnu_name_type)))
4033 || (INTEGRAL_TYPE_P (gnu_name_type)
4034 && smaller_form_type_p (gnu_name_type,
4035 TREE_TYPE (gnu_name))))
4036 gnu_name = convert (gnu_name_type, gnu_name);
4038 /* If this is an In Out or Out parameter and we're returning a value,
4039 we need to create a temporary for the return value because we must
4040 preserve it before copying back at the very end. */
4041 if (!in_param && returning_value && !gnu_retval)
4042 gnu_retval = create_temporary ("R", gnu_result_type);
4044 /* If we haven't pushed a binding level, push a new one. This will
4045 narrow the lifetime of the temporary we are about to make as much
4046 as possible. The drawback is that we'd need to create a temporary
4047 for the return value, if any (see comment before the loop). So do
4048 it only when this temporary was already created just above. */
4049 if (!pushed_binding_level && !(in_param && returning_value))
4051 start_stmt_group ();
4052 gnat_pushlevel ();
4053 pushed_binding_level = true;
4056 /* Create an explicit temporary holding the copy. */
4057 gnu_temp
4058 = create_init_temporary ("A", gnu_name, &gnu_stmt, gnat_actual);
4060 /* But initialize it on the fly like for an implicit temporary as
4061 we aren't necessarily having a statement list. */
4062 gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
4063 gnu_temp);
4065 /* Set up to move the copy back to the original if needed. */
4066 if (!in_param)
4068 /* If the original is a COND_EXPR whose first arm isn't meant to
4069 be further used, just deal with the second arm. This is very
4070 likely the conditional expression built for a check. */
4071 if (TREE_CODE (gnu_orig) == COND_EXPR
4072 && TREE_CODE (TREE_OPERAND (gnu_orig, 1)) == COMPOUND_EXPR
4073 && integer_zerop
4074 (TREE_OPERAND (TREE_OPERAND (gnu_orig, 1), 1)))
4075 gnu_orig = TREE_OPERAND (gnu_orig, 2);
4077 gnu_stmt
4078 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig, gnu_temp);
4079 set_expr_location_from_node (gnu_stmt, gnat_node);
4081 append_to_statement_list (gnu_stmt, &gnu_after_list);
4085 /* Start from the real object and build the actual. */
4086 gnu_actual = gnu_name;
4088 /* If this is an atomic access of an In or In Out parameter for which
4089 synchronization is required, build the atomic load. */
4090 if (is_true_formal_parm
4091 && !is_by_ref_formal_parm
4092 && Ekind (gnat_formal) != E_Out_Parameter
4093 && atomic_sync_required_p (gnat_actual))
4094 gnu_actual = build_atomic_load (gnu_actual);
4096 /* If this was a procedure call, we may not have removed any padding.
4097 So do it here for the part we will use as an input, if any. */
4098 if (Ekind (gnat_formal) != E_Out_Parameter
4099 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4100 gnu_actual
4101 = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
4103 /* Put back the conversion we suppressed above in the computation of the
4104 real object. And even if we didn't suppress any conversion there, we
4105 may have suppressed a conversion to the Etype of the actual earlier,
4106 since the parent is a procedure call, so put it back here. */
4107 if (suppress_type_conversion
4108 && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4109 gnu_actual
4110 = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
4111 gnu_actual, No_Truncation (gnat_actual));
4112 else
4113 gnu_actual
4114 = convert (gnat_to_gnu_type (Etype (gnat_actual)), gnu_actual);
4116 /* Make sure that the actual is in range of the formal's type. */
4117 if (Ekind (gnat_formal) != E_Out_Parameter
4118 && Do_Range_Check (gnat_actual))
4119 gnu_actual
4120 = emit_range_check (gnu_actual, Etype (gnat_formal), gnat_actual);
4122 /* Unless this is an In parameter, we must remove any justified modular
4123 building from GNU_NAME to get an lvalue. */
4124 if (Ekind (gnat_formal) != E_In_Parameter
4125 && TREE_CODE (gnu_name) == CONSTRUCTOR
4126 && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
4127 && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
4128 gnu_name
4129 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))), gnu_name);
4131 /* First see if the parameter is passed by reference. */
4132 if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
4134 if (Ekind (gnat_formal) != E_In_Parameter)
4136 /* In Out or Out parameters passed by reference don't use the
4137 copy-in/copy-out mechanism so the address of the real object
4138 must be passed to the function. */
4139 gnu_actual = gnu_name;
4141 /* If we have a padded type, be sure we've removed padding. */
4142 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4143 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
4144 gnu_actual);
4146 /* If we have the constructed subtype of an aliased object
4147 with an unconstrained nominal subtype, the type of the
4148 actual includes the template, although it is formally
4149 constrained. So we need to convert it back to the real
4150 constructed subtype to retrieve the constrained part
4151 and takes its address. */
4152 if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
4153 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
4154 && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
4155 && Is_Array_Type (Underlying_Type (Etype (gnat_actual))))
4156 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4157 gnu_actual);
4160 /* There is no need to convert the actual to the formal's type before
4161 taking its address. The only exception is for unconstrained array
4162 types because of the way we build fat pointers. */
4163 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4165 /* Put back a view conversion for In Out or Out parameters. */
4166 if (Ekind (gnat_formal) != E_In_Parameter)
4167 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4168 gnu_actual);
4169 gnu_actual = convert (gnu_formal_type, gnu_actual);
4172 /* The symmetry of the paths to the type of an entity is broken here
4173 since arguments don't know that they will be passed by ref. */
4174 gnu_formal_type = TREE_TYPE (gnu_formal);
4175 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4178 /* Then see if the parameter is an array passed to a foreign convention
4179 subprogram. */
4180 else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
4182 gnu_formal_type = TREE_TYPE (gnu_formal);
4183 gnu_actual = maybe_implicit_deref (gnu_actual);
4184 gnu_actual = maybe_unconstrained_array (gnu_actual);
4186 if (TYPE_IS_PADDING_P (gnu_formal_type))
4188 gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
4189 gnu_actual = convert (gnu_formal_type, gnu_actual);
4192 /* Take the address of the object and convert to the proper pointer
4193 type. We'd like to actually compute the address of the beginning
4194 of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
4195 possibility that the ARRAY_REF might return a constant and we'd be
4196 getting the wrong address. Neither approach is exactly correct,
4197 but this is the most likely to work in all cases. */
4198 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4201 /* Otherwise the parameter is passed by copy. */
4202 else
4204 tree gnu_size;
4206 if (Ekind (gnat_formal) != E_In_Parameter)
4207 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
4209 /* If we didn't create a PARM_DECL for the formal, this means that
4210 it is an Out parameter not passed by reference and that need not
4211 be copied in. In this case, the value of the actual need not be
4212 read. However, we still need to make sure that its side-effects
4213 are evaluated before the call, so we evaluate its address. */
4214 if (!is_true_formal_parm)
4216 if (TREE_SIDE_EFFECTS (gnu_name))
4218 tree addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_name);
4219 append_to_statement_list (addr, &gnu_stmt_list);
4221 continue;
4224 gnu_actual = convert (gnu_formal_type, gnu_actual);
4226 /* If this is 'Null_Parameter, pass a zero even though we are
4227 dereferencing it. */
4228 if (TREE_CODE (gnu_actual) == INDIRECT_REF
4229 && TREE_PRIVATE (gnu_actual)
4230 && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
4231 && TREE_CODE (gnu_size) == INTEGER_CST
4232 && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
4233 gnu_actual
4234 = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
4235 convert (gnat_type_for_size
4236 (TREE_INT_CST_LOW (gnu_size), 1),
4237 integer_zero_node),
4238 false);
4239 else
4240 gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
4243 vec_safe_push (gnu_actual_vec, gnu_actual);
4246 gnu_call
4247 = build_call_vec (gnu_result_type, gnu_subprog_addr, gnu_actual_vec);
4248 set_expr_location_from_node (gnu_call, gnat_node);
4250 /* If we have created a temporary for the return value, initialize it. */
4251 if (gnu_retval)
4253 tree gnu_stmt
4254 = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
4255 set_expr_location_from_node (gnu_stmt, gnat_node);
4256 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4257 gnu_call = gnu_retval;
4260 /* If this is a subprogram with copy-in/copy-out parameters, we need to
4261 unpack the valued returned from the function into the In Out or Out
4262 parameters. We deal with the function return (if this is an Ada
4263 function) below. */
4264 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4266 /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
4267 copy-out parameters. */
4268 tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
4269 const int length = list_length (gnu_cico_list);
4271 /* The call sequence must contain one and only one call, even though the
4272 function is pure. Save the result into a temporary if needed. */
4273 if (length > 1)
4275 if (!gnu_retval)
4277 tree gnu_stmt;
4278 /* If we haven't pushed a binding level, push a new one. This
4279 will narrow the lifetime of the temporary we are about to
4280 make as much as possible. */
4281 if (!pushed_binding_level)
4283 start_stmt_group ();
4284 gnat_pushlevel ();
4285 pushed_binding_level = true;
4287 gnu_call
4288 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
4289 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4292 gnu_name_list = nreverse (gnu_name_list);
4295 /* The first entry is for the actual return value if this is a
4296 function, so skip it. */
4297 if (function_call)
4298 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4300 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4301 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4302 else
4303 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4305 for (gnat_actual = First_Actual (gnat_node);
4306 Present (gnat_actual);
4307 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4308 gnat_actual = Next_Actual (gnat_actual))
4309 /* If we are dealing with a copy-in/copy-out parameter, we must
4310 retrieve its value from the record returned in the call. */
4311 if (!(present_gnu_tree (gnat_formal)
4312 && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
4313 && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
4314 || DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))))
4315 && Ekind (gnat_formal) != E_In_Parameter)
4317 /* Get the value to assign to this Out or In Out parameter. It is
4318 either the result of the function if there is only a single such
4319 parameter or the appropriate field from the record returned. */
4320 tree gnu_result
4321 = length == 1
4322 ? gnu_call
4323 : build_component_ref (gnu_call, NULL_TREE,
4324 TREE_PURPOSE (gnu_cico_list), false);
4326 /* If the actual is a conversion, get the inner expression, which
4327 will be the real destination, and convert the result to the
4328 type of the actual parameter. */
4329 tree gnu_actual
4330 = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
4332 /* If the result is a padded type, remove the padding. */
4333 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
4334 gnu_result
4335 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
4336 gnu_result);
4338 /* If the actual is a type conversion, the real target object is
4339 denoted by the inner Expression and we need to convert the
4340 result to the associated type.
4341 We also need to convert our gnu assignment target to this type
4342 if the corresponding GNU_NAME was constructed from the GNAT
4343 conversion node and not from the inner Expression. */
4344 if (Nkind (gnat_actual) == N_Type_Conversion)
4346 gnu_result
4347 = convert_with_check
4348 (Etype (Expression (gnat_actual)), gnu_result,
4349 Do_Overflow_Check (gnat_actual),
4350 Do_Range_Check (Expression (gnat_actual)),
4351 Float_Truncate (gnat_actual), gnat_actual);
4353 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
4354 gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
4357 /* Unchecked conversions as actuals for Out parameters are not
4358 allowed in user code because they are not variables, but do
4359 occur in front-end expansions. The associated GNU_NAME is
4360 always obtained from the inner expression in such cases. */
4361 else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4362 gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
4363 gnu_result,
4364 No_Truncation (gnat_actual));
4365 else
4367 if (Do_Range_Check (gnat_actual))
4368 gnu_result
4369 = emit_range_check (gnu_result, Etype (gnat_actual),
4370 gnat_actual);
4372 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
4373 && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
4374 gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
4377 if (atomic_sync_required_p (gnat_actual))
4378 gnu_result = build_atomic_store (gnu_actual, gnu_result);
4379 else
4380 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
4381 gnu_actual, gnu_result);
4382 set_expr_location_from_node (gnu_result, gnat_node);
4383 append_to_statement_list (gnu_result, &gnu_stmt_list);
4384 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4385 gnu_name_list = TREE_CHAIN (gnu_name_list);
4389 /* If this is a function call, the result is the call expression unless a
4390 target is specified, in which case we copy the result into the target
4391 and return the assignment statement. */
4392 if (function_call)
4394 /* If this is a function with copy-in/copy-out parameters, extract the
4395 return value from it and update the return type. */
4396 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4398 tree gnu_elmt = TYPE_CI_CO_LIST (gnu_subprog_type);
4399 gnu_call = build_component_ref (gnu_call, NULL_TREE,
4400 TREE_PURPOSE (gnu_elmt), false);
4401 gnu_result_type = TREE_TYPE (gnu_call);
4404 /* If the function returns an unconstrained array or by direct reference,
4405 we have to dereference the pointer. */
4406 if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
4407 || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
4408 gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
4410 if (gnu_target)
4412 Node_Id gnat_parent = Parent (gnat_node);
4413 enum tree_code op_code;
4415 /* If range check is needed, emit code to generate it. */
4416 if (Do_Range_Check (gnat_node))
4417 gnu_call
4418 = emit_range_check (gnu_call, Etype (Name (gnat_parent)),
4419 gnat_parent);
4421 /* ??? If the return type has variable size, then force the return
4422 slot optimization as we would not be able to create a temporary.
4423 Likewise if it was unconstrained as we would copy too much data.
4424 That's what has been done historically. */
4425 if (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
4426 || (TYPE_IS_PADDING_P (gnu_result_type)
4427 && CONTAINS_PLACEHOLDER_P
4428 (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_result_type))))))
4429 op_code = INIT_EXPR;
4430 else
4431 op_code = MODIFY_EXPR;
4433 if (atomic_sync)
4434 gnu_call = build_atomic_store (gnu_target, gnu_call);
4435 else
4436 gnu_call
4437 = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
4438 set_expr_location_from_node (gnu_call, gnat_parent);
4439 append_to_statement_list (gnu_call, &gnu_stmt_list);
4441 else
4442 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
4445 /* Otherwise, if this is a procedure call statement without copy-in/copy-out
4446 parameters, the result is just the call statement. */
4447 else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
4448 append_to_statement_list (gnu_call, &gnu_stmt_list);
4450 /* Finally, add the copy back statements, if any. */
4451 append_to_statement_list (gnu_after_list, &gnu_stmt_list);
4453 if (went_into_elab_proc)
4454 current_function_decl = NULL_TREE;
4456 /* If we have pushed a binding level, pop it and finish up the enclosing
4457 statement group. */
4458 if (pushed_binding_level)
4460 add_stmt (gnu_stmt_list);
4461 gnat_poplevel ();
4462 gnu_result = end_stmt_group ();
4465 /* Otherwise, retrieve the statement list, if any. */
4466 else if (gnu_stmt_list)
4467 gnu_result = gnu_stmt_list;
4469 /* Otherwise, just return the call expression. */
4470 else
4471 return gnu_call;
4473 /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
4474 But first simplify if we have only one statement in the list. */
4475 if (returning_value)
4477 tree first = expr_first (gnu_result), last = expr_last (gnu_result);
4478 if (first == last)
4479 gnu_result = first;
4480 gnu_result
4481 = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
4484 return gnu_result;
4487 /* Subroutine of gnat_to_gnu to translate gnat_node, an
4488 N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned. */
4490 static tree
4491 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
4493 tree gnu_jmpsave_decl = NULL_TREE;
4494 tree gnu_jmpbuf_decl = NULL_TREE;
4495 /* If just annotating, ignore all EH and cleanups. */
4496 bool gcc_zcx = (!type_annotate_only
4497 && Present (Exception_Handlers (gnat_node))
4498 && Exception_Mechanism == Back_End_Exceptions);
4499 bool setjmp_longjmp
4500 = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
4501 && Exception_Mechanism == Setjmp_Longjmp);
4502 bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
4503 bool binding_for_block = (at_end || gcc_zcx || setjmp_longjmp);
4504 tree gnu_inner_block; /* The statement(s) for the block itself. */
4505 tree gnu_result;
4506 tree gnu_expr;
4507 Node_Id gnat_temp;
4508 /* Node providing the sloc for the cleanup actions. */
4509 Node_Id gnat_cleanup_loc_node = (Present (End_Label (gnat_node)) ?
4510 End_Label (gnat_node) :
4511 gnat_node);
4513 /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
4514 and we have our own SJLJ mechanism. To call the GCC mechanism, we call
4515 add_cleanup, and when we leave the binding, end_stmt_group will create
4516 the TRY_FINALLY_EXPR.
4518 ??? The region level calls down there have been specifically put in place
4519 for a ZCX context and currently the order in which things are emitted
4520 (region/handlers) is different from the SJLJ case. Instead of putting
4521 other calls with different conditions at other places for the SJLJ case,
4522 it seems cleaner to reorder things for the SJLJ case and generalize the
4523 condition to make it not ZCX specific.
4525 If there are any exceptions or cleanup processing involved, we need an
4526 outer statement group (for Setjmp_Longjmp) and binding level. */
4527 if (binding_for_block)
4529 start_stmt_group ();
4530 gnat_pushlevel ();
4533 /* If using setjmp_longjmp, make the variables for the setjmp buffer and save
4534 area for address of previous buffer. Do this first since we need to have
4535 the setjmp buf known for any decls in this block. */
4536 if (setjmp_longjmp)
4538 gnu_jmpsave_decl
4539 = create_var_decl (get_identifier ("JMPBUF_SAVE"), NULL_TREE,
4540 jmpbuf_ptr_type,
4541 build_call_n_expr (get_jmpbuf_decl, 0),
4542 false, false, false, false, NULL, gnat_node);
4543 DECL_ARTIFICIAL (gnu_jmpsave_decl) = 1;
4545 /* The __builtin_setjmp receivers will immediately reinstall it. Now
4546 because of the unstructured form of EH used by setjmp_longjmp, there
4547 might be forward edges going to __builtin_setjmp receivers on which
4548 it is uninitialized, although they will never be actually taken. */
4549 TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
4550 gnu_jmpbuf_decl
4551 = create_var_decl (get_identifier ("JMP_BUF"), NULL_TREE,
4552 jmpbuf_type,
4553 NULL_TREE,
4554 false, false, false, false, NULL, gnat_node);
4555 DECL_ARTIFICIAL (gnu_jmpbuf_decl) = 1;
4557 set_block_jmpbuf_decl (gnu_jmpbuf_decl);
4559 /* When we exit this block, restore the saved value. */
4560 add_cleanup (build_call_n_expr (set_jmpbuf_decl, 1, gnu_jmpsave_decl),
4561 gnat_cleanup_loc_node);
4564 /* If we are to call a function when exiting this block, add a cleanup
4565 to the binding level we made above. Note that add_cleanup is FIFO
4566 so we must register this cleanup after the EH cleanup just above. */
4567 if (at_end)
4568 add_cleanup (build_call_n_expr (gnat_to_gnu (At_End_Proc (gnat_node)), 0),
4569 gnat_cleanup_loc_node);
4571 /* Now build the tree for the declarations and statements inside this block.
4572 If this is SJLJ, set our jmp_buf as the current buffer. */
4573 start_stmt_group ();
4575 if (setjmp_longjmp)
4576 add_stmt (build_call_n_expr (set_jmpbuf_decl, 1,
4577 build_unary_op (ADDR_EXPR, NULL_TREE,
4578 gnu_jmpbuf_decl)));
4580 if (Present (First_Real_Statement (gnat_node)))
4581 process_decls (Statements (gnat_node), Empty,
4582 First_Real_Statement (gnat_node), true, true);
4584 /* Generate code for each statement in the block. */
4585 for (gnat_temp = (Present (First_Real_Statement (gnat_node))
4586 ? First_Real_Statement (gnat_node)
4587 : First (Statements (gnat_node)));
4588 Present (gnat_temp); gnat_temp = Next (gnat_temp))
4589 add_stmt (gnat_to_gnu (gnat_temp));
4590 gnu_inner_block = end_stmt_group ();
4592 /* Now generate code for the two exception models, if either is relevant for
4593 this block. */
4594 if (setjmp_longjmp)
4596 tree *gnu_else_ptr = 0;
4597 tree gnu_handler;
4599 /* Make a binding level for the exception handling declarations and code
4600 and set up gnu_except_ptr_stack for the handlers to use. */
4601 start_stmt_group ();
4602 gnat_pushlevel ();
4604 vec_safe_push (gnu_except_ptr_stack,
4605 create_var_decl (get_identifier ("EXCEPT_PTR"), NULL_TREE,
4606 build_pointer_type (except_type_node),
4607 build_call_n_expr (get_excptr_decl, 0),
4608 false, false, false, false,
4609 NULL, gnat_node));
4611 /* Generate code for each handler. The N_Exception_Handler case does the
4612 real work and returns a COND_EXPR for each handler, which we chain
4613 together here. */
4614 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4615 Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
4617 gnu_expr = gnat_to_gnu (gnat_temp);
4619 /* If this is the first one, set it as the outer one. Otherwise,
4620 point the "else" part of the previous handler to us. Then point
4621 to our "else" part. */
4622 if (!gnu_else_ptr)
4623 add_stmt (gnu_expr);
4624 else
4625 *gnu_else_ptr = gnu_expr;
4627 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
4630 /* If none of the exception handlers did anything, re-raise but do not
4631 defer abortion. */
4632 gnu_expr = build_call_n_expr (raise_nodefer_decl, 1,
4633 gnu_except_ptr_stack->last ());
4634 set_expr_location_from_node
4635 (gnu_expr,
4636 Present (End_Label (gnat_node)) ? End_Label (gnat_node) : gnat_node);
4638 if (gnu_else_ptr)
4639 *gnu_else_ptr = gnu_expr;
4640 else
4641 add_stmt (gnu_expr);
4643 /* End the binding level dedicated to the exception handlers and get the
4644 whole statement group. */
4645 gnu_except_ptr_stack->pop ();
4646 gnat_poplevel ();
4647 gnu_handler = end_stmt_group ();
4649 /* If the setjmp returns 1, we restore our incoming longjmp value and
4650 then check the handlers. */
4651 start_stmt_group ();
4652 add_stmt_with_node (build_call_n_expr (set_jmpbuf_decl, 1,
4653 gnu_jmpsave_decl),
4654 gnat_node);
4655 add_stmt (gnu_handler);
4656 gnu_handler = end_stmt_group ();
4658 /* This block is now "if (setjmp) ... <handlers> else <block>". */
4659 gnu_result = build3 (COND_EXPR, void_type_node,
4660 (build_call_n_expr
4661 (setjmp_decl, 1,
4662 build_unary_op (ADDR_EXPR, NULL_TREE,
4663 gnu_jmpbuf_decl))),
4664 gnu_handler, gnu_inner_block);
4666 else if (gcc_zcx)
4668 tree gnu_handlers;
4669 location_t locus;
4671 /* First make a block containing the handlers. */
4672 start_stmt_group ();
4673 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4674 Present (gnat_temp);
4675 gnat_temp = Next_Non_Pragma (gnat_temp))
4676 add_stmt (gnat_to_gnu (gnat_temp));
4677 gnu_handlers = end_stmt_group ();
4679 /* Now make the TRY_CATCH_EXPR for the block. */
4680 gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
4681 gnu_inner_block, gnu_handlers);
4682 /* Set a location. We need to find a unique location for the dispatching
4683 code, otherwise we can get coverage or debugging issues. Try with
4684 the location of the end label. */
4685 if (Present (End_Label (gnat_node))
4686 && Sloc_to_locus (Sloc (End_Label (gnat_node)), &locus))
4687 SET_EXPR_LOCATION (gnu_result, locus);
4688 else
4689 /* Clear column information so that the exception handler of an
4690 implicit transient block does not incorrectly inherit the slocs
4691 of a decision, which would otherwise confuse control flow based
4692 coverage analysis tools. */
4693 set_expr_location_from_node1 (gnu_result, gnat_node, true);
4695 else
4696 gnu_result = gnu_inner_block;
4698 /* Now close our outer block, if we had to make one. */
4699 if (binding_for_block)
4701 add_stmt (gnu_result);
4702 gnat_poplevel ();
4703 gnu_result = end_stmt_group ();
4706 return gnu_result;
4709 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4710 to a GCC tree, which is returned. This is the variant for Setjmp_Longjmp
4711 exception handling. */
4713 static tree
4714 Exception_Handler_to_gnu_sjlj (Node_Id gnat_node)
4716 /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
4717 an "if" statement to select the proper exceptions. For "Others", exclude
4718 exceptions where Handled_By_Others is nonzero unless the All_Others flag
4719 is set. For "Non-ada", accept an exception if "Lang" is 'V'. */
4720 tree gnu_choice = boolean_false_node;
4721 tree gnu_body = build_stmt_group (Statements (gnat_node), false);
4722 Node_Id gnat_temp;
4724 for (gnat_temp = First (Exception_Choices (gnat_node));
4725 gnat_temp; gnat_temp = Next (gnat_temp))
4727 tree this_choice;
4729 if (Nkind (gnat_temp) == N_Others_Choice)
4731 if (All_Others (gnat_temp))
4732 this_choice = boolean_true_node;
4733 else
4734 this_choice
4735 = build_binary_op
4736 (EQ_EXPR, boolean_type_node,
4737 convert
4738 (integer_type_node,
4739 build_component_ref
4740 (build_unary_op
4741 (INDIRECT_REF, NULL_TREE,
4742 gnu_except_ptr_stack->last ()),
4743 get_identifier ("not_handled_by_others"), NULL_TREE,
4744 false)),
4745 integer_zero_node);
4748 else if (Nkind (gnat_temp) == N_Identifier
4749 || Nkind (gnat_temp) == N_Expanded_Name)
4751 Entity_Id gnat_ex_id = Entity (gnat_temp);
4752 tree gnu_expr;
4754 /* Exception may be a renaming. Recover original exception which is
4755 the one elaborated and registered. */
4756 if (Present (Renamed_Object (gnat_ex_id)))
4757 gnat_ex_id = Renamed_Object (gnat_ex_id);
4759 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4761 this_choice
4762 = build_binary_op
4763 (EQ_EXPR, boolean_type_node,
4764 gnu_except_ptr_stack->last (),
4765 convert (TREE_TYPE (gnu_except_ptr_stack->last ()),
4766 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
4768 else
4769 gcc_unreachable ();
4771 gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
4772 gnu_choice, this_choice);
4775 return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
4778 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4779 to a GCC tree, which is returned. This is the variant for ZCX. */
4781 static tree
4782 Exception_Handler_to_gnu_zcx (Node_Id gnat_node)
4784 tree gnu_etypes_list = NULL_TREE;
4785 tree gnu_current_exc_ptr, prev_gnu_incoming_exc_ptr;
4786 Node_Id gnat_temp;
4788 /* We build a TREE_LIST of nodes representing what exception types this
4789 handler can catch, with special cases for others and all others cases.
4791 Each exception type is actually identified by a pointer to the exception
4792 id, or to a dummy object for "others" and "all others". */
4793 for (gnat_temp = First (Exception_Choices (gnat_node));
4794 gnat_temp; gnat_temp = Next (gnat_temp))
4796 tree gnu_expr, gnu_etype;
4798 if (Nkind (gnat_temp) == N_Others_Choice)
4800 gnu_expr = All_Others (gnat_temp) ? all_others_decl : others_decl;
4801 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4803 else if (Nkind (gnat_temp) == N_Identifier
4804 || Nkind (gnat_temp) == N_Expanded_Name)
4806 Entity_Id gnat_ex_id = Entity (gnat_temp);
4808 /* Exception may be a renaming. Recover original exception which is
4809 the one elaborated and registered. */
4810 if (Present (Renamed_Object (gnat_ex_id)))
4811 gnat_ex_id = Renamed_Object (gnat_ex_id);
4813 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4814 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4816 else
4817 gcc_unreachable ();
4819 /* The GCC interface expects NULL to be passed for catch all handlers, so
4820 it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
4821 is integer_zero_node. It would not work, however, because GCC's
4822 notion of "catch all" is stronger than our notion of "others". Until
4823 we correctly use the cleanup interface as well, doing that would
4824 prevent the "all others" handlers from being seen, because nothing
4825 can be caught beyond a catch all from GCC's point of view. */
4826 gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
4829 start_stmt_group ();
4830 gnat_pushlevel ();
4832 /* Expand a call to the begin_handler hook at the beginning of the handler,
4833 and arrange for a call to the end_handler hook to occur on every possible
4834 exit path.
4836 The hooks expect a pointer to the low level occurrence. This is required
4837 for our stack management scheme because a raise inside the handler pushes
4838 a new occurrence on top of the stack, which means that this top does not
4839 necessarily match the occurrence this handler was dealing with.
4841 __builtin_eh_pointer references the exception occurrence being
4842 propagated. Upon handler entry, this is the exception for which the
4843 handler is triggered. This might not be the case upon handler exit,
4844 however, as we might have a new occurrence propagated by the handler's
4845 body, and the end_handler hook called as a cleanup in this context.
4847 We use a local variable to retrieve the incoming value at handler entry
4848 time, and reuse it to feed the end_handler hook's argument at exit. */
4850 gnu_current_exc_ptr
4851 = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
4852 1, integer_zero_node);
4853 prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
4854 gnu_incoming_exc_ptr = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
4855 ptr_type_node, gnu_current_exc_ptr,
4856 false, false, false, false,
4857 NULL, gnat_node);
4859 add_stmt_with_node (build_call_n_expr (begin_handler_decl, 1,
4860 gnu_incoming_exc_ptr),
4861 gnat_node);
4863 /* Declare and initialize the choice parameter, if present. */
4864 if (Present (Choice_Parameter (gnat_node)))
4866 tree gnu_param
4867 = gnat_to_gnu_entity (Choice_Parameter (gnat_node), NULL_TREE, 1);
4869 add_stmt (build_call_n_expr
4870 (set_exception_parameter_decl, 2,
4871 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_param),
4872 gnu_incoming_exc_ptr));
4875 /* We don't have an End_Label at hand to set the location of the cleanup
4876 actions, so we use that of the exception handler itself instead. */
4877 add_cleanup (build_call_n_expr (end_handler_decl, 1, gnu_incoming_exc_ptr),
4878 gnat_node);
4879 add_stmt_list (Statements (gnat_node));
4880 gnat_poplevel ();
4882 gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
4884 return
4885 build2 (CATCH_EXPR, void_type_node, gnu_etypes_list, end_stmt_group ());
4888 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit. */
4890 static void
4891 Compilation_Unit_to_gnu (Node_Id gnat_node)
4893 const Node_Id gnat_unit = Unit (gnat_node);
4894 const bool body_p = (Nkind (gnat_unit) == N_Package_Body
4895 || Nkind (gnat_unit) == N_Subprogram_Body);
4896 const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
4897 Entity_Id gnat_entity;
4898 Node_Id gnat_pragma;
4899 /* Make the decl for the elaboration procedure. */
4900 tree gnu_elab_proc_decl
4901 = create_subprog_decl
4902 (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
4903 NULL_TREE, void_ftype, NULL_TREE, is_disabled, true, false, true, NULL,
4904 gnat_unit);
4905 struct elab_info *info;
4907 vec_safe_push (gnu_elab_proc_stack, gnu_elab_proc_decl);
4908 DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
4910 /* Initialize the information structure for the function. */
4911 allocate_struct_function (gnu_elab_proc_decl, false);
4912 set_cfun (NULL);
4914 current_function_decl = NULL_TREE;
4916 start_stmt_group ();
4917 gnat_pushlevel ();
4919 /* For a body, first process the spec if there is one. */
4920 if (Nkind (gnat_unit) == N_Package_Body
4921 || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
4922 add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
4924 if (type_annotate_only && gnat_node == Cunit (Main_Unit))
4926 elaborate_all_entities (gnat_node);
4928 if (Nkind (gnat_unit) == N_Subprogram_Declaration
4929 || Nkind (gnat_unit) == N_Generic_Package_Declaration
4930 || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
4931 return;
4934 /* Then process any pragmas and declarations preceding the unit. */
4935 for (gnat_pragma = First (Context_Items (gnat_node));
4936 Present (gnat_pragma);
4937 gnat_pragma = Next (gnat_pragma))
4938 if (Nkind (gnat_pragma) == N_Pragma)
4939 add_stmt (gnat_to_gnu (gnat_pragma));
4940 process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
4941 true, true);
4943 /* Process the unit itself. */
4944 add_stmt (gnat_to_gnu (gnat_unit));
4946 /* Generate code for all the inlined subprograms. */
4947 for (gnat_entity = First_Inlined_Subprogram (gnat_node);
4948 Present (gnat_entity);
4949 gnat_entity = Next_Inlined_Subprogram (gnat_entity))
4951 Node_Id gnat_body;
4953 /* Without optimization, process only the required subprograms. */
4954 if (!optimize && !Has_Pragma_Inline_Always (gnat_entity))
4955 continue;
4957 gnat_body = Parent (Declaration_Node (gnat_entity));
4958 if (Nkind (gnat_body) != N_Subprogram_Body)
4960 /* ??? This happens when only the spec of a package is provided. */
4961 if (No (Corresponding_Body (gnat_body)))
4962 continue;
4964 gnat_body
4965 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
4968 /* Define the entity first so we set DECL_EXTERNAL. */
4969 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
4970 add_stmt (gnat_to_gnu (gnat_body));
4973 /* Process any pragmas and actions following the unit. */
4974 add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
4975 add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
4976 finalize_from_limited_with ();
4978 /* Save away what we've made so far and record this potential elaboration
4979 procedure. */
4980 info = ggc_alloc<elab_info> ();
4981 set_current_block_context (gnu_elab_proc_decl);
4982 gnat_poplevel ();
4983 DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
4985 set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
4987 info->next = elab_info_list;
4988 info->elab_proc = gnu_elab_proc_decl;
4989 info->gnat_node = gnat_node;
4990 elab_info_list = info;
4992 /* Generate elaboration code for this unit, if necessary, and say whether
4993 we did or not. */
4994 gnu_elab_proc_stack->pop ();
4996 /* Invalidate the global renaming pointers. This is necessary because
4997 stabilization of the renamed entities may create SAVE_EXPRs which
4998 have been tied to a specific elaboration routine just above. */
4999 invalidate_global_renaming_pointers ();
5001 /* Force the processing for all nodes that remain in the queue. */
5002 process_deferred_decl_context (true);
5005 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Raise_xxx_Error,
5006 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to where
5007 we should place the result type. LABEL_P is true if there is a label to
5008 branch to for the exception. */
5010 static tree
5011 Raise_Error_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
5013 const Node_Kind kind = Nkind (gnat_node);
5014 const int reason = UI_To_Int (Reason (gnat_node));
5015 const Node_Id gnat_cond = Condition (gnat_node);
5016 const bool with_extra_info
5017 = Exception_Extra_Info
5018 && !No_Exception_Handlers_Set ()
5019 && !get_exception_label (kind);
5020 tree gnu_result = NULL_TREE, gnu_cond = NULL_TREE;
5022 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5024 switch (reason)
5026 case CE_Access_Check_Failed:
5027 if (with_extra_info)
5028 gnu_result = build_call_raise_column (reason, gnat_node);
5029 break;
5031 case CE_Index_Check_Failed:
5032 case CE_Range_Check_Failed:
5033 case CE_Invalid_Data:
5034 if (Present (gnat_cond) && Nkind (gnat_cond) == N_Op_Not)
5036 Node_Id gnat_range, gnat_index, gnat_type;
5037 tree gnu_index, gnu_low_bound, gnu_high_bound;
5038 struct range_check_info_d *rci;
5040 switch (Nkind (Right_Opnd (gnat_cond)))
5042 case N_In:
5043 gnat_range = Right_Opnd (Right_Opnd (gnat_cond));
5044 gcc_assert (Nkind (gnat_range) == N_Range);
5045 gnu_low_bound = gnat_to_gnu (Low_Bound (gnat_range));
5046 gnu_high_bound = gnat_to_gnu (High_Bound (gnat_range));
5047 break;
5049 case N_Op_Ge:
5050 gnu_low_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5051 gnu_high_bound = NULL_TREE;
5052 break;
5054 case N_Op_Le:
5055 gnu_low_bound = NULL_TREE;
5056 gnu_high_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5057 break;
5059 default:
5060 goto common;
5063 gnat_index = Left_Opnd (Right_Opnd (gnat_cond));
5064 gnat_type = Etype (gnat_index);
5065 gnu_index = gnat_to_gnu (gnat_index);
5067 if (with_extra_info
5068 && gnu_low_bound
5069 && gnu_high_bound
5070 && Known_Esize (gnat_type)
5071 && UI_To_Int (Esize (gnat_type)) <= 32)
5072 gnu_result
5073 = build_call_raise_range (reason, gnat_node, gnu_index,
5074 gnu_low_bound, gnu_high_bound);
5076 /* If loop unswitching is enabled, we try to compute invariant
5077 conditions for checks applied to iteration variables, i.e.
5078 conditions that are both independent of the variable and
5079 necessary in order for the check to fail in the course of
5080 some iteration, and prepend them to the original condition
5081 of the checks. This will make it possible later for the
5082 loop unswitching pass to replace the loop with two loops,
5083 one of which has the checks eliminated and the other has
5084 the original checks reinstated, and a run time selection.
5085 The former loop will be suitable for vectorization. */
5086 if (flag_unswitch_loops
5087 && (!gnu_low_bound
5088 || (gnu_low_bound = gnat_invariant_expr (gnu_low_bound)))
5089 && (!gnu_high_bound
5090 || (gnu_high_bound = gnat_invariant_expr (gnu_high_bound)))
5091 && (rci = push_range_check_info (gnu_index)))
5093 rci->low_bound = gnu_low_bound;
5094 rci->high_bound = gnu_high_bound;
5095 rci->type = get_unpadded_type (gnat_type);
5096 rci->invariant_cond = build1 (SAVE_EXPR, boolean_type_node,
5097 boolean_true_node);
5098 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5099 boolean_type_node,
5100 rci->invariant_cond,
5101 gnat_to_gnu (gnat_cond));
5104 break;
5106 default:
5107 break;
5110 common:
5111 if (!gnu_result)
5112 gnu_result = build_call_raise (reason, gnat_node, kind);
5113 set_expr_location_from_node (gnu_result, gnat_node);
5115 /* If the type is VOID, this is a statement, so we need to generate the code
5116 for the call. Handle a condition, if there is one. */
5117 if (VOID_TYPE_P (*gnu_result_type_p))
5119 if (Present (gnat_cond))
5121 if (!gnu_cond)
5122 gnu_cond = gnat_to_gnu (gnat_cond);
5123 gnu_result = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
5124 alloc_stmt_list ());
5127 else
5128 gnu_result = build1 (NULL_EXPR, *gnu_result_type_p, gnu_result);
5130 return gnu_result;
5133 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
5134 parameter of a call. */
5136 static bool
5137 lhs_or_actual_p (Node_Id gnat_node)
5139 Node_Id gnat_parent = Parent (gnat_node);
5140 Node_Kind kind = Nkind (gnat_parent);
5142 if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
5143 return true;
5145 if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
5146 && Name (gnat_parent) != gnat_node)
5147 return true;
5149 if (kind == N_Parameter_Association)
5150 return true;
5152 return false;
5155 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
5156 of an assignment or an actual parameter of a call. */
5158 static bool
5159 present_in_lhs_or_actual_p (Node_Id gnat_node)
5161 Node_Kind kind;
5163 if (lhs_or_actual_p (gnat_node))
5164 return true;
5166 kind = Nkind (Parent (gnat_node));
5168 if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
5169 && lhs_or_actual_p (Parent (gnat_node)))
5170 return true;
5172 return false;
5175 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
5176 as gigi is concerned. This is used to avoid conversions on the LHS. */
5178 static bool
5179 unchecked_conversion_nop (Node_Id gnat_node)
5181 Entity_Id from_type, to_type;
5183 /* The conversion must be on the LHS of an assignment or an actual parameter
5184 of a call. Otherwise, even if the conversion was essentially a no-op, it
5185 could de facto ensure type consistency and this should be preserved. */
5186 if (!lhs_or_actual_p (gnat_node))
5187 return false;
5189 from_type = Etype (Expression (gnat_node));
5191 /* We're interested in artificial conversions generated by the front-end
5192 to make private types explicit, e.g. in Expand_Assign_Array. */
5193 if (!Is_Private_Type (from_type))
5194 return false;
5196 from_type = Underlying_Type (from_type);
5197 to_type = Etype (gnat_node);
5199 /* The direct conversion to the underlying type is a no-op. */
5200 if (to_type == from_type)
5201 return true;
5203 /* For an array subtype, the conversion to the PAIT is a no-op. */
5204 if (Ekind (from_type) == E_Array_Subtype
5205 && to_type == Packed_Array_Impl_Type (from_type))
5206 return true;
5208 /* For a record subtype, the conversion to the type is a no-op. */
5209 if (Ekind (from_type) == E_Record_Subtype
5210 && to_type == Etype (from_type))
5211 return true;
5213 return false;
5216 /* This function is the driver of the GNAT to GCC tree transformation process.
5217 It is the entry point of the tree transformer. GNAT_NODE is the root of
5218 some GNAT tree. Return the root of the corresponding GCC tree. If this
5219 is an expression, return the GCC equivalent of the expression. If this
5220 is a statement, return the statement or add it to the current statement
5221 group, in which case anything returned is to be interpreted as occurring
5222 after anything added. */
5224 tree
5225 gnat_to_gnu (Node_Id gnat_node)
5227 const Node_Kind kind = Nkind (gnat_node);
5228 bool went_into_elab_proc = false;
5229 tree gnu_result = error_mark_node; /* Default to no value. */
5230 tree gnu_result_type = void_type_node;
5231 tree gnu_expr, gnu_lhs, gnu_rhs;
5232 Node_Id gnat_temp;
5234 /* Save node number for error message and set location information. */
5235 error_gnat_node = gnat_node;
5236 Sloc_to_locus (Sloc (gnat_node), &input_location);
5238 /* If this node is a statement and we are only annotating types, return an
5239 empty statement list. */
5240 if (type_annotate_only && IN (kind, N_Statement_Other_Than_Procedure_Call))
5241 return alloc_stmt_list ();
5243 /* If this node is a non-static subexpression and we are only annotating
5244 types, make this into a NULL_EXPR. */
5245 if (type_annotate_only
5246 && IN (kind, N_Subexpr)
5247 && kind != N_Identifier
5248 && !Compile_Time_Known_Value (gnat_node))
5249 return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
5250 build_call_raise (CE_Range_Check_Failed, gnat_node,
5251 N_Raise_Constraint_Error));
5253 if ((IN (kind, N_Statement_Other_Than_Procedure_Call)
5254 && kind != N_Null_Statement)
5255 || kind == N_Procedure_Call_Statement
5256 || kind == N_Label
5257 || kind == N_Implicit_Label_Declaration
5258 || kind == N_Handled_Sequence_Of_Statements
5259 || (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void))
5261 tree current_elab_proc = get_elaboration_procedure ();
5263 /* If this is a statement and we are at top level, it must be part of
5264 the elaboration procedure, so mark us as being in that procedure. */
5265 if (!current_function_decl)
5267 current_function_decl = current_elab_proc;
5268 went_into_elab_proc = true;
5271 /* If we are in the elaboration procedure, check if we are violating a
5272 No_Elaboration_Code restriction by having a statement there. Don't
5273 check for a possible No_Elaboration_Code restriction violation on
5274 N_Handled_Sequence_Of_Statements, as we want to signal an error on
5275 every nested real statement instead. This also avoids triggering
5276 spurious errors on dummy (empty) sequences created by the front-end
5277 for package bodies in some cases. */
5278 if (current_function_decl == current_elab_proc
5279 && kind != N_Handled_Sequence_Of_Statements)
5280 Check_Elaboration_Code_Allowed (gnat_node);
5283 switch (kind)
5285 /********************************/
5286 /* Chapter 2: Lexical Elements */
5287 /********************************/
5289 case N_Identifier:
5290 case N_Expanded_Name:
5291 case N_Operator_Symbol:
5292 case N_Defining_Identifier:
5293 gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
5295 /* If this is an atomic access on the RHS for which synchronization is
5296 required, build the atomic load. */
5297 if (atomic_sync_required_p (gnat_node)
5298 && !present_in_lhs_or_actual_p (gnat_node))
5299 gnu_result = build_atomic_load (gnu_result);
5300 break;
5302 case N_Integer_Literal:
5304 tree gnu_type;
5306 /* Get the type of the result, looking inside any padding and
5307 justified modular types. Then get the value in that type. */
5308 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
5310 if (TREE_CODE (gnu_type) == RECORD_TYPE
5311 && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
5312 gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
5314 gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
5316 /* If the result overflows (meaning it doesn't fit in its base type),
5317 abort. We would like to check that the value is within the range
5318 of the subtype, but that causes problems with subtypes whose usage
5319 will raise Constraint_Error and with biased representation, so
5320 we don't. */
5321 gcc_assert (!TREE_OVERFLOW (gnu_result));
5323 break;
5325 case N_Character_Literal:
5326 /* If a Entity is present, it means that this was one of the
5327 literals in a user-defined character type. In that case,
5328 just return the value in the CONST_DECL. Otherwise, use the
5329 character code. In that case, the base type should be an
5330 INTEGER_TYPE, but we won't bother checking for that. */
5331 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5332 if (Present (Entity (gnat_node)))
5333 gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
5334 else
5335 gnu_result
5336 = build_int_cst_type
5337 (gnu_result_type, UI_To_CC (Char_Literal_Value (gnat_node)));
5338 break;
5340 case N_Real_Literal:
5341 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5343 /* If this is of a fixed-point type, the value we want is the value of
5344 the corresponding integer. */
5345 if (IN (Ekind (Underlying_Type (Etype (gnat_node))), Fixed_Point_Kind))
5347 gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
5348 gnu_result_type);
5349 gcc_assert (!TREE_OVERFLOW (gnu_result));
5352 else
5354 Ureal ur_realval = Realval (gnat_node);
5356 /* First convert the value to a machine number if it isn't already.
5357 That will force the base to 2 for non-zero values and simplify
5358 the rest of the logic. */
5359 if (!Is_Machine_Number (gnat_node))
5360 ur_realval
5361 = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
5362 ur_realval, Round_Even, gnat_node);
5364 if (UR_Is_Zero (ur_realval))
5365 gnu_result = convert (gnu_result_type, integer_zero_node);
5366 else
5368 REAL_VALUE_TYPE tmp;
5370 gnu_result = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
5372 /* The base must be 2 as Machine guarantees this, so we scale
5373 the value, which we know can fit in the mantissa of the type
5374 (hence the use of that type above). */
5375 gcc_assert (Rbase (ur_realval) == 2);
5376 real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
5377 - UI_To_Int (Denominator (ur_realval)));
5378 gnu_result = build_real (gnu_result_type, tmp);
5381 /* Now see if we need to negate the result. Do it this way to
5382 properly handle -0. */
5383 if (UR_Is_Negative (Realval (gnat_node)))
5384 gnu_result
5385 = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
5386 gnu_result);
5389 break;
5391 case N_String_Literal:
5392 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5393 if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
5395 String_Id gnat_string = Strval (gnat_node);
5396 int length = String_Length (gnat_string);
5397 int i;
5398 char *string;
5399 if (length >= ALLOCA_THRESHOLD)
5400 string = XNEWVEC (char, length + 1);
5401 else
5402 string = (char *) alloca (length + 1);
5404 /* Build the string with the characters in the literal. Note
5405 that Ada strings are 1-origin. */
5406 for (i = 0; i < length; i++)
5407 string[i] = Get_String_Char (gnat_string, i + 1);
5409 /* Put a null at the end of the string in case it's in a context
5410 where GCC will want to treat it as a C string. */
5411 string[i] = 0;
5413 gnu_result = build_string (length, string);
5415 /* Strings in GCC don't normally have types, but we want
5416 this to not be converted to the array type. */
5417 TREE_TYPE (gnu_result) = gnu_result_type;
5419 if (length >= ALLOCA_THRESHOLD)
5420 free (string);
5422 else
5424 /* Build a list consisting of each character, then make
5425 the aggregate. */
5426 String_Id gnat_string = Strval (gnat_node);
5427 int length = String_Length (gnat_string);
5428 int i;
5429 tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5430 tree gnu_one_node = convert (TREE_TYPE (gnu_idx), integer_one_node);
5431 vec<constructor_elt, va_gc> *gnu_vec;
5432 vec_alloc (gnu_vec, length);
5434 for (i = 0; i < length; i++)
5436 tree t = build_int_cst (TREE_TYPE (gnu_result_type),
5437 Get_String_Char (gnat_string, i + 1));
5439 CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
5440 gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, gnu_one_node);
5443 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
5445 break;
5447 case N_Pragma:
5448 gnu_result = Pragma_to_gnu (gnat_node);
5449 break;
5451 /**************************************/
5452 /* Chapter 3: Declarations and Types */
5453 /**************************************/
5455 case N_Subtype_Declaration:
5456 case N_Full_Type_Declaration:
5457 case N_Incomplete_Type_Declaration:
5458 case N_Private_Type_Declaration:
5459 case N_Private_Extension_Declaration:
5460 case N_Task_Type_Declaration:
5461 process_type (Defining_Entity (gnat_node));
5462 gnu_result = alloc_stmt_list ();
5463 break;
5465 case N_Object_Declaration:
5466 case N_Exception_Declaration:
5467 gnat_temp = Defining_Entity (gnat_node);
5468 gnu_result = alloc_stmt_list ();
5470 /* If we are just annotating types and this object has an unconstrained
5471 or task type, don't elaborate it. */
5472 if (type_annotate_only
5473 && (((Is_Array_Type (Etype (gnat_temp))
5474 || Is_Record_Type (Etype (gnat_temp)))
5475 && !Is_Constrained (Etype (gnat_temp)))
5476 || Is_Concurrent_Type (Etype (gnat_temp))))
5477 break;
5479 if (Present (Expression (gnat_node))
5480 && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
5481 && (!type_annotate_only
5482 || Compile_Time_Known_Value (Expression (gnat_node))))
5484 gnu_expr = gnat_to_gnu (Expression (gnat_node));
5485 if (Do_Range_Check (Expression (gnat_node)))
5486 gnu_expr
5487 = emit_range_check (gnu_expr, Etype (gnat_temp), gnat_node);
5489 /* If this object has its elaboration delayed, we must force
5490 evaluation of GNU_EXPR right now and save it for when the object
5491 is frozen. */
5492 if (Present (Freeze_Node (gnat_temp)))
5494 if (TREE_CONSTANT (gnu_expr))
5496 else if (global_bindings_p ())
5497 gnu_expr
5498 = create_var_decl (create_concat_name (gnat_temp, "init"),
5499 NULL_TREE, TREE_TYPE (gnu_expr), gnu_expr,
5500 false, false, false, false,
5501 NULL, gnat_temp);
5502 else
5503 gnu_expr = gnat_save_expr (gnu_expr);
5505 save_gnu_tree (gnat_node, gnu_expr, true);
5508 else
5509 gnu_expr = NULL_TREE;
5511 if (type_annotate_only && gnu_expr && TREE_CODE (gnu_expr) == ERROR_MARK)
5512 gnu_expr = NULL_TREE;
5514 /* If this is a deferred constant with an address clause, we ignore the
5515 full view since the clause is on the partial view and we cannot have
5516 2 different GCC trees for the object. The only bits of the full view
5517 we will use is the initializer, but it will be directly fetched. */
5518 if (Ekind(gnat_temp) == E_Constant
5519 && Present (Address_Clause (gnat_temp))
5520 && Present (Full_View (gnat_temp)))
5521 save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
5523 if (No (Freeze_Node (gnat_temp)))
5524 gnat_to_gnu_entity (gnat_temp, gnu_expr, 1);
5525 break;
5527 case N_Object_Renaming_Declaration:
5528 gnat_temp = Defining_Entity (gnat_node);
5530 /* Don't do anything if this renaming is handled by the front end or if
5531 we are just annotating types and this object has a composite or task
5532 type, don't elaborate it. We return the result in case it has any
5533 SAVE_EXPRs in it that need to be evaluated here. */
5534 if (!Is_Renaming_Of_Object (gnat_temp)
5535 && ! (type_annotate_only
5536 && (Is_Array_Type (Etype (gnat_temp))
5537 || Is_Record_Type (Etype (gnat_temp))
5538 || Is_Concurrent_Type (Etype (gnat_temp)))))
5539 gnu_result
5540 = gnat_to_gnu_entity (gnat_temp,
5541 gnat_to_gnu (Renamed_Object (gnat_temp)), 1);
5542 else
5543 gnu_result = alloc_stmt_list ();
5544 break;
5546 case N_Exception_Renaming_Declaration:
5547 gnat_temp = Defining_Entity (gnat_node);
5548 if (Renamed_Entity (gnat_temp) != Empty)
5549 gnu_result
5550 = gnat_to_gnu_entity (gnat_temp,
5551 gnat_to_gnu (Renamed_Entity (gnat_temp)), 1);
5552 else
5553 gnu_result = alloc_stmt_list ();
5554 break;
5556 case N_Implicit_Label_Declaration:
5557 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
5558 gnu_result = alloc_stmt_list ();
5559 break;
5561 case N_Number_Declaration:
5562 case N_Subprogram_Renaming_Declaration:
5563 case N_Package_Renaming_Declaration:
5564 /* These are fully handled in the front end. */
5565 /* ??? For package renamings, find a way to use GENERIC namespaces so
5566 that we get proper debug information for them. */
5567 gnu_result = alloc_stmt_list ();
5568 break;
5570 /*************************************/
5571 /* Chapter 4: Names and Expressions */
5572 /*************************************/
5574 case N_Explicit_Dereference:
5575 gnu_result = gnat_to_gnu (Prefix (gnat_node));
5576 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5577 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
5579 /* If this is an atomic access on the RHS for which synchronization is
5580 required, build the atomic load. */
5581 if (atomic_sync_required_p (gnat_node)
5582 && !present_in_lhs_or_actual_p (gnat_node))
5583 gnu_result = build_atomic_load (gnu_result);
5584 break;
5586 case N_Indexed_Component:
5588 tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
5589 tree gnu_type;
5590 int ndim;
5591 int i;
5592 Node_Id *gnat_expr_array;
5594 gnu_array_object = maybe_implicit_deref (gnu_array_object);
5596 /* Convert vector inputs to their representative array type, to fit
5597 what the code below expects. */
5598 if (VECTOR_TYPE_P (TREE_TYPE (gnu_array_object)))
5600 if (present_in_lhs_or_actual_p (gnat_node))
5601 gnat_mark_addressable (gnu_array_object);
5602 gnu_array_object = maybe_vector_array (gnu_array_object);
5605 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
5607 /* If we got a padded type, remove it too. */
5608 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
5609 gnu_array_object
5610 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
5611 gnu_array_object);
5613 gnu_result = gnu_array_object;
5615 /* The failure of this assertion will very likely come from a missing
5616 expansion for a packed array access. */
5617 gcc_assert (TREE_CODE (TREE_TYPE (gnu_array_object)) == ARRAY_TYPE);
5619 /* First compute the number of dimensions of the array, then
5620 fill the expression array, the order depending on whether
5621 this is a Convention_Fortran array or not. */
5622 for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
5623 TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
5624 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
5625 ndim++, gnu_type = TREE_TYPE (gnu_type))
5628 gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
5630 if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
5631 for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
5632 i >= 0;
5633 i--, gnat_temp = Next (gnat_temp))
5634 gnat_expr_array[i] = gnat_temp;
5635 else
5636 for (i = 0, gnat_temp = First (Expressions (gnat_node));
5637 i < ndim;
5638 i++, gnat_temp = Next (gnat_temp))
5639 gnat_expr_array[i] = gnat_temp;
5641 for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
5642 i < ndim; i++, gnu_type = TREE_TYPE (gnu_type))
5644 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
5645 gnat_temp = gnat_expr_array[i];
5646 gnu_expr = gnat_to_gnu (gnat_temp);
5648 if (Do_Range_Check (gnat_temp))
5649 gnu_expr
5650 = emit_index_check
5651 (gnu_array_object, gnu_expr,
5652 TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5653 TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5654 gnat_temp);
5656 gnu_result
5657 = build_binary_op (ARRAY_REF, NULL_TREE, gnu_result, gnu_expr);
5659 /* Array accesses are bound-checked so they cannot trap, but this
5660 is valid only if they are not hoisted ahead of the check. We
5661 need to mark them as no-trap to get decent loop optimizations
5662 in the presence of -fnon-call-exceptions, so we do it when we
5663 know that the original expression had no side-effects. */
5664 if (TREE_CODE (gnu_result) == ARRAY_REF
5665 && !(Nkind (gnat_temp) == N_Identifier
5666 && Ekind (Entity (gnat_temp)) == E_Constant))
5667 TREE_THIS_NOTRAP (gnu_result) = 1;
5670 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5672 /* If this is an atomic access on the RHS for which synchronization is
5673 required, build the atomic load. */
5674 if (atomic_sync_required_p (gnat_node)
5675 && !present_in_lhs_or_actual_p (gnat_node))
5676 gnu_result = build_atomic_load (gnu_result);
5678 break;
5680 case N_Slice:
5682 Node_Id gnat_range_node = Discrete_Range (gnat_node);
5683 tree gnu_type;
5685 gnu_result = gnat_to_gnu (Prefix (gnat_node));
5686 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5688 /* Do any implicit dereferences of the prefix and do any needed
5689 range check. */
5690 gnu_result = maybe_implicit_deref (gnu_result);
5691 gnu_result = maybe_unconstrained_array (gnu_result);
5692 gnu_type = TREE_TYPE (gnu_result);
5693 if (Do_Range_Check (gnat_range_node))
5695 /* Get the bounds of the slice. */
5696 tree gnu_index_type
5697 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_result_type));
5698 tree gnu_min_expr = TYPE_MIN_VALUE (gnu_index_type);
5699 tree gnu_max_expr = TYPE_MAX_VALUE (gnu_index_type);
5700 /* Get the permitted bounds. */
5701 tree gnu_base_index_type
5702 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
5703 tree gnu_base_min_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5704 (TYPE_MIN_VALUE (gnu_base_index_type), gnu_result);
5705 tree gnu_base_max_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5706 (TYPE_MAX_VALUE (gnu_base_index_type), gnu_result);
5707 tree gnu_expr_l, gnu_expr_h, gnu_expr_type;
5709 gnu_min_expr = gnat_protect_expr (gnu_min_expr);
5710 gnu_max_expr = gnat_protect_expr (gnu_max_expr);
5712 /* Derive a good type to convert everything to. */
5713 gnu_expr_type = get_base_type (gnu_index_type);
5715 /* Test whether the minimum slice value is too small. */
5716 gnu_expr_l = build_binary_op (LT_EXPR, boolean_type_node,
5717 convert (gnu_expr_type,
5718 gnu_min_expr),
5719 convert (gnu_expr_type,
5720 gnu_base_min_expr));
5722 /* Test whether the maximum slice value is too large. */
5723 gnu_expr_h = build_binary_op (GT_EXPR, boolean_type_node,
5724 convert (gnu_expr_type,
5725 gnu_max_expr),
5726 convert (gnu_expr_type,
5727 gnu_base_max_expr));
5729 /* Build a slice index check that returns the low bound,
5730 assuming the slice is not empty. */
5731 gnu_expr = emit_check
5732 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
5733 gnu_expr_l, gnu_expr_h),
5734 gnu_min_expr, CE_Index_Check_Failed, gnat_node);
5736 /* Build a conditional expression that does the index checks and
5737 returns the low bound if the slice is not empty (max >= min),
5738 and returns the naked low bound otherwise (max < min), unless
5739 it is non-constant and the high bound is; this prevents VRP
5740 from inferring bogus ranges on the unlikely path. */
5741 gnu_expr = fold_build3 (COND_EXPR, gnu_expr_type,
5742 build_binary_op (GE_EXPR, gnu_expr_type,
5743 convert (gnu_expr_type,
5744 gnu_max_expr),
5745 convert (gnu_expr_type,
5746 gnu_min_expr)),
5747 gnu_expr,
5748 TREE_CODE (gnu_min_expr) != INTEGER_CST
5749 && TREE_CODE (gnu_max_expr) == INTEGER_CST
5750 ? gnu_max_expr : gnu_min_expr);
5752 else
5753 /* Simply return the naked low bound. */
5754 gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5756 /* If this is a slice with non-constant size of an array with constant
5757 size, set the maximum size for the allocation of temporaries. */
5758 if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
5759 && TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_type)))
5760 TYPE_ARRAY_MAX_SIZE (gnu_result_type) = TYPE_SIZE_UNIT (gnu_type);
5762 gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
5763 gnu_result, gnu_expr);
5765 break;
5767 case N_Selected_Component:
5769 Entity_Id gnat_prefix = Prefix (gnat_node);
5770 Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
5771 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
5772 tree gnu_field;
5774 gnu_prefix = maybe_implicit_deref (gnu_prefix);
5776 /* For discriminant references in tagged types always substitute the
5777 corresponding discriminant as the actual selected component. */
5778 if (Is_Tagged_Type (Underlying_Type (Etype (gnat_prefix))))
5779 while (Present (Corresponding_Discriminant (gnat_field)))
5780 gnat_field = Corresponding_Discriminant (gnat_field);
5782 /* For discriminant references of untagged types always substitute the
5783 corresponding stored discriminant. */
5784 else if (Present (Corresponding_Discriminant (gnat_field)))
5785 gnat_field = Original_Record_Component (gnat_field);
5787 /* Handle extracting the real or imaginary part of a complex.
5788 The real part is the first field and the imaginary the last. */
5789 if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
5790 gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
5791 ? REALPART_EXPR : IMAGPART_EXPR,
5792 NULL_TREE, gnu_prefix);
5793 else
5795 gnu_field = gnat_to_gnu_field_decl (gnat_field);
5797 /* If there are discriminants, the prefix might be evaluated more
5798 than once, which is a problem if it has side-effects. */
5799 if (Has_Discriminants (Is_Access_Type (Etype (Prefix (gnat_node)))
5800 ? Designated_Type (Etype
5801 (Prefix (gnat_node)))
5802 : Etype (Prefix (gnat_node))))
5803 gnu_prefix = gnat_stabilize_reference (gnu_prefix, false, NULL);
5805 gnu_result
5806 = build_component_ref (gnu_prefix, NULL_TREE, gnu_field,
5807 (Nkind (Parent (gnat_node))
5808 == N_Attribute_Reference)
5809 && lvalue_required_for_attribute_p
5810 (Parent (gnat_node)));
5813 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5815 /* If this is an atomic access on the RHS for which synchronization is
5816 required, build the atomic load. */
5817 if (atomic_sync_required_p (gnat_node)
5818 && !present_in_lhs_or_actual_p (gnat_node))
5819 gnu_result = build_atomic_load (gnu_result);
5821 break;
5823 case N_Attribute_Reference:
5825 /* The attribute designator. */
5826 const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
5828 /* The Elab_Spec and Elab_Body attributes are special in that Prefix
5829 is a unit, not an object with a GCC equivalent. */
5830 if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
5831 return
5832 create_subprog_decl (create_concat_name
5833 (Entity (Prefix (gnat_node)),
5834 attr == Attr_Elab_Body ? "elabb" : "elabs"),
5835 NULL_TREE, void_ftype, NULL_TREE, is_disabled,
5836 true, true, true, NULL, gnat_node);
5838 gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
5840 break;
5842 case N_Reference:
5843 /* Like 'Access as far as we are concerned. */
5844 gnu_result = gnat_to_gnu (Prefix (gnat_node));
5845 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
5846 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5847 break;
5849 case N_Aggregate:
5850 case N_Extension_Aggregate:
5852 tree gnu_aggr_type;
5854 /* ??? It is wrong to evaluate the type now, but there doesn't
5855 seem to be any other practical way of doing it. */
5857 gcc_assert (!Expansion_Delayed (gnat_node));
5859 gnu_aggr_type = gnu_result_type
5860 = get_unpadded_type (Etype (gnat_node));
5862 if (TREE_CODE (gnu_result_type) == RECORD_TYPE
5863 && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
5864 gnu_aggr_type
5865 = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
5866 else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
5867 gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
5869 if (Null_Record_Present (gnat_node))
5870 gnu_result = gnat_build_constructor (gnu_aggr_type,
5871 NULL);
5873 else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
5874 || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
5875 gnu_result
5876 = assoc_to_constructor (Etype (gnat_node),
5877 First (Component_Associations (gnat_node)),
5878 gnu_aggr_type);
5879 else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
5880 gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
5881 gnu_aggr_type,
5882 Component_Type (Etype (gnat_node)));
5883 else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
5884 gnu_result
5885 = build_binary_op
5886 (COMPLEX_EXPR, gnu_aggr_type,
5887 gnat_to_gnu (Expression (First
5888 (Component_Associations (gnat_node)))),
5889 gnat_to_gnu (Expression
5890 (Next
5891 (First (Component_Associations (gnat_node))))));
5892 else
5893 gcc_unreachable ();
5895 gnu_result = convert (gnu_result_type, gnu_result);
5897 break;
5899 case N_Null:
5900 if (TARGET_VTABLE_USES_DESCRIPTORS
5901 && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
5902 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
5903 gnu_result = null_fdesc_node;
5904 else
5905 gnu_result = null_pointer_node;
5906 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5907 break;
5909 case N_Type_Conversion:
5910 case N_Qualified_Expression:
5911 /* Get the operand expression. */
5912 gnu_result = gnat_to_gnu (Expression (gnat_node));
5913 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5915 /* If this is a qualified expression for a tagged type, we mark the type
5916 as used. Because of polymorphism, this might be the only reference to
5917 the tagged type in the program while objects have it as dynamic type.
5918 The debugger needs to see it to display these objects properly. */
5919 if (kind == N_Qualified_Expression && Is_Tagged_Type (Etype (gnat_node)))
5920 used_types_insert (gnu_result_type);
5922 gnu_result
5923 = convert_with_check (Etype (gnat_node), gnu_result,
5924 Do_Overflow_Check (gnat_node),
5925 Do_Range_Check (Expression (gnat_node)),
5926 kind == N_Type_Conversion
5927 && Float_Truncate (gnat_node), gnat_node);
5928 break;
5930 case N_Unchecked_Type_Conversion:
5931 gnu_result = gnat_to_gnu (Expression (gnat_node));
5933 /* Skip further processing if the conversion is deemed a no-op. */
5934 if (unchecked_conversion_nop (gnat_node))
5936 gnu_result_type = TREE_TYPE (gnu_result);
5937 break;
5940 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5942 /* If the result is a pointer type, see if we are improperly
5943 converting to a stricter alignment. */
5944 if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
5945 && IN (Ekind (Etype (gnat_node)), Access_Kind))
5947 unsigned int align = known_alignment (gnu_result);
5948 tree gnu_obj_type = TREE_TYPE (gnu_result_type);
5949 unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
5951 if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
5952 post_error_ne_tree_2
5953 ("?source alignment (^) '< alignment of & (^)",
5954 gnat_node, Designated_Type (Etype (gnat_node)),
5955 size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
5958 /* If we are converting a descriptor to a function pointer, first
5959 build the pointer. */
5960 if (TARGET_VTABLE_USES_DESCRIPTORS
5961 && TREE_TYPE (gnu_result) == fdesc_type_node
5962 && POINTER_TYPE_P (gnu_result_type))
5963 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
5965 gnu_result = unchecked_convert (gnu_result_type, gnu_result,
5966 No_Truncation (gnat_node));
5967 break;
5969 case N_In:
5970 case N_Not_In:
5972 tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
5973 Node_Id gnat_range = Right_Opnd (gnat_node);
5974 tree gnu_low, gnu_high;
5976 /* GNAT_RANGE is either an N_Range node or an identifier denoting a
5977 subtype. */
5978 if (Nkind (gnat_range) == N_Range)
5980 gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
5981 gnu_high = gnat_to_gnu (High_Bound (gnat_range));
5983 else if (Nkind (gnat_range) == N_Identifier
5984 || Nkind (gnat_range) == N_Expanded_Name)
5986 tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
5987 tree gnu_range_base_type = get_base_type (gnu_range_type);
5989 gnu_low
5990 = convert (gnu_range_base_type, TYPE_MIN_VALUE (gnu_range_type));
5991 gnu_high
5992 = convert (gnu_range_base_type, TYPE_MAX_VALUE (gnu_range_type));
5994 else
5995 gcc_unreachable ();
5997 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5999 /* If LOW and HIGH are identical, perform an equality test. Otherwise,
6000 ensure that GNU_OBJ is evaluated only once and perform a full range
6001 test. */
6002 if (operand_equal_p (gnu_low, gnu_high, 0))
6003 gnu_result
6004 = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
6005 else
6007 tree t1, t2;
6008 gnu_obj = gnat_protect_expr (gnu_obj);
6009 t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
6010 if (EXPR_P (t1))
6011 set_expr_location_from_node (t1, gnat_node);
6012 t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
6013 if (EXPR_P (t2))
6014 set_expr_location_from_node (t2, gnat_node);
6015 gnu_result
6016 = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
6019 if (kind == N_Not_In)
6020 gnu_result
6021 = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
6023 break;
6025 case N_Op_Divide:
6026 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6027 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6028 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6029 gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
6030 ? RDIV_EXPR
6031 : (Rounded_Result (gnat_node)
6032 ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
6033 gnu_result_type, gnu_lhs, gnu_rhs);
6034 break;
6036 case N_Op_Or: case N_Op_And: case N_Op_Xor:
6037 /* These can either be operations on booleans or on modular types.
6038 Fall through for boolean types since that's the way GNU_CODES is
6039 set up. */
6040 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6042 enum tree_code code
6043 = (kind == N_Op_Or ? BIT_IOR_EXPR
6044 : kind == N_Op_And ? BIT_AND_EXPR
6045 : BIT_XOR_EXPR);
6047 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6048 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6049 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6050 gnu_result = build_binary_op (code, gnu_result_type,
6051 gnu_lhs, gnu_rhs);
6052 break;
6055 /* ... fall through ... */
6057 case N_Op_Eq: case N_Op_Ne: case N_Op_Lt:
6058 case N_Op_Le: case N_Op_Gt: case N_Op_Ge:
6059 case N_Op_Add: case N_Op_Subtract: case N_Op_Multiply:
6060 case N_Op_Mod: case N_Op_Rem:
6061 case N_Op_Rotate_Left:
6062 case N_Op_Rotate_Right:
6063 case N_Op_Shift_Left:
6064 case N_Op_Shift_Right:
6065 case N_Op_Shift_Right_Arithmetic:
6066 case N_And_Then: case N_Or_Else:
6068 enum tree_code code = gnu_codes[kind];
6069 bool ignore_lhs_overflow = false;
6070 location_t saved_location = input_location;
6071 tree gnu_type;
6073 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6074 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6075 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6077 /* Pending generic support for efficient vector logical operations in
6078 GCC, convert vectors to their representative array type view and
6079 fallthrough. */
6080 gnu_lhs = maybe_vector_array (gnu_lhs);
6081 gnu_rhs = maybe_vector_array (gnu_rhs);
6083 /* If this is a comparison operator, convert any references to an
6084 unconstrained array value into a reference to the actual array. */
6085 if (TREE_CODE_CLASS (code) == tcc_comparison)
6087 gnu_lhs = maybe_unconstrained_array (gnu_lhs);
6088 gnu_rhs = maybe_unconstrained_array (gnu_rhs);
6091 /* If this is a shift whose count is not guaranteed to be correct,
6092 we need to adjust the shift count. */
6093 if (IN (kind, N_Op_Shift) && !Shift_Count_OK (gnat_node))
6095 tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
6096 tree gnu_max_shift
6097 = convert (gnu_count_type, TYPE_SIZE (gnu_type));
6099 if (kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
6100 gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
6101 gnu_rhs, gnu_max_shift);
6102 else if (kind == N_Op_Shift_Right_Arithmetic)
6103 gnu_rhs
6104 = build_binary_op
6105 (MIN_EXPR, gnu_count_type,
6106 build_binary_op (MINUS_EXPR,
6107 gnu_count_type,
6108 gnu_max_shift,
6109 convert (gnu_count_type,
6110 integer_one_node)),
6111 gnu_rhs);
6114 /* For right shifts, the type says what kind of shift to do,
6115 so we may need to choose a different type. In this case,
6116 we have to ignore integer overflow lest it propagates all
6117 the way down and causes a CE to be explicitly raised. */
6118 if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
6120 gnu_type = gnat_unsigned_type (gnu_type);
6121 ignore_lhs_overflow = true;
6123 else if (kind == N_Op_Shift_Right_Arithmetic
6124 && TYPE_UNSIGNED (gnu_type))
6126 gnu_type = gnat_signed_type (gnu_type);
6127 ignore_lhs_overflow = true;
6130 if (gnu_type != gnu_result_type)
6132 tree gnu_old_lhs = gnu_lhs;
6133 gnu_lhs = convert (gnu_type, gnu_lhs);
6134 if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
6135 TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
6136 gnu_rhs = convert (gnu_type, gnu_rhs);
6139 /* Instead of expanding overflow checks for addition, subtraction
6140 and multiplication itself, the front end will leave this to
6141 the back end when Backend_Overflow_Checks_On_Target is set.
6142 As the GCC back end itself does not know yet how to properly
6143 do overflow checking, do it here. The goal is to push
6144 the expansions further into the back end over time. */
6145 if (Do_Overflow_Check (gnat_node) && Backend_Overflow_Checks_On_Target
6146 && (kind == N_Op_Add
6147 || kind == N_Op_Subtract
6148 || kind == N_Op_Multiply)
6149 && !TYPE_UNSIGNED (gnu_type)
6150 && !FLOAT_TYPE_P (gnu_type))
6151 gnu_result = build_binary_op_trapv (code, gnu_type,
6152 gnu_lhs, gnu_rhs, gnat_node);
6153 else
6155 /* Some operations, e.g. comparisons of arrays, generate complex
6156 trees that need to be annotated while they are being built. */
6157 input_location = saved_location;
6158 gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
6161 /* If this is a logical shift with the shift count not verified,
6162 we must return zero if it is too large. We cannot compensate
6163 above in this case. */
6164 if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
6165 && !Shift_Count_OK (gnat_node))
6166 gnu_result
6167 = build_cond_expr
6168 (gnu_type,
6169 build_binary_op (GE_EXPR, boolean_type_node,
6170 gnu_rhs,
6171 convert (TREE_TYPE (gnu_rhs),
6172 TYPE_SIZE (gnu_type))),
6173 convert (gnu_type, integer_zero_node),
6174 gnu_result);
6176 break;
6178 case N_If_Expression:
6180 tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
6181 tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
6182 tree gnu_false
6183 = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
6185 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6186 gnu_result
6187 = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
6189 break;
6191 case N_Op_Plus:
6192 gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
6193 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6194 break;
6196 case N_Op_Not:
6197 /* This case can apply to a boolean or a modular type.
6198 Fall through for a boolean operand since GNU_CODES is set
6199 up to handle this. */
6200 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6202 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6203 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6204 gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
6205 gnu_expr);
6206 break;
6209 /* ... fall through ... */
6211 case N_Op_Minus: case N_Op_Abs:
6212 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6213 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6215 if (Do_Overflow_Check (gnat_node)
6216 && !TYPE_UNSIGNED (gnu_result_type)
6217 && !FLOAT_TYPE_P (gnu_result_type))
6218 gnu_result
6219 = build_unary_op_trapv (gnu_codes[kind],
6220 gnu_result_type, gnu_expr, gnat_node);
6221 else
6222 gnu_result = build_unary_op (gnu_codes[kind],
6223 gnu_result_type, gnu_expr);
6224 break;
6226 case N_Allocator:
6228 tree gnu_init = 0;
6229 tree gnu_type;
6230 bool ignore_init_type = false;
6232 gnat_temp = Expression (gnat_node);
6234 /* The Expression operand can either be an N_Identifier or
6235 Expanded_Name, which must represent a type, or a
6236 N_Qualified_Expression, which contains both the object type and an
6237 initial value for the object. */
6238 if (Nkind (gnat_temp) == N_Identifier
6239 || Nkind (gnat_temp) == N_Expanded_Name)
6240 gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
6241 else if (Nkind (gnat_temp) == N_Qualified_Expression)
6243 Entity_Id gnat_desig_type
6244 = Designated_Type (Underlying_Type (Etype (gnat_node)));
6246 ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
6247 gnu_init = gnat_to_gnu (Expression (gnat_temp));
6249 gnu_init = maybe_unconstrained_array (gnu_init);
6250 if (Do_Range_Check (Expression (gnat_temp)))
6251 gnu_init
6252 = emit_range_check (gnu_init, gnat_desig_type, gnat_temp);
6254 if (Is_Elementary_Type (gnat_desig_type)
6255 || Is_Constrained (gnat_desig_type))
6256 gnu_type = gnat_to_gnu_type (gnat_desig_type);
6257 else
6259 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
6260 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
6261 gnu_type = TREE_TYPE (gnu_init);
6264 /* See the N_Qualified_Expression case for the rationale. */
6265 if (Is_Tagged_Type (gnat_desig_type))
6266 used_types_insert (gnu_type);
6268 gnu_init = convert (gnu_type, gnu_init);
6270 else
6271 gcc_unreachable ();
6273 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6274 return build_allocator (gnu_type, gnu_init, gnu_result_type,
6275 Procedure_To_Call (gnat_node),
6276 Storage_Pool (gnat_node), gnat_node,
6277 ignore_init_type);
6279 break;
6281 /**************************/
6282 /* Chapter 5: Statements */
6283 /**************************/
6285 case N_Label:
6286 gnu_result = build1 (LABEL_EXPR, void_type_node,
6287 gnat_to_gnu (Identifier (gnat_node)));
6288 break;
6290 case N_Null_Statement:
6291 /* When not optimizing, turn null statements from source into gotos to
6292 the next statement that the middle-end knows how to preserve. */
6293 if (!optimize && Comes_From_Source (gnat_node))
6295 tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
6296 DECL_IGNORED_P (label) = 1;
6297 start_stmt_group ();
6298 stmt = build1 (GOTO_EXPR, void_type_node, label);
6299 set_expr_location_from_node (stmt, gnat_node);
6300 add_stmt (stmt);
6301 stmt = build1 (LABEL_EXPR, void_type_node, label);
6302 set_expr_location_from_node (stmt, gnat_node);
6303 add_stmt (stmt);
6304 gnu_result = end_stmt_group ();
6306 else
6307 gnu_result = alloc_stmt_list ();
6308 break;
6310 case N_Assignment_Statement:
6311 /* Get the LHS and RHS of the statement and convert any reference to an
6312 unconstrained array into a reference to the underlying array. */
6313 gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
6315 /* If the type has a size that overflows, convert this into raise of
6316 Storage_Error: execution shouldn't have gotten here anyway. */
6317 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
6318 && !valid_constant_size_p (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
6319 gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
6320 N_Raise_Storage_Error);
6321 else if (Nkind (Expression (gnat_node)) == N_Function_Call)
6322 gnu_result
6323 = Call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
6324 atomic_sync_required_p (Name (gnat_node)));
6325 else
6327 const Node_Id gnat_expr = Expression (gnat_node);
6328 const Entity_Id gnat_type
6329 = Underlying_Type (Etype (Name (gnat_node)));
6330 const bool regular_array_type_p
6331 = (Is_Array_Type (gnat_type) && !Is_Bit_Packed_Array (gnat_type));
6332 const bool use_memset_p
6333 = (regular_array_type_p
6334 && Nkind (gnat_expr) == N_Aggregate
6335 && Is_Others_Aggregate (gnat_expr));
6337 /* If we'll use memset, we need to find the inner expression. */
6338 if (use_memset_p)
6340 Node_Id gnat_inner
6341 = Expression (First (Component_Associations (gnat_expr)));
6342 while (Nkind (gnat_inner) == N_Aggregate
6343 && Is_Others_Aggregate (gnat_inner))
6344 gnat_inner
6345 = Expression (First (Component_Associations (gnat_inner)));
6346 gnu_rhs = gnat_to_gnu (gnat_inner);
6348 else
6349 gnu_rhs = maybe_unconstrained_array (gnat_to_gnu (gnat_expr));
6351 /* If range check is needed, emit code to generate it. */
6352 if (Do_Range_Check (gnat_expr))
6353 gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)),
6354 gnat_node);
6356 /* If atomic synchronization is required, build an atomic store. */
6357 if (atomic_sync_required_p (Name (gnat_node)))
6358 gnu_result = build_atomic_store (gnu_lhs, gnu_rhs);
6360 /* Or else, use memset when the conditions are met. */
6361 else if (use_memset_p)
6363 tree value = fold_convert (integer_type_node, gnu_rhs);
6364 tree to = gnu_lhs;
6365 tree type = TREE_TYPE (to);
6366 tree size
6367 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), to);
6368 tree to_ptr = build_fold_addr_expr (to);
6369 tree t = builtin_decl_implicit (BUILT_IN_MEMSET);
6370 if (TREE_CODE (value) == INTEGER_CST)
6372 tree mask
6373 = build_int_cst (integer_type_node,
6374 ((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
6375 value = int_const_binop (BIT_AND_EXPR, value, mask);
6377 gnu_result = build_call_expr (t, 3, to_ptr, value, size);
6380 /* Otherwise build a regular assignment. */
6381 else
6382 gnu_result
6383 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
6385 /* If the assignment type is a regular array and the two sides are
6386 not completely disjoint, play safe and use memmove. But don't do
6387 it for a bit-packed array as it might not be byte-aligned. */
6388 if (TREE_CODE (gnu_result) == MODIFY_EXPR
6389 && regular_array_type_p
6390 && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
6392 tree to = TREE_OPERAND (gnu_result, 0);
6393 tree from = TREE_OPERAND (gnu_result, 1);
6394 tree type = TREE_TYPE (from);
6395 tree size
6396 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), from);
6397 tree to_ptr = build_fold_addr_expr (to);
6398 tree from_ptr = build_fold_addr_expr (from);
6399 tree t = builtin_decl_implicit (BUILT_IN_MEMMOVE);
6400 gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
6403 break;
6405 case N_If_Statement:
6407 tree *gnu_else_ptr; /* Point to put next "else if" or "else". */
6409 /* Make the outer COND_EXPR. Avoid non-determinism. */
6410 gnu_result = build3 (COND_EXPR, void_type_node,
6411 gnat_to_gnu (Condition (gnat_node)),
6412 NULL_TREE, NULL_TREE);
6413 COND_EXPR_THEN (gnu_result)
6414 = build_stmt_group (Then_Statements (gnat_node), false);
6415 TREE_SIDE_EFFECTS (gnu_result) = 1;
6416 gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
6418 /* Now make a COND_EXPR for each of the "else if" parts. Put each
6419 into the previous "else" part and point to where to put any
6420 outer "else". Also avoid non-determinism. */
6421 if (Present (Elsif_Parts (gnat_node)))
6422 for (gnat_temp = First (Elsif_Parts (gnat_node));
6423 Present (gnat_temp); gnat_temp = Next (gnat_temp))
6425 gnu_expr = build3 (COND_EXPR, void_type_node,
6426 gnat_to_gnu (Condition (gnat_temp)),
6427 NULL_TREE, NULL_TREE);
6428 COND_EXPR_THEN (gnu_expr)
6429 = build_stmt_group (Then_Statements (gnat_temp), false);
6430 TREE_SIDE_EFFECTS (gnu_expr) = 1;
6431 set_expr_location_from_node (gnu_expr, gnat_temp);
6432 *gnu_else_ptr = gnu_expr;
6433 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
6436 *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
6438 break;
6440 case N_Case_Statement:
6441 gnu_result = Case_Statement_to_gnu (gnat_node);
6442 break;
6444 case N_Loop_Statement:
6445 gnu_result = Loop_Statement_to_gnu (gnat_node);
6446 break;
6448 case N_Block_Statement:
6449 /* The only way to enter the block is to fall through to it. */
6450 if (stmt_group_may_fallthru ())
6452 start_stmt_group ();
6453 gnat_pushlevel ();
6454 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6455 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6456 gnat_poplevel ();
6457 gnu_result = end_stmt_group ();
6459 else
6460 gnu_result = alloc_stmt_list ();
6461 break;
6463 case N_Exit_Statement:
6464 gnu_result
6465 = build2 (EXIT_STMT, void_type_node,
6466 (Present (Condition (gnat_node))
6467 ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
6468 (Present (Name (gnat_node))
6469 ? get_gnu_tree (Entity (Name (gnat_node)))
6470 : LOOP_STMT_LABEL (gnu_loop_stack->last ()->stmt)));
6471 break;
6473 case N_Simple_Return_Statement:
6475 tree gnu_ret_obj, gnu_ret_val;
6477 /* If the subprogram is a function, we must return the expression. */
6478 if (Present (Expression (gnat_node)))
6480 tree gnu_subprog_type = TREE_TYPE (current_function_decl);
6482 /* If this function has copy-in/copy-out parameters, get the real
6483 object for the return. See Subprogram_to_gnu. */
6484 if (TYPE_CI_CO_LIST (gnu_subprog_type))
6485 gnu_ret_obj = gnu_return_var_stack->last ();
6486 else
6487 gnu_ret_obj = DECL_RESULT (current_function_decl);
6489 /* Get the GCC tree for the expression to be returned. */
6490 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
6492 /* Do not remove the padding from GNU_RET_VAL if the inner type is
6493 self-referential since we want to allocate the fixed size. */
6494 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
6495 && TYPE_IS_PADDING_P
6496 (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0)))
6497 && CONTAINS_PLACEHOLDER_P
6498 (TYPE_SIZE (TREE_TYPE (gnu_ret_val))))
6499 gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
6501 /* If the function returns by direct reference, return a pointer
6502 to the return value. */
6503 if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
6504 || By_Ref (gnat_node))
6505 gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
6507 /* Otherwise, if it returns an unconstrained array, we have to
6508 allocate a new version of the result and return it. */
6509 else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
6511 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
6513 /* And find out whether this is a candidate for Named Return
6514 Value. If so, record it. */
6515 if (!TYPE_CI_CO_LIST (gnu_subprog_type) && optimize)
6517 tree ret_val = gnu_ret_val;
6519 /* Strip useless conversions around the return value. */
6520 if (gnat_useless_type_conversion (ret_val))
6521 ret_val = TREE_OPERAND (ret_val, 0);
6523 /* Strip unpadding around the return value. */
6524 if (TREE_CODE (ret_val) == COMPONENT_REF
6525 && TYPE_IS_PADDING_P
6526 (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
6527 ret_val = TREE_OPERAND (ret_val, 0);
6529 /* Now apply the test to the return value. */
6530 if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
6532 if (!f_named_ret_val)
6533 f_named_ret_val = BITMAP_GGC_ALLOC ();
6534 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
6535 if (!f_gnat_ret)
6536 f_gnat_ret = gnat_node;
6540 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
6541 gnu_ret_val,
6542 TREE_TYPE (gnu_ret_obj),
6543 Procedure_To_Call (gnat_node),
6544 Storage_Pool (gnat_node),
6545 gnat_node, false);
6548 /* Otherwise, if it returns by invisible reference, dereference
6549 the pointer it is passed using the type of the return value
6550 and build the copy operation manually. This ensures that we
6551 don't copy too much data, for example if the return type is
6552 unconstrained with a maximum size. */
6553 else if (TREE_ADDRESSABLE (gnu_subprog_type))
6555 tree gnu_ret_deref
6556 = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
6557 gnu_ret_obj);
6558 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
6559 gnu_ret_deref, gnu_ret_val);
6560 add_stmt_with_node (gnu_result, gnat_node);
6561 gnu_ret_val = NULL_TREE;
6565 else
6566 gnu_ret_obj = gnu_ret_val = NULL_TREE;
6568 /* If we have a return label defined, convert this into a branch to
6569 that label. The return proper will be handled elsewhere. */
6570 if (gnu_return_label_stack->last ())
6572 if (gnu_ret_obj)
6573 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_ret_obj,
6574 gnu_ret_val));
6576 gnu_result = build1 (GOTO_EXPR, void_type_node,
6577 gnu_return_label_stack->last ());
6579 /* When not optimizing, make sure the return is preserved. */
6580 if (!optimize && Comes_From_Source (gnat_node))
6581 DECL_ARTIFICIAL (gnu_return_label_stack->last ()) = 0;
6584 /* Otherwise, build a regular return. */
6585 else
6586 gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
6588 break;
6590 case N_Goto_Statement:
6591 gnu_result
6592 = build1 (GOTO_EXPR, void_type_node, gnat_to_gnu (Name (gnat_node)));
6593 break;
6595 /***************************/
6596 /* Chapter 6: Subprograms */
6597 /***************************/
6599 case N_Subprogram_Declaration:
6600 /* Unless there is a freeze node, declare the subprogram. We consider
6601 this a "definition" even though we're not generating code for
6602 the subprogram because we will be making the corresponding GCC
6603 node here. */
6605 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6606 gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
6607 NULL_TREE, 1);
6608 gnu_result = alloc_stmt_list ();
6609 break;
6611 case N_Abstract_Subprogram_Declaration:
6612 /* This subprogram doesn't exist for code generation purposes, but we
6613 have to elaborate the types of any parameters and result, unless
6614 they are imported types (nothing to generate in this case).
6616 The parameter list may contain types with freeze nodes, e.g. not null
6617 subtypes, so the subprogram itself may carry a freeze node, in which
6618 case its elaboration must be deferred. */
6620 /* Process the parameter types first. */
6621 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6622 for (gnat_temp
6623 = First_Formal_With_Extras
6624 (Defining_Entity (Specification (gnat_node)));
6625 Present (gnat_temp);
6626 gnat_temp = Next_Formal_With_Extras (gnat_temp))
6627 if (Is_Itype (Etype (gnat_temp))
6628 && !From_Limited_With (Etype (gnat_temp)))
6629 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
6631 /* Then the result type, set to Standard_Void_Type for procedures. */
6633 Entity_Id gnat_temp_type
6634 = Etype (Defining_Entity (Specification (gnat_node)));
6636 if (Is_Itype (gnat_temp_type) && !From_Limited_With (gnat_temp_type))
6637 gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, 0);
6640 gnu_result = alloc_stmt_list ();
6641 break;
6643 case N_Defining_Program_Unit_Name:
6644 /* For a child unit identifier go up a level to get the specification.
6645 We get this when we try to find the spec of a child unit package
6646 that is the compilation unit being compiled. */
6647 gnu_result = gnat_to_gnu (Parent (gnat_node));
6648 break;
6650 case N_Subprogram_Body:
6651 Subprogram_Body_to_gnu (gnat_node);
6652 gnu_result = alloc_stmt_list ();
6653 break;
6655 case N_Function_Call:
6656 case N_Procedure_Call_Statement:
6657 gnu_result = Call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE, false);
6658 break;
6660 /************************/
6661 /* Chapter 7: Packages */
6662 /************************/
6664 case N_Package_Declaration:
6665 gnu_result = gnat_to_gnu (Specification (gnat_node));
6666 break;
6668 case N_Package_Specification:
6670 start_stmt_group ();
6671 process_decls (Visible_Declarations (gnat_node),
6672 Private_Declarations (gnat_node), Empty, true, true);
6673 gnu_result = end_stmt_group ();
6674 break;
6676 case N_Package_Body:
6678 /* If this is the body of a generic package - do nothing. */
6679 if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
6681 gnu_result = alloc_stmt_list ();
6682 break;
6685 start_stmt_group ();
6686 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6688 if (Present (Handled_Statement_Sequence (gnat_node)))
6689 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6691 gnu_result = end_stmt_group ();
6692 break;
6694 /********************************/
6695 /* Chapter 8: Visibility Rules */
6696 /********************************/
6698 case N_Use_Package_Clause:
6699 case N_Use_Type_Clause:
6700 /* Nothing to do here - but these may appear in list of declarations. */
6701 gnu_result = alloc_stmt_list ();
6702 break;
6704 /*********************/
6705 /* Chapter 9: Tasks */
6706 /*********************/
6708 case N_Protected_Type_Declaration:
6709 gnu_result = alloc_stmt_list ();
6710 break;
6712 case N_Single_Task_Declaration:
6713 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
6714 gnu_result = alloc_stmt_list ();
6715 break;
6717 /*********************************************************/
6718 /* Chapter 10: Program Structure and Compilation Issues */
6719 /*********************************************************/
6721 case N_Compilation_Unit:
6722 /* This is not called for the main unit on which gigi is invoked. */
6723 Compilation_Unit_to_gnu (gnat_node);
6724 gnu_result = alloc_stmt_list ();
6725 break;
6727 case N_Subprogram_Body_Stub:
6728 case N_Package_Body_Stub:
6729 case N_Protected_Body_Stub:
6730 case N_Task_Body_Stub:
6731 /* Simply process whatever unit is being inserted. */
6732 if (Present (Library_Unit (gnat_node)))
6733 gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
6734 else
6736 gcc_assert (type_annotate_only);
6737 gnu_result = alloc_stmt_list ();
6739 break;
6741 case N_Subunit:
6742 gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
6743 break;
6745 /***************************/
6746 /* Chapter 11: Exceptions */
6747 /***************************/
6749 case N_Handled_Sequence_Of_Statements:
6750 /* If there is an At_End procedure attached to this node, and the EH
6751 mechanism is SJLJ, we must have at least a corresponding At_End
6752 handler, unless the No_Exception_Handlers restriction is set. */
6753 gcc_assert (type_annotate_only
6754 || Exception_Mechanism != Setjmp_Longjmp
6755 || No (At_End_Proc (gnat_node))
6756 || Present (Exception_Handlers (gnat_node))
6757 || No_Exception_Handlers_Set ());
6759 gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
6760 break;
6762 case N_Exception_Handler:
6763 if (Exception_Mechanism == Setjmp_Longjmp)
6764 gnu_result = Exception_Handler_to_gnu_sjlj (gnat_node);
6765 else if (Exception_Mechanism == Back_End_Exceptions)
6766 gnu_result = Exception_Handler_to_gnu_zcx (gnat_node);
6767 else
6768 gcc_unreachable ();
6769 break;
6771 case N_Raise_Statement:
6772 /* Only for reraise in back-end exceptions mode. */
6773 gcc_assert (No (Name (gnat_node))
6774 && Exception_Mechanism == Back_End_Exceptions);
6776 start_stmt_group ();
6777 gnat_pushlevel ();
6779 /* Clear the current exception pointer so that the occurrence won't be
6780 deallocated. */
6781 gnu_expr = create_var_decl (get_identifier ("SAVED_EXPTR"), NULL_TREE,
6782 ptr_type_node, gnu_incoming_exc_ptr,
6783 false, false, false, false, NULL, gnat_node);
6785 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_incoming_exc_ptr,
6786 convert (ptr_type_node, integer_zero_node)));
6787 add_stmt (build_call_n_expr (reraise_zcx_decl, 1, gnu_expr));
6788 gnat_poplevel ();
6789 gnu_result = end_stmt_group ();
6790 break;
6792 case N_Push_Constraint_Error_Label:
6793 push_exception_label_stack (&gnu_constraint_error_label_stack,
6794 Exception_Label (gnat_node));
6795 break;
6797 case N_Push_Storage_Error_Label:
6798 push_exception_label_stack (&gnu_storage_error_label_stack,
6799 Exception_Label (gnat_node));
6800 break;
6802 case N_Push_Program_Error_Label:
6803 push_exception_label_stack (&gnu_program_error_label_stack,
6804 Exception_Label (gnat_node));
6805 break;
6807 case N_Pop_Constraint_Error_Label:
6808 gnu_constraint_error_label_stack->pop ();
6809 break;
6811 case N_Pop_Storage_Error_Label:
6812 gnu_storage_error_label_stack->pop ();
6813 break;
6815 case N_Pop_Program_Error_Label:
6816 gnu_program_error_label_stack->pop ();
6817 break;
6819 /******************************/
6820 /* Chapter 12: Generic Units */
6821 /******************************/
6823 case N_Generic_Function_Renaming_Declaration:
6824 case N_Generic_Package_Renaming_Declaration:
6825 case N_Generic_Procedure_Renaming_Declaration:
6826 case N_Generic_Package_Declaration:
6827 case N_Generic_Subprogram_Declaration:
6828 case N_Package_Instantiation:
6829 case N_Procedure_Instantiation:
6830 case N_Function_Instantiation:
6831 /* These nodes can appear on a declaration list but there is nothing to
6832 to be done with them. */
6833 gnu_result = alloc_stmt_list ();
6834 break;
6836 /**************************************************/
6837 /* Chapter 13: Representation Clauses and */
6838 /* Implementation-Dependent Features */
6839 /**************************************************/
6841 case N_Attribute_Definition_Clause:
6842 gnu_result = alloc_stmt_list ();
6844 /* The only one we need to deal with is 'Address since, for the others,
6845 the front-end puts the information elsewhere. */
6846 if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
6847 break;
6849 /* And we only deal with 'Address if the object has a Freeze node. */
6850 gnat_temp = Entity (Name (gnat_node));
6851 if (No (Freeze_Node (gnat_temp)))
6852 break;
6854 /* Get the value to use as the address and save it as the equivalent
6855 for the object. When it is frozen, gnat_to_gnu_entity will do the
6856 right thing. */
6857 save_gnu_tree (gnat_temp, gnat_to_gnu (Expression (gnat_node)), true);
6858 break;
6860 case N_Enumeration_Representation_Clause:
6861 case N_Record_Representation_Clause:
6862 case N_At_Clause:
6863 /* We do nothing with these. SEM puts the information elsewhere. */
6864 gnu_result = alloc_stmt_list ();
6865 break;
6867 case N_Code_Statement:
6868 if (!type_annotate_only)
6870 tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
6871 tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
6872 tree gnu_clobbers = NULL_TREE, tail;
6873 bool allows_mem, allows_reg, fake;
6874 int ninputs, noutputs, i;
6875 const char **oconstraints;
6876 const char *constraint;
6877 char *clobber;
6879 /* First retrieve the 3 operand lists built by the front-end. */
6880 Setup_Asm_Outputs (gnat_node);
6881 while (Present (gnat_temp = Asm_Output_Variable ()))
6883 tree gnu_value = gnat_to_gnu (gnat_temp);
6884 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
6885 (Asm_Output_Constraint ()));
6887 gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
6888 Next_Asm_Output ();
6891 Setup_Asm_Inputs (gnat_node);
6892 while (Present (gnat_temp = Asm_Input_Value ()))
6894 tree gnu_value = gnat_to_gnu (gnat_temp);
6895 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
6896 (Asm_Input_Constraint ()));
6898 gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
6899 Next_Asm_Input ();
6902 Clobber_Setup (gnat_node);
6903 while ((clobber = Clobber_Get_Next ()))
6904 gnu_clobbers
6905 = tree_cons (NULL_TREE,
6906 build_string (strlen (clobber) + 1, clobber),
6907 gnu_clobbers);
6909 /* Then perform some standard checking and processing on the
6910 operands. In particular, mark them addressable if needed. */
6911 gnu_outputs = nreverse (gnu_outputs);
6912 noutputs = list_length (gnu_outputs);
6913 gnu_inputs = nreverse (gnu_inputs);
6914 ninputs = list_length (gnu_inputs);
6915 oconstraints = XALLOCAVEC (const char *, noutputs);
6917 for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
6919 tree output = TREE_VALUE (tail);
6920 constraint
6921 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
6922 oconstraints[i] = constraint;
6924 if (parse_output_constraint (&constraint, i, ninputs, noutputs,
6925 &allows_mem, &allows_reg, &fake))
6927 /* If the operand is going to end up in memory,
6928 mark it addressable. Note that we don't test
6929 allows_mem like in the input case below; this
6930 is modelled on the C front-end. */
6931 if (!allows_reg)
6933 output = remove_conversions (output, false);
6934 if (TREE_CODE (output) == CONST_DECL
6935 && DECL_CONST_CORRESPONDING_VAR (output))
6936 output = DECL_CONST_CORRESPONDING_VAR (output);
6937 if (!gnat_mark_addressable (output))
6938 output = error_mark_node;
6941 else
6942 output = error_mark_node;
6944 TREE_VALUE (tail) = output;
6947 for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
6949 tree input = TREE_VALUE (tail);
6950 constraint
6951 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
6953 if (parse_input_constraint (&constraint, i, ninputs, noutputs,
6954 0, oconstraints,
6955 &allows_mem, &allows_reg))
6957 /* If the operand is going to end up in memory,
6958 mark it addressable. */
6959 if (!allows_reg && allows_mem)
6961 input = remove_conversions (input, false);
6962 if (TREE_CODE (input) == CONST_DECL
6963 && DECL_CONST_CORRESPONDING_VAR (input))
6964 input = DECL_CONST_CORRESPONDING_VAR (input);
6965 if (!gnat_mark_addressable (input))
6966 input = error_mark_node;
6969 else
6970 input = error_mark_node;
6972 TREE_VALUE (tail) = input;
6975 gnu_result = build5 (ASM_EXPR, void_type_node,
6976 gnu_template, gnu_outputs,
6977 gnu_inputs, gnu_clobbers, NULL_TREE);
6978 ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
6980 else
6981 gnu_result = alloc_stmt_list ();
6983 break;
6985 /****************/
6986 /* Added Nodes */
6987 /****************/
6989 case N_Expression_With_Actions:
6990 /* This construct doesn't define a scope so we don't push a binding level
6991 around the statement list; but we wrap it in a SAVE_EXPR to protect it
6992 from unsharing. */
6993 gnu_result = build_stmt_group (Actions (gnat_node), false);
6994 gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
6995 TREE_SIDE_EFFECTS (gnu_result) = 1;
6996 gnu_expr = gnat_to_gnu (Expression (gnat_node));
6997 gnu_result
6998 = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
6999 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7000 break;
7002 case N_Freeze_Entity:
7003 start_stmt_group ();
7004 process_freeze_entity (gnat_node);
7005 process_decls (Actions (gnat_node), Empty, Empty, true, true);
7006 gnu_result = end_stmt_group ();
7007 break;
7009 case N_Freeze_Generic_Entity:
7010 gnu_result = alloc_stmt_list ();
7011 break;
7013 case N_Itype_Reference:
7014 if (!present_gnu_tree (Itype (gnat_node)))
7015 process_type (Itype (gnat_node));
7017 gnu_result = alloc_stmt_list ();
7018 break;
7020 case N_Free_Statement:
7021 if (!type_annotate_only)
7023 tree gnu_ptr = gnat_to_gnu (Expression (gnat_node));
7024 tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
7025 tree gnu_obj_type, gnu_actual_obj_type;
7027 /* If this is a thin pointer, we must first dereference it to create
7028 a fat pointer, then go back below to a thin pointer. The reason
7029 for this is that we need to have a fat pointer someplace in order
7030 to properly compute the size. */
7031 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7032 gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
7033 build_unary_op (INDIRECT_REF, NULL_TREE,
7034 gnu_ptr));
7036 /* If this is a fat pointer, the object must have been allocated with
7037 the template in front of the array. So pass the template address,
7038 and get the total size; do it by converting to a thin pointer. */
7039 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
7040 gnu_ptr
7041 = convert (build_pointer_type
7042 (TYPE_OBJECT_RECORD_TYPE
7043 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
7044 gnu_ptr);
7046 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
7048 /* If this is a thin pointer, the object must have been allocated with
7049 the template in front of the array. So pass the template address,
7050 and get the total size. */
7051 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7052 gnu_ptr
7053 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
7054 gnu_ptr,
7055 fold_build1 (NEGATE_EXPR, sizetype,
7056 byte_position
7057 (DECL_CHAIN
7058 TYPE_FIELDS ((gnu_obj_type)))));
7060 /* If we have a special dynamic constrained subtype on the node, use
7061 it to compute the size; otherwise, use the designated subtype. */
7062 if (Present (Actual_Designated_Subtype (gnat_node)))
7064 gnu_actual_obj_type
7065 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
7067 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
7068 gnu_actual_obj_type
7069 = build_unc_object_type_from_ptr (gnu_ptr_type,
7070 gnu_actual_obj_type,
7071 get_identifier ("DEALLOC"),
7072 false);
7074 else
7075 gnu_actual_obj_type = gnu_obj_type;
7077 gnu_result
7078 = build_call_alloc_dealloc (gnu_ptr,
7079 TYPE_SIZE_UNIT (gnu_actual_obj_type),
7080 gnu_obj_type,
7081 Procedure_To_Call (gnat_node),
7082 Storage_Pool (gnat_node),
7083 gnat_node);
7085 break;
7087 case N_Raise_Constraint_Error:
7088 case N_Raise_Program_Error:
7089 case N_Raise_Storage_Error:
7090 if (type_annotate_only)
7091 gnu_result = alloc_stmt_list ();
7092 else
7093 gnu_result = Raise_Error_to_gnu (gnat_node, &gnu_result_type);
7094 break;
7096 case N_Validate_Unchecked_Conversion:
7097 /* The only validation we currently do on an unchecked conversion is
7098 that of aliasing assumptions. */
7099 if (flag_strict_aliasing)
7100 gnat_validate_uc_list.safe_push (gnat_node);
7101 gnu_result = alloc_stmt_list ();
7102 break;
7104 case N_Function_Specification:
7105 case N_Procedure_Specification:
7106 case N_Op_Concat:
7107 case N_Component_Association:
7108 case N_Protected_Body:
7109 case N_Task_Body:
7110 /* These nodes should only be present when annotating types. */
7111 gcc_assert (type_annotate_only);
7112 gnu_result = alloc_stmt_list ();
7113 break;
7115 default:
7116 /* Other nodes are not supposed to reach here. */
7117 gcc_unreachable ();
7120 /* If we pushed the processing of the elaboration routine, pop it back. */
7121 if (went_into_elab_proc)
7122 current_function_decl = NULL_TREE;
7124 /* When not optimizing, turn boolean rvalues B into B != false tests
7125 so that the code just below can put the location information of the
7126 reference to B on the inequality operator for better debug info. */
7127 if (!optimize
7128 && TREE_CODE (gnu_result) != INTEGER_CST
7129 && (kind == N_Identifier
7130 || kind == N_Expanded_Name
7131 || kind == N_Explicit_Dereference
7132 || kind == N_Function_Call
7133 || kind == N_Indexed_Component
7134 || kind == N_Selected_Component)
7135 && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
7136 && !lvalue_required_p (gnat_node, gnu_result_type, false, false, false))
7137 gnu_result = build_binary_op (NE_EXPR, gnu_result_type,
7138 convert (gnu_result_type, gnu_result),
7139 convert (gnu_result_type,
7140 boolean_false_node));
7142 /* Set the location information on the result. Note that we may have
7143 no result if we tried to build a CALL_EXPR node to a procedure with
7144 no side-effects and optimization is enabled. */
7145 if (gnu_result && EXPR_P (gnu_result))
7146 set_gnu_expr_location_from_node (gnu_result, gnat_node);
7148 /* If we're supposed to return something of void_type, it means we have
7149 something we're elaborating for effect, so just return. */
7150 if (TREE_CODE (gnu_result_type) == VOID_TYPE)
7151 return gnu_result;
7153 /* If the result is a constant that overflowed, raise Constraint_Error. */
7154 if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
7156 post_error ("?`Constraint_Error` will be raised at run time", gnat_node);
7157 gnu_result
7158 = build1 (NULL_EXPR, gnu_result_type,
7159 build_call_raise (CE_Overflow_Check_Failed, gnat_node,
7160 N_Raise_Constraint_Error));
7163 /* If the result has side-effects and is of an unconstrained type, make a
7164 SAVE_EXPR so that we can be sure it will only be referenced once. But
7165 this is useless for a call to a function that returns an unconstrained
7166 type with default discriminant, as we cannot compute the size of the
7167 actual returned object. We must do this before any conversions. */
7168 if (TREE_SIDE_EFFECTS (gnu_result)
7169 && !(TREE_CODE (gnu_result) == CALL_EXPR
7170 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
7171 && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
7172 || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))))
7173 gnu_result = gnat_stabilize_reference (gnu_result, false, NULL);
7175 /* Now convert the result to the result type, unless we are in one of the
7176 following cases:
7178 1. If this is the LHS of an assignment or an actual parameter of a
7179 call, return the result almost unmodified since the RHS will have
7180 to be converted to our type in that case, unless the result type
7181 has a simpler size. Likewise if there is just a no-op unchecked
7182 conversion in-between. Similarly, don't convert integral types
7183 that are the operands of an unchecked conversion since we need
7184 to ignore those conversions (for 'Valid).
7186 2. If we have a label (which doesn't have any well-defined type), a
7187 field or an error, return the result almost unmodified. Similarly,
7188 if the two types are record types with the same name, don't convert.
7189 This will be the case when we are converting from a packable version
7190 of a type to its original type and we need those conversions to be
7191 NOPs in order for assignments into these types to work properly.
7193 3. If the type is void or if we have no result, return error_mark_node
7194 to show we have no result.
7196 4. If this a call to a function that returns an unconstrained type with
7197 default discriminant, return the call expression unmodified since we
7198 cannot compute the size of the actual returned object.
7200 5. Finally, if the type of the result is already correct. */
7202 if (Present (Parent (gnat_node))
7203 && (lhs_or_actual_p (gnat_node)
7204 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7205 && unchecked_conversion_nop (Parent (gnat_node)))
7206 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7207 && !AGGREGATE_TYPE_P (gnu_result_type)
7208 && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
7209 && !(TYPE_SIZE (gnu_result_type)
7210 && TYPE_SIZE (TREE_TYPE (gnu_result))
7211 && (AGGREGATE_TYPE_P (gnu_result_type)
7212 == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
7213 && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
7214 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
7215 != INTEGER_CST))
7216 || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
7217 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
7218 && (CONTAINS_PLACEHOLDER_P
7219 (TYPE_SIZE (TREE_TYPE (gnu_result))))))
7220 && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
7221 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
7223 /* Remove padding only if the inner object is of self-referential
7224 size: in that case it must be an object of unconstrained type
7225 with a default discriminant and we want to avoid copying too
7226 much data. */
7227 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
7228 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
7229 (TREE_TYPE (gnu_result))))))
7230 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7231 gnu_result);
7234 else if (TREE_CODE (gnu_result) == LABEL_DECL
7235 || TREE_CODE (gnu_result) == FIELD_DECL
7236 || TREE_CODE (gnu_result) == ERROR_MARK
7237 || (TYPE_NAME (gnu_result_type)
7238 == TYPE_NAME (TREE_TYPE (gnu_result))
7239 && TREE_CODE (gnu_result_type) == RECORD_TYPE
7240 && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
7242 /* Remove any padding. */
7243 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
7244 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7245 gnu_result);
7248 else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
7249 gnu_result = error_mark_node;
7251 else if (TREE_CODE (gnu_result) == CALL_EXPR
7252 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
7253 && TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result)))
7254 == gnu_result_type
7255 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type)))
7258 else if (TREE_TYPE (gnu_result) != gnu_result_type)
7259 gnu_result = convert (gnu_result_type, gnu_result);
7261 /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result. */
7262 while ((TREE_CODE (gnu_result) == NOP_EXPR
7263 || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
7264 && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
7265 gnu_result = TREE_OPERAND (gnu_result, 0);
7267 return gnu_result;
7270 /* Subroutine of above to push the exception label stack. GNU_STACK is
7271 a pointer to the stack to update and GNAT_LABEL, if present, is the
7272 label to push onto the stack. */
7274 static void
7275 push_exception_label_stack (vec<tree, va_gc> **gnu_stack, Entity_Id gnat_label)
7277 tree gnu_label = (Present (gnat_label)
7278 ? gnat_to_gnu_entity (gnat_label, NULL_TREE, 0)
7279 : NULL_TREE);
7281 vec_safe_push (*gnu_stack, gnu_label);
7284 /* Record the current code position in GNAT_NODE. */
7286 static void
7287 record_code_position (Node_Id gnat_node)
7289 tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
7291 add_stmt_with_node (stmt_stmt, gnat_node);
7292 save_gnu_tree (gnat_node, stmt_stmt, true);
7295 /* Insert the code for GNAT_NODE at the position saved for that node. */
7297 static void
7298 insert_code_for (Node_Id gnat_node)
7300 STMT_STMT_STMT (get_gnu_tree (gnat_node)) = gnat_to_gnu (gnat_node);
7301 save_gnu_tree (gnat_node, NULL_TREE, true);
7304 /* Start a new statement group chained to the previous group. */
7306 void
7307 start_stmt_group (void)
7309 struct stmt_group *group = stmt_group_free_list;
7311 /* First see if we can get one from the free list. */
7312 if (group)
7313 stmt_group_free_list = group->previous;
7314 else
7315 group = ggc_alloc<stmt_group> ();
7317 group->previous = current_stmt_group;
7318 group->stmt_list = group->block = group->cleanups = NULL_TREE;
7319 current_stmt_group = group;
7322 /* Add GNU_STMT to the current statement group. If it is an expression with
7323 no effects, it is ignored. */
7325 void
7326 add_stmt (tree gnu_stmt)
7328 append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
7331 /* Similar, but the statement is always added, regardless of side-effects. */
7333 void
7334 add_stmt_force (tree gnu_stmt)
7336 append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
7339 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE. */
7341 void
7342 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
7344 /* Do not emit a location for renamings that come from generic instantiation,
7345 they are likely to disturb debugging. */
7346 if (Present (gnat_node)
7347 && !renaming_from_generic_instantiation_p (gnat_node))
7348 set_expr_location_from_node (gnu_stmt, gnat_node);
7349 add_stmt (gnu_stmt);
7352 /* Similar, but the statement is always added, regardless of side-effects. */
7354 void
7355 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
7357 if (Present (gnat_node))
7358 set_expr_location_from_node (gnu_stmt, gnat_node);
7359 add_stmt_force (gnu_stmt);
7362 /* Add a declaration statement for GNU_DECL to the current statement group.
7363 Get SLOC from Entity_Id. */
7365 void
7366 add_decl_expr (tree gnu_decl, Entity_Id gnat_entity)
7368 tree type = TREE_TYPE (gnu_decl);
7369 tree gnu_stmt, gnu_init, t;
7371 /* If this is a variable that Gigi is to ignore, we may have been given
7372 an ERROR_MARK. So test for it. We also might have been given a
7373 reference for a renaming. So only do something for a decl. Also
7374 ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE. */
7375 if (!DECL_P (gnu_decl)
7376 || (TREE_CODE (gnu_decl) == TYPE_DECL
7377 && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
7378 return;
7380 gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
7382 /* If we are external or global, we don't want to output the DECL_EXPR for
7383 this DECL node since we already have evaluated the expressions in the
7384 sizes and positions as globals and doing it again would be wrong. */
7385 if (DECL_EXTERNAL (gnu_decl) || global_bindings_p ())
7387 /* Mark everything as used to prevent node sharing with subprograms.
7388 Note that walk_tree knows how to deal with TYPE_DECL, but neither
7389 VAR_DECL nor CONST_DECL. This appears to be somewhat arbitrary. */
7390 MARK_VISITED (gnu_stmt);
7391 if (TREE_CODE (gnu_decl) == VAR_DECL
7392 || TREE_CODE (gnu_decl) == CONST_DECL)
7394 MARK_VISITED (DECL_SIZE (gnu_decl));
7395 MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
7396 MARK_VISITED (DECL_INITIAL (gnu_decl));
7398 /* In any case, we have to deal with our own TYPE_ADA_SIZE field. */
7399 else if (TREE_CODE (gnu_decl) == TYPE_DECL
7400 && RECORD_OR_UNION_TYPE_P (type)
7401 && !TYPE_FAT_POINTER_P (type))
7402 MARK_VISITED (TYPE_ADA_SIZE (type));
7404 else
7405 add_stmt_with_node (gnu_stmt, gnat_entity);
7407 /* If this is a variable and an initializer is attached to it, it must be
7408 valid for the context. Similar to init_const in create_var_decl_1. */
7409 if (TREE_CODE (gnu_decl) == VAR_DECL
7410 && (gnu_init = DECL_INITIAL (gnu_decl)) != NULL_TREE
7411 && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
7412 || (TREE_STATIC (gnu_decl)
7413 && !initializer_constant_valid_p (gnu_init,
7414 TREE_TYPE (gnu_init)))))
7416 /* If GNU_DECL has a padded type, convert it to the unpadded
7417 type so the assignment is done properly. */
7418 if (TYPE_IS_PADDING_P (type))
7419 t = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
7420 else
7421 t = gnu_decl;
7423 gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, t, gnu_init);
7425 DECL_INITIAL (gnu_decl) = NULL_TREE;
7426 if (TREE_READONLY (gnu_decl))
7428 TREE_READONLY (gnu_decl) = 0;
7429 DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
7432 add_stmt_with_node (gnu_stmt, gnat_entity);
7436 /* Callback for walk_tree to mark the visited trees rooted at *TP. */
7438 static tree
7439 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
7441 tree t = *tp;
7443 if (TREE_VISITED (t))
7444 *walk_subtrees = 0;
7446 /* Don't mark a dummy type as visited because we want to mark its sizes
7447 and fields once it's filled in. */
7448 else if (!TYPE_IS_DUMMY_P (t))
7449 TREE_VISITED (t) = 1;
7451 if (TYPE_P (t))
7452 TYPE_SIZES_GIMPLIFIED (t) = 1;
7454 return NULL_TREE;
7457 /* Mark nodes rooted at T with TREE_VISITED and types as having their
7458 sized gimplified. We use this to indicate all variable sizes and
7459 positions in global types may not be shared by any subprogram. */
7461 void
7462 mark_visited (tree t)
7464 walk_tree (&t, mark_visited_r, NULL, NULL);
7467 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
7468 set its location to that of GNAT_NODE if present, but with column info
7469 cleared so that conditional branches generated as part of the cleanup
7470 code do not interfere with coverage analysis tools. */
7472 static void
7473 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
7475 if (Present (gnat_node))
7476 set_expr_location_from_node1 (gnu_cleanup, gnat_node, true);
7477 append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
7480 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK. */
7482 void
7483 set_block_for_group (tree gnu_block)
7485 gcc_assert (!current_stmt_group->block);
7486 current_stmt_group->block = gnu_block;
7489 /* Return code corresponding to the current code group. It is normally
7490 a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
7491 BLOCK or cleanups were set. */
7493 tree
7494 end_stmt_group (void)
7496 struct stmt_group *group = current_stmt_group;
7497 tree gnu_retval = group->stmt_list;
7499 /* If this is a null list, allocate a new STATEMENT_LIST. Then, if there
7500 are cleanups, make a TRY_FINALLY_EXPR. Last, if there is a BLOCK,
7501 make a BIND_EXPR. Note that we nest in that because the cleanup may
7502 reference variables in the block. */
7503 if (gnu_retval == NULL_TREE)
7504 gnu_retval = alloc_stmt_list ();
7506 if (group->cleanups)
7507 gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
7508 group->cleanups);
7510 if (current_stmt_group->block)
7511 gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
7512 gnu_retval, group->block);
7514 /* Remove this group from the stack and add it to the free list. */
7515 current_stmt_group = group->previous;
7516 group->previous = stmt_group_free_list;
7517 stmt_group_free_list = group;
7519 return gnu_retval;
7522 /* Return whether the current statement group may fall through. */
7524 static inline bool
7525 stmt_group_may_fallthru (void)
7527 if (current_stmt_group->stmt_list)
7528 return block_may_fallthru (current_stmt_group->stmt_list);
7529 else
7530 return true;
7533 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
7534 statements.*/
7536 static void
7537 add_stmt_list (List_Id gnat_list)
7539 Node_Id gnat_node;
7541 if (Present (gnat_list))
7542 for (gnat_node = First (gnat_list); Present (gnat_node);
7543 gnat_node = Next (gnat_node))
7544 add_stmt (gnat_to_gnu (gnat_node));
7547 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
7548 If BINDING_P is true, push and pop a binding level around the list. */
7550 static tree
7551 build_stmt_group (List_Id gnat_list, bool binding_p)
7553 start_stmt_group ();
7554 if (binding_p)
7555 gnat_pushlevel ();
7557 add_stmt_list (gnat_list);
7558 if (binding_p)
7559 gnat_poplevel ();
7561 return end_stmt_group ();
7564 /* Generate GIMPLE in place for the expression at *EXPR_P. */
7567 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
7568 gimple_seq *post_p ATTRIBUTE_UNUSED)
7570 tree expr = *expr_p;
7571 tree op;
7573 if (IS_ADA_STMT (expr))
7574 return gnat_gimplify_stmt (expr_p);
7576 switch (TREE_CODE (expr))
7578 case NULL_EXPR:
7579 /* If this is for a scalar, just make a VAR_DECL for it. If for
7580 an aggregate, get a null pointer of the appropriate type and
7581 dereference it. */
7582 if (AGGREGATE_TYPE_P (TREE_TYPE (expr)))
7583 *expr_p = build1 (INDIRECT_REF, TREE_TYPE (expr),
7584 convert (build_pointer_type (TREE_TYPE (expr)),
7585 integer_zero_node));
7586 else
7588 *expr_p = create_tmp_var (TREE_TYPE (expr), NULL);
7589 TREE_NO_WARNING (*expr_p) = 1;
7592 gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
7593 return GS_OK;
7595 case UNCONSTRAINED_ARRAY_REF:
7596 /* We should only do this if we are just elaborating for side-effects,
7597 but we can't know that yet. */
7598 *expr_p = TREE_OPERAND (*expr_p, 0);
7599 return GS_OK;
7601 case ADDR_EXPR:
7602 op = TREE_OPERAND (expr, 0);
7604 /* If we are taking the address of a constant CONSTRUCTOR, make sure it
7605 is put into static memory. We know that it's going to be read-only
7606 given the semantics we have and it must be in static memory when the
7607 reference is in an elaboration procedure. */
7608 if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
7610 tree addr = build_fold_addr_expr (tree_output_constant_def (op));
7611 *expr_p = fold_convert (TREE_TYPE (expr), addr);
7612 return GS_ALL_DONE;
7615 return GS_UNHANDLED;
7617 case VIEW_CONVERT_EXPR:
7618 op = TREE_OPERAND (expr, 0);
7620 /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
7621 type to a scalar one, explicitly create the local temporary. That's
7622 required if the type is passed by reference. */
7623 if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
7624 && AGGREGATE_TYPE_P (TREE_TYPE (op))
7625 && !AGGREGATE_TYPE_P (TREE_TYPE (expr)))
7627 tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
7628 gimple_add_tmp_var (new_var);
7630 mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
7631 gimplify_and_add (mod, pre_p);
7633 TREE_OPERAND (expr, 0) = new_var;
7634 return GS_OK;
7637 return GS_UNHANDLED;
7639 case DECL_EXPR:
7640 op = DECL_EXPR_DECL (expr);
7642 /* The expressions for the RM bounds must be gimplified to ensure that
7643 they are properly elaborated. See gimplify_decl_expr. */
7644 if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
7645 && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
7646 switch (TREE_CODE (TREE_TYPE (op)))
7648 case INTEGER_TYPE:
7649 case ENUMERAL_TYPE:
7650 case BOOLEAN_TYPE:
7651 case REAL_TYPE:
7653 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
7655 val = TYPE_RM_MIN_VALUE (type);
7656 if (val)
7658 gimplify_one_sizepos (&val, pre_p);
7659 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7660 SET_TYPE_RM_MIN_VALUE (t, val);
7663 val = TYPE_RM_MAX_VALUE (type);
7664 if (val)
7666 gimplify_one_sizepos (&val, pre_p);
7667 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7668 SET_TYPE_RM_MAX_VALUE (t, val);
7672 break;
7674 default:
7675 break;
7678 /* ... fall through ... */
7680 default:
7681 return GS_UNHANDLED;
7685 /* Generate GIMPLE in place for the statement at *STMT_P. */
7687 static enum gimplify_status
7688 gnat_gimplify_stmt (tree *stmt_p)
7690 tree stmt = *stmt_p;
7692 switch (TREE_CODE (stmt))
7694 case STMT_STMT:
7695 *stmt_p = STMT_STMT_STMT (stmt);
7696 return GS_OK;
7698 case LOOP_STMT:
7700 tree gnu_start_label = create_artificial_label (input_location);
7701 tree gnu_cond = LOOP_STMT_COND (stmt);
7702 tree gnu_update = LOOP_STMT_UPDATE (stmt);
7703 tree gnu_end_label = LOOP_STMT_LABEL (stmt);
7705 /* Build the condition expression from the test, if any. */
7706 if (gnu_cond)
7708 /* Deal with the optimization hints. */
7709 if (LOOP_STMT_IVDEP (stmt))
7710 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7711 build_int_cst (integer_type_node,
7712 annot_expr_ivdep_kind));
7713 if (LOOP_STMT_NO_VECTOR (stmt))
7714 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7715 build_int_cst (integer_type_node,
7716 annot_expr_no_vector_kind));
7717 if (LOOP_STMT_VECTOR (stmt))
7718 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7719 build_int_cst (integer_type_node,
7720 annot_expr_vector_kind));
7722 gnu_cond
7723 = build3 (COND_EXPR, void_type_node, gnu_cond, NULL_TREE,
7724 build1 (GOTO_EXPR, void_type_node, gnu_end_label));
7727 /* Set to emit the statements of the loop. */
7728 *stmt_p = NULL_TREE;
7730 /* We first emit the start label and then a conditional jump to the
7731 end label if there's a top condition, then the update if it's at
7732 the top, then the body of the loop, then a conditional jump to
7733 the end label if there's a bottom condition, then the update if
7734 it's at the bottom, and finally a jump to the start label and the
7735 definition of the end label. */
7736 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7737 gnu_start_label),
7738 stmt_p);
7740 if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
7741 append_to_statement_list (gnu_cond, stmt_p);
7743 if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
7744 append_to_statement_list (gnu_update, stmt_p);
7746 append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
7748 if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
7749 append_to_statement_list (gnu_cond, stmt_p);
7751 if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
7752 append_to_statement_list (gnu_update, stmt_p);
7754 tree t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
7755 SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
7756 append_to_statement_list (t, stmt_p);
7758 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7759 gnu_end_label),
7760 stmt_p);
7761 return GS_OK;
7764 case EXIT_STMT:
7765 /* Build a statement to jump to the corresponding end label, then
7766 see if it needs to be conditional. */
7767 *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
7768 if (EXIT_STMT_COND (stmt))
7769 *stmt_p = build3 (COND_EXPR, void_type_node,
7770 EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
7771 return GS_OK;
7773 default:
7774 gcc_unreachable ();
7778 /* Force references to each of the entities in packages withed by GNAT_NODE.
7779 Operate recursively but check that we aren't elaborating something more
7780 than once.
7782 This routine is exclusively called in type_annotate mode, to compute DDA
7783 information for types in withed units, for ASIS use. */
7785 static void
7786 elaborate_all_entities (Node_Id gnat_node)
7788 Entity_Id gnat_with_clause, gnat_entity;
7790 /* Process each unit only once. As we trace the context of all relevant
7791 units transitively, including generic bodies, we may encounter the
7792 same generic unit repeatedly. */
7793 if (!present_gnu_tree (gnat_node))
7794 save_gnu_tree (gnat_node, integer_zero_node, true);
7796 /* Save entities in all context units. A body may have an implicit_with
7797 on its own spec, if the context includes a child unit, so don't save
7798 the spec twice. */
7799 for (gnat_with_clause = First (Context_Items (gnat_node));
7800 Present (gnat_with_clause);
7801 gnat_with_clause = Next (gnat_with_clause))
7802 if (Nkind (gnat_with_clause) == N_With_Clause
7803 && !present_gnu_tree (Library_Unit (gnat_with_clause))
7804 && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
7806 elaborate_all_entities (Library_Unit (gnat_with_clause));
7808 if (Ekind (Entity (Name (gnat_with_clause))) == E_Package)
7810 for (gnat_entity = First_Entity (Entity (Name (gnat_with_clause)));
7811 Present (gnat_entity);
7812 gnat_entity = Next_Entity (gnat_entity))
7813 if (Is_Public (gnat_entity)
7814 && Convention (gnat_entity) != Convention_Intrinsic
7815 && Ekind (gnat_entity) != E_Package
7816 && Ekind (gnat_entity) != E_Package_Body
7817 && Ekind (gnat_entity) != E_Operator
7818 && !(IN (Ekind (gnat_entity), Type_Kind)
7819 && !Is_Frozen (gnat_entity))
7820 && !((Ekind (gnat_entity) == E_Procedure
7821 || Ekind (gnat_entity) == E_Function)
7822 && Is_Intrinsic_Subprogram (gnat_entity))
7823 && !IN (Ekind (gnat_entity), Named_Kind)
7824 && !IN (Ekind (gnat_entity), Generic_Unit_Kind))
7825 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
7827 else if (Ekind (Entity (Name (gnat_with_clause))) == E_Generic_Package)
7829 Node_Id gnat_body
7830 = Corresponding_Body (Unit (Library_Unit (gnat_with_clause)));
7832 /* Retrieve compilation unit node of generic body. */
7833 while (Present (gnat_body)
7834 && Nkind (gnat_body) != N_Compilation_Unit)
7835 gnat_body = Parent (gnat_body);
7837 /* If body is available, elaborate its context. */
7838 if (Present (gnat_body))
7839 elaborate_all_entities (gnat_body);
7843 if (Nkind (Unit (gnat_node)) == N_Package_Body)
7844 elaborate_all_entities (Library_Unit (gnat_node));
7847 /* Do the processing of GNAT_NODE, an N_Freeze_Entity. */
7849 static void
7850 process_freeze_entity (Node_Id gnat_node)
7852 const Entity_Id gnat_entity = Entity (gnat_node);
7853 const Entity_Kind kind = Ekind (gnat_entity);
7854 tree gnu_old, gnu_new;
7856 /* If this is a package, we need to generate code for the package. */
7857 if (kind == E_Package)
7859 insert_code_for
7860 (Parent (Corresponding_Body
7861 (Parent (Declaration_Node (gnat_entity)))));
7862 return;
7865 /* Don't do anything for class-wide types as they are always transformed
7866 into their root type. */
7867 if (kind == E_Class_Wide_Type)
7868 return;
7870 /* Check for an old definition. This freeze node might be for an Itype. */
7871 gnu_old
7872 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
7874 /* If this entity has an address representation clause, GNU_OLD is the
7875 address, so discard it here. */
7876 if (Present (Address_Clause (gnat_entity)))
7877 gnu_old = NULL_TREE;
7879 /* Don't do anything for subprograms that may have been elaborated before
7880 their freeze nodes. This can happen, for example, because of an inner
7881 call in an instance body or because of previous compilation of a spec
7882 for inlining purposes. */
7883 if (gnu_old
7884 && ((TREE_CODE (gnu_old) == FUNCTION_DECL
7885 && (kind == E_Function || kind == E_Procedure))
7886 || (TREE_CODE (TREE_TYPE (gnu_old)) == FUNCTION_TYPE
7887 && kind == E_Subprogram_Type)))
7888 return;
7890 /* If we have a non-dummy type old tree, we have nothing to do, except
7891 aborting if this is the public view of a private type whose full view was
7892 not delayed, as this node was never delayed as it should have been. We
7893 let this happen for concurrent types and their Corresponding_Record_Type,
7894 however, because each might legitimately be elaborated before its own
7895 freeze node, e.g. while processing the other. */
7896 if (gnu_old
7897 && !(TREE_CODE (gnu_old) == TYPE_DECL
7898 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
7900 gcc_assert ((IN (kind, Incomplete_Or_Private_Kind)
7901 && Present (Full_View (gnat_entity))
7902 && No (Freeze_Node (Full_View (gnat_entity))))
7903 || Is_Concurrent_Type (gnat_entity)
7904 || (IN (kind, Record_Kind)
7905 && Is_Concurrent_Record_Type (gnat_entity)));
7906 return;
7909 /* Reset the saved tree, if any, and elaborate the object or type for real.
7910 If there is a full view, elaborate it and use the result. And, if this
7911 is the root type of a class-wide type, reuse it for the latter. */
7912 if (gnu_old)
7914 save_gnu_tree (gnat_entity, NULL_TREE, false);
7916 if (IN (kind, Incomplete_Or_Private_Kind)
7917 && Present (Full_View (gnat_entity)))
7919 Entity_Id full_view = Full_View (gnat_entity);
7921 save_gnu_tree (full_view, NULL_TREE, false);
7923 if (IN (Ekind (full_view), Private_Kind)
7924 && Present (Underlying_Full_View (full_view)))
7926 full_view = Underlying_Full_View (full_view);
7927 save_gnu_tree (full_view, NULL_TREE, false);
7931 if (IN (kind, Type_Kind)
7932 && Present (Class_Wide_Type (gnat_entity))
7933 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
7934 save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
7937 if (IN (kind, Incomplete_Or_Private_Kind)
7938 && Present (Full_View (gnat_entity)))
7940 Entity_Id full_view = Full_View (gnat_entity);
7942 if (IN (Ekind (full_view), Private_Kind)
7943 && Present (Underlying_Full_View (full_view)))
7944 full_view = Underlying_Full_View (full_view);
7946 gnu_new = gnat_to_gnu_entity (full_view, NULL_TREE, 1);
7948 /* Propagate back-annotations from full view to partial view. */
7949 if (Unknown_Alignment (gnat_entity))
7950 Set_Alignment (gnat_entity, Alignment (full_view));
7952 if (Unknown_Esize (gnat_entity))
7953 Set_Esize (gnat_entity, Esize (full_view));
7955 if (Unknown_RM_Size (gnat_entity))
7956 Set_RM_Size (gnat_entity, RM_Size (full_view));
7958 /* The above call may have defined this entity (the simplest example
7959 of this is when we have a private enumeral type since the bounds
7960 will have the public view). */
7961 if (!present_gnu_tree (gnat_entity))
7962 save_gnu_tree (gnat_entity, gnu_new, false);
7964 else
7966 tree gnu_init
7967 = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
7968 && present_gnu_tree (Declaration_Node (gnat_entity)))
7969 ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
7971 gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, 1);
7974 if (IN (kind, Type_Kind)
7975 && Present (Class_Wide_Type (gnat_entity))
7976 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
7977 save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
7979 /* If we have an old type and we've made pointers to this type, update those
7980 pointers. If this is a Taft amendment type in the main unit, we need to
7981 mark the type as used since other units referencing it don't see the full
7982 declaration and, therefore, cannot mark it as used themselves. */
7983 if (gnu_old)
7985 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
7986 TREE_TYPE (gnu_new));
7987 if (DECL_TAFT_TYPE_P (gnu_old))
7988 used_types_insert (TREE_TYPE (gnu_new));
7992 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
7993 We make two passes, one to elaborate anything other than bodies (but
7994 we declare a function if there was no spec). The second pass
7995 elaborates the bodies.
7997 GNAT_END_LIST gives the element in the list past the end. Normally,
7998 this is Empty, but can be First_Real_Statement for a
7999 Handled_Sequence_Of_Statements.
8001 We make a complete pass through both lists if PASS1P is true, then make
8002 the second pass over both lists if PASS2P is true. The lists usually
8003 correspond to the public and private parts of a package. */
8005 static void
8006 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
8007 Node_Id gnat_end_list, bool pass1p, bool pass2p)
8009 List_Id gnat_decl_array[2];
8010 Node_Id gnat_decl;
8011 int i;
8013 gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
8015 if (pass1p)
8016 for (i = 0; i <= 1; i++)
8017 if (Present (gnat_decl_array[i]))
8018 for (gnat_decl = First (gnat_decl_array[i]);
8019 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8021 /* For package specs, we recurse inside the declarations,
8022 thus taking the two pass approach inside the boundary. */
8023 if (Nkind (gnat_decl) == N_Package_Declaration
8024 && (Nkind (Specification (gnat_decl)
8025 == N_Package_Specification)))
8026 process_decls (Visible_Declarations (Specification (gnat_decl)),
8027 Private_Declarations (Specification (gnat_decl)),
8028 Empty, true, false);
8030 /* Similarly for any declarations in the actions of a
8031 freeze node. */
8032 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8034 process_freeze_entity (gnat_decl);
8035 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
8038 /* Package bodies with freeze nodes get their elaboration deferred
8039 until the freeze node, but the code must be placed in the right
8040 place, so record the code position now. */
8041 else if (Nkind (gnat_decl) == N_Package_Body
8042 && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
8043 record_code_position (gnat_decl);
8045 else if (Nkind (gnat_decl) == N_Package_Body_Stub
8046 && Present (Library_Unit (gnat_decl))
8047 && Present (Freeze_Node
8048 (Corresponding_Spec
8049 (Proper_Body (Unit
8050 (Library_Unit (gnat_decl)))))))
8051 record_code_position
8052 (Proper_Body (Unit (Library_Unit (gnat_decl))));
8054 /* We defer most subprogram bodies to the second pass. */
8055 else if (Nkind (gnat_decl) == N_Subprogram_Body)
8057 if (Acts_As_Spec (gnat_decl))
8059 Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
8061 if (Ekind (gnat_subprog_id) != E_Generic_Procedure
8062 && Ekind (gnat_subprog_id) != E_Generic_Function)
8063 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8067 /* For bodies and stubs that act as their own specs, the entity
8068 itself must be elaborated in the first pass, because it may
8069 be used in other declarations. */
8070 else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
8072 Node_Id gnat_subprog_id
8073 = Defining_Entity (Specification (gnat_decl));
8075 if (Ekind (gnat_subprog_id) != E_Subprogram_Body
8076 && Ekind (gnat_subprog_id) != E_Generic_Procedure
8077 && Ekind (gnat_subprog_id) != E_Generic_Function)
8078 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8081 /* Concurrent stubs stand for the corresponding subprogram bodies,
8082 which are deferred like other bodies. */
8083 else if (Nkind (gnat_decl) == N_Task_Body_Stub
8084 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8087 else
8088 add_stmt (gnat_to_gnu (gnat_decl));
8091 /* Here we elaborate everything we deferred above except for package bodies,
8092 which are elaborated at their freeze nodes. Note that we must also
8093 go inside things (package specs and freeze nodes) the first pass did. */
8094 if (pass2p)
8095 for (i = 0; i <= 1; i++)
8096 if (Present (gnat_decl_array[i]))
8097 for (gnat_decl = First (gnat_decl_array[i]);
8098 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8100 if (Nkind (gnat_decl) == N_Subprogram_Body
8101 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
8102 || Nkind (gnat_decl) == N_Task_Body_Stub
8103 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8104 add_stmt (gnat_to_gnu (gnat_decl));
8106 else if (Nkind (gnat_decl) == N_Package_Declaration
8107 && (Nkind (Specification (gnat_decl)
8108 == N_Package_Specification)))
8109 process_decls (Visible_Declarations (Specification (gnat_decl)),
8110 Private_Declarations (Specification (gnat_decl)),
8111 Empty, false, true);
8113 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8114 process_decls (Actions (gnat_decl), Empty, Empty, false, true);
8118 /* Make a unary operation of kind CODE using build_unary_op, but guard
8119 the operation by an overflow check. CODE can be one of NEGATE_EXPR
8120 or ABS_EXPR. GNU_TYPE is the type desired for the result. Usually
8121 the operation is to be performed in that type. GNAT_NODE is the gnat
8122 node conveying the source location for which the error should be
8123 signaled. */
8125 static tree
8126 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
8127 Node_Id gnat_node)
8129 gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
8131 operand = gnat_protect_expr (operand);
8133 return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
8134 operand, TYPE_MIN_VALUE (gnu_type)),
8135 build_unary_op (code, gnu_type, operand),
8136 CE_Overflow_Check_Failed, gnat_node);
8139 /* Make a binary operation of kind CODE using build_binary_op, but guard
8140 the operation by an overflow check. CODE can be one of PLUS_EXPR,
8141 MINUS_EXPR or MULT_EXPR. GNU_TYPE is the type desired for the result.
8142 Usually the operation is to be performed in that type. GNAT_NODE is
8143 the GNAT node conveying the source location for which the error should
8144 be signaled. */
8146 static tree
8147 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
8148 tree right, Node_Id gnat_node)
8150 const unsigned int precision = TYPE_PRECISION (gnu_type);
8151 tree lhs = gnat_protect_expr (left);
8152 tree rhs = gnat_protect_expr (right);
8153 tree type_max = TYPE_MAX_VALUE (gnu_type);
8154 tree type_min = TYPE_MIN_VALUE (gnu_type);
8155 tree zero = convert (gnu_type, integer_zero_node);
8156 tree gnu_expr, rhs_lt_zero, tmp1, tmp2;
8157 tree check_pos, check_neg, check;
8159 /* Assert that the precision is a power of 2. */
8160 gcc_assert ((precision & (precision - 1)) == 0);
8162 /* Prefer a constant or known-positive rhs to simplify checks. */
8163 if (!TREE_CONSTANT (rhs)
8164 && commutative_tree_code (code)
8165 && (TREE_CONSTANT (lhs)
8166 || (!tree_expr_nonnegative_p (rhs)
8167 && tree_expr_nonnegative_p (lhs))))
8169 tree tmp = lhs;
8170 lhs = rhs;
8171 rhs = tmp;
8174 gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
8176 /* If we can fold the expression to a constant, just return it.
8177 The caller will deal with overflow, no need to generate a check. */
8178 if (TREE_CONSTANT (gnu_expr))
8179 return gnu_expr;
8181 rhs_lt_zero = tree_expr_nonnegative_p (rhs)
8182 ? boolean_false_node
8183 : build_binary_op (LT_EXPR, boolean_type_node, rhs, zero);
8185 /* ??? Should use more efficient check for operand_equal_p (lhs, rhs, 0) */
8187 /* Try a few strategies that may be cheaper than the general
8188 code at the end of the function, if the rhs is not known.
8189 The strategies are:
8190 - Call library function for 64-bit multiplication (complex)
8191 - Widen, if input arguments are sufficiently small
8192 - Determine overflow using wrapped result for addition/subtraction. */
8194 if (!TREE_CONSTANT (rhs))
8196 /* Even for add/subtract double size to get another base type. */
8197 const unsigned int needed_precision = precision * 2;
8199 if (code == MULT_EXPR && precision == 64)
8201 tree int_64 = gnat_type_for_size (64, 0);
8203 return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
8204 convert (int_64, lhs),
8205 convert (int_64, rhs)));
8208 if (needed_precision <= BITS_PER_WORD
8209 || (code == MULT_EXPR && needed_precision <= LONG_LONG_TYPE_SIZE))
8211 tree wide_type = gnat_type_for_size (needed_precision, 0);
8212 tree wide_result = build_binary_op (code, wide_type,
8213 convert (wide_type, lhs),
8214 convert (wide_type, rhs));
8216 check = build_binary_op
8217 (TRUTH_ORIF_EXPR, boolean_type_node,
8218 build_binary_op (LT_EXPR, boolean_type_node, wide_result,
8219 convert (wide_type, type_min)),
8220 build_binary_op (GT_EXPR, boolean_type_node, wide_result,
8221 convert (wide_type, type_max)));
8223 return
8224 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8227 if (code == PLUS_EXPR || code == MINUS_EXPR)
8229 tree unsigned_type = gnat_type_for_size (precision, 1);
8230 tree wrapped_expr
8231 = convert (gnu_type,
8232 build_binary_op (code, unsigned_type,
8233 convert (unsigned_type, lhs),
8234 convert (unsigned_type, rhs)));
8236 /* Overflow when (rhs < 0) ^ (wrapped_expr < lhs)), for addition
8237 or when (rhs < 0) ^ (wrapped_expr > lhs) for subtraction. */
8238 check
8239 = build_binary_op (TRUTH_XOR_EXPR, boolean_type_node, rhs_lt_zero,
8240 build_binary_op (code == PLUS_EXPR
8241 ? LT_EXPR : GT_EXPR,
8242 boolean_type_node,
8243 wrapped_expr, lhs));
8245 return
8246 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8250 switch (code)
8252 case PLUS_EXPR:
8253 /* When rhs >= 0, overflow when lhs > type_max - rhs. */
8254 check_pos = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8255 build_binary_op (MINUS_EXPR, gnu_type,
8256 type_max, rhs)),
8258 /* When rhs < 0, overflow when lhs < type_min - rhs. */
8259 check_neg = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8260 build_binary_op (MINUS_EXPR, gnu_type,
8261 type_min, rhs));
8262 break;
8264 case MINUS_EXPR:
8265 /* When rhs >= 0, overflow when lhs < type_min + rhs. */
8266 check_pos = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8267 build_binary_op (PLUS_EXPR, gnu_type,
8268 type_min, rhs)),
8270 /* When rhs < 0, overflow when lhs > type_max + rhs. */
8271 check_neg = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8272 build_binary_op (PLUS_EXPR, gnu_type,
8273 type_max, rhs));
8274 break;
8276 case MULT_EXPR:
8277 /* The check here is designed to be efficient if the rhs is constant,
8278 but it will work for any rhs by using integer division.
8279 Four different check expressions determine whether X * C overflows,
8280 depending on C.
8281 C == 0 => false
8282 C > 0 => X > type_max / C || X < type_min / C
8283 C == -1 => X == type_min
8284 C < -1 => X > type_min / C || X < type_max / C */
8286 tmp1 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
8287 tmp2 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
8289 check_pos
8290 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
8291 build_binary_op (NE_EXPR, boolean_type_node, zero,
8292 rhs),
8293 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8294 build_binary_op (GT_EXPR,
8295 boolean_type_node,
8296 lhs, tmp1),
8297 build_binary_op (LT_EXPR,
8298 boolean_type_node,
8299 lhs, tmp2)));
8301 check_neg
8302 = fold_build3 (COND_EXPR, boolean_type_node,
8303 build_binary_op (EQ_EXPR, boolean_type_node, rhs,
8304 build_int_cst (gnu_type, -1)),
8305 build_binary_op (EQ_EXPR, boolean_type_node, lhs,
8306 type_min),
8307 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8308 build_binary_op (GT_EXPR,
8309 boolean_type_node,
8310 lhs, tmp2),
8311 build_binary_op (LT_EXPR,
8312 boolean_type_node,
8313 lhs, tmp1)));
8314 break;
8316 default:
8317 gcc_unreachable();
8320 check = fold_build3 (COND_EXPR, boolean_type_node, rhs_lt_zero, check_neg,
8321 check_pos);
8323 return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8326 /* Emit code for a range check. GNU_EXPR is the expression to be checked,
8327 GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
8328 which we have to check. GNAT_NODE is the GNAT node conveying the source
8329 location for which the error should be signaled. */
8331 static tree
8332 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type, Node_Id gnat_node)
8334 tree gnu_range_type = get_unpadded_type (gnat_range_type);
8335 tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
8337 /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
8338 This can for example happen when translating 'Val or 'Value. */
8339 if (gnu_compare_type == gnu_range_type)
8340 return gnu_expr;
8342 /* Range checks can only be applied to types with ranges. */
8343 gcc_assert (INTEGRAL_TYPE_P (gnu_range_type)
8344 || SCALAR_FLOAT_TYPE_P (gnu_range_type));
8346 /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
8347 we can't do anything since we might be truncating the bounds. No
8348 check is needed in this case. */
8349 if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
8350 && (TYPE_PRECISION (gnu_compare_type)
8351 < TYPE_PRECISION (get_base_type (gnu_range_type))))
8352 return gnu_expr;
8354 /* Checked expressions must be evaluated only once. */
8355 gnu_expr = gnat_protect_expr (gnu_expr);
8357 /* Note that the form of the check is
8358 (not (expr >= lo)) or (not (expr <= hi))
8359 the reason for this slightly convoluted form is that NaNs
8360 are not considered to be in range in the float case. */
8361 return emit_check
8362 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8363 invert_truthvalue
8364 (build_binary_op (GE_EXPR, boolean_type_node,
8365 convert (gnu_compare_type, gnu_expr),
8366 convert (gnu_compare_type,
8367 TYPE_MIN_VALUE
8368 (gnu_range_type)))),
8369 invert_truthvalue
8370 (build_binary_op (LE_EXPR, boolean_type_node,
8371 convert (gnu_compare_type, gnu_expr),
8372 convert (gnu_compare_type,
8373 TYPE_MAX_VALUE
8374 (gnu_range_type))))),
8375 gnu_expr, CE_Range_Check_Failed, gnat_node);
8378 /* Emit code for an index check. GNU_ARRAY_OBJECT is the array object which
8379 we are about to index, GNU_EXPR is the index expression to be checked,
8380 GNU_LOW and GNU_HIGH are the lower and upper bounds against which GNU_EXPR
8381 has to be checked. Note that for index checking we cannot simply use the
8382 emit_range_check function (although very similar code needs to be generated
8383 in both cases) since for index checking the array type against which we are
8384 checking the indices may be unconstrained and consequently we need to get
8385 the actual index bounds from the array object itself (GNU_ARRAY_OBJECT).
8386 The place where we need to do that is in subprograms having unconstrained
8387 array formal parameters. GNAT_NODE is the GNAT node conveying the source
8388 location for which the error should be signaled. */
8390 static tree
8391 emit_index_check (tree gnu_array_object, tree gnu_expr, tree gnu_low,
8392 tree gnu_high, Node_Id gnat_node)
8394 tree gnu_expr_check;
8396 /* Checked expressions must be evaluated only once. */
8397 gnu_expr = gnat_protect_expr (gnu_expr);
8399 /* Must do this computation in the base type in case the expression's
8400 type is an unsigned subtypes. */
8401 gnu_expr_check = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
8403 /* If GNU_LOW or GNU_HIGH are a PLACEHOLDER_EXPR, qualify them by
8404 the object we are handling. */
8405 gnu_low = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_low, gnu_array_object);
8406 gnu_high = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_high, gnu_array_object);
8408 return emit_check
8409 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8410 build_binary_op (LT_EXPR, boolean_type_node,
8411 gnu_expr_check,
8412 convert (TREE_TYPE (gnu_expr_check),
8413 gnu_low)),
8414 build_binary_op (GT_EXPR, boolean_type_node,
8415 gnu_expr_check,
8416 convert (TREE_TYPE (gnu_expr_check),
8417 gnu_high))),
8418 gnu_expr, CE_Index_Check_Failed, gnat_node);
8421 /* GNU_COND contains the condition corresponding to an access, discriminant or
8422 range check of value GNU_EXPR. Build a COND_EXPR that returns GNU_EXPR if
8423 GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
8424 REASON is the code that says why the exception was raised. GNAT_NODE is
8425 the GNAT node conveying the source location for which the error should be
8426 signaled. */
8428 static tree
8429 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
8431 tree gnu_call
8432 = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
8433 tree gnu_result
8434 = fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
8435 build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
8436 convert (TREE_TYPE (gnu_expr), integer_zero_node)),
8437 gnu_expr);
8439 /* GNU_RESULT has side effects if and only if GNU_EXPR has:
8440 we don't need to evaluate it just for the check. */
8441 TREE_SIDE_EFFECTS (gnu_result) = TREE_SIDE_EFFECTS (gnu_expr);
8443 return gnu_result;
8446 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
8447 checks if OVERFLOW_P is true and range checks if RANGE_P is true.
8448 GNAT_TYPE is known to be an integral type. If TRUNCATE_P true, do a
8449 float to integer conversion with truncation; otherwise round.
8450 GNAT_NODE is the GNAT node conveying the source location for which the
8451 error should be signaled. */
8453 static tree
8454 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflowp,
8455 bool rangep, bool truncatep, Node_Id gnat_node)
8457 tree gnu_type = get_unpadded_type (gnat_type);
8458 tree gnu_in_type = TREE_TYPE (gnu_expr);
8459 tree gnu_in_basetype = get_base_type (gnu_in_type);
8460 tree gnu_base_type = get_base_type (gnu_type);
8461 tree gnu_result = gnu_expr;
8463 /* If we are not doing any checks, the output is an integral type and the
8464 input is not a floating-point type, just do the conversion. This is
8465 required for packed array types and is simpler in all cases anyway. */
8466 if (!rangep
8467 && !overflowp
8468 && INTEGRAL_TYPE_P (gnu_base_type)
8469 && !FLOAT_TYPE_P (gnu_in_type))
8470 return convert (gnu_type, gnu_expr);
8472 /* First convert the expression to its base type. This
8473 will never generate code, but makes the tests below much simpler.
8474 But don't do this if converting from an integer type to an unconstrained
8475 array type since then we need to get the bounds from the original
8476 (unpacked) type. */
8477 if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
8478 gnu_result = convert (gnu_in_basetype, gnu_result);
8480 /* If overflow checks are requested, we need to be sure the result will
8481 fit in the output base type. But don't do this if the input
8482 is integer and the output floating-point. */
8483 if (overflowp
8484 && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_basetype)))
8486 /* Ensure GNU_EXPR only gets evaluated once. */
8487 tree gnu_input = gnat_protect_expr (gnu_result);
8488 tree gnu_cond = boolean_false_node;
8489 tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_basetype);
8490 tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_basetype);
8491 tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
8492 tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
8494 /* Convert the lower bounds to signed types, so we're sure we're
8495 comparing them properly. Likewise, convert the upper bounds
8496 to unsigned types. */
8497 if (INTEGRAL_TYPE_P (gnu_in_basetype) && TYPE_UNSIGNED (gnu_in_basetype))
8498 gnu_in_lb = convert (gnat_signed_type (gnu_in_basetype), gnu_in_lb);
8500 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8501 && !TYPE_UNSIGNED (gnu_in_basetype))
8502 gnu_in_ub = convert (gnat_unsigned_type (gnu_in_basetype), gnu_in_ub);
8504 if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
8505 gnu_out_lb = convert (gnat_signed_type (gnu_base_type), gnu_out_lb);
8507 if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
8508 gnu_out_ub = convert (gnat_unsigned_type (gnu_base_type), gnu_out_ub);
8510 /* Check each bound separately and only if the result bound
8511 is tighter than the bound on the input type. Note that all the
8512 types are base types, so the bounds must be constant. Also,
8513 the comparison is done in the base type of the input, which
8514 always has the proper signedness. First check for input
8515 integer (which means output integer), output float (which means
8516 both float), or mixed, in which case we always compare.
8517 Note that we have to do the comparison which would *fail* in the
8518 case of an error since if it's an FP comparison and one of the
8519 values is a NaN or Inf, the comparison will fail. */
8520 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8521 ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
8522 : (FLOAT_TYPE_P (gnu_base_type)
8523 ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_in_lb),
8524 TREE_REAL_CST (gnu_out_lb))
8525 : 1))
8526 gnu_cond
8527 = invert_truthvalue
8528 (build_binary_op (GE_EXPR, boolean_type_node,
8529 gnu_input, convert (gnu_in_basetype,
8530 gnu_out_lb)));
8532 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8533 ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
8534 : (FLOAT_TYPE_P (gnu_base_type)
8535 ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_out_ub),
8536 TREE_REAL_CST (gnu_in_lb))
8537 : 1))
8538 gnu_cond
8539 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
8540 invert_truthvalue
8541 (build_binary_op (LE_EXPR, boolean_type_node,
8542 gnu_input,
8543 convert (gnu_in_basetype,
8544 gnu_out_ub))));
8546 if (!integer_zerop (gnu_cond))
8547 gnu_result = emit_check (gnu_cond, gnu_input,
8548 CE_Overflow_Check_Failed, gnat_node);
8551 /* Now convert to the result base type. If this is a non-truncating
8552 float-to-integer conversion, round. */
8553 if (INTEGRAL_TYPE_P (gnu_base_type)
8554 && FLOAT_TYPE_P (gnu_in_basetype)
8555 && !truncatep)
8557 REAL_VALUE_TYPE half_minus_pred_half, pred_half;
8558 tree gnu_conv, gnu_zero, gnu_comp, calc_type;
8559 tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
8560 const struct real_format *fmt;
8562 /* The following calculations depend on proper rounding to even
8563 of each arithmetic operation. In order to prevent excess
8564 precision from spoiling this property, use the widest hardware
8565 floating-point type if FP_ARITH_MAY_WIDEN is true. */
8566 calc_type
8567 = fp_arith_may_widen ? longest_float_type_node : gnu_in_basetype;
8569 /* Compute the exact value calc_type'Pred (0.5) at compile time. */
8570 fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
8571 real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
8572 REAL_ARITHMETIC (pred_half, MINUS_EXPR, dconsthalf,
8573 half_minus_pred_half);
8574 gnu_pred_half = build_real (calc_type, pred_half);
8576 /* If the input is strictly negative, subtract this value
8577 and otherwise add it from the input. For 0.5, the result
8578 is exactly between 1.0 and the machine number preceding 1.0
8579 (for calc_type). Since the last bit of 1.0 is even, this 0.5
8580 will round to 1.0, while all other number with an absolute
8581 value less than 0.5 round to 0.0. For larger numbers exactly
8582 halfway between integers, rounding will always be correct as
8583 the true mathematical result will be closer to the higher
8584 integer compared to the lower one. So, this constant works
8585 for all floating-point numbers.
8587 The reason to use the same constant with subtract/add instead
8588 of a positive and negative constant is to allow the comparison
8589 to be scheduled in parallel with retrieval of the constant and
8590 conversion of the input to the calc_type (if necessary). */
8592 gnu_zero = convert (gnu_in_basetype, integer_zero_node);
8593 gnu_result = gnat_protect_expr (gnu_result);
8594 gnu_conv = convert (calc_type, gnu_result);
8595 gnu_comp
8596 = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
8597 gnu_add_pred_half
8598 = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8599 gnu_subtract_pred_half
8600 = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8601 gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
8602 gnu_add_pred_half, gnu_subtract_pred_half);
8605 if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8606 && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
8607 && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
8608 gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
8609 else
8610 gnu_result = convert (gnu_base_type, gnu_result);
8612 /* Finally, do the range check if requested. Note that if the result type
8613 is a modular type, the range check is actually an overflow check. */
8614 if (rangep
8615 || (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8616 && TYPE_MODULAR_P (gnu_base_type) && overflowp))
8617 gnu_result = emit_range_check (gnu_result, gnat_type, gnat_node);
8619 return convert (gnu_type, gnu_result);
8622 /* Return true if GNU_EXPR can be directly addressed. This is the case
8623 unless it is an expression involving computation or if it involves a
8624 reference to a bitfield or to an object not sufficiently aligned for
8625 its type. If GNU_TYPE is non-null, return true only if GNU_EXPR can
8626 be directly addressed as an object of this type.
8628 *** Notes on addressability issues in the Ada compiler ***
8630 This predicate is necessary in order to bridge the gap between Gigi
8631 and the middle-end about addressability of GENERIC trees. A tree
8632 is said to be addressable if it can be directly addressed, i.e. if
8633 its address can be taken, is a multiple of the type's alignment on
8634 strict-alignment architectures and returns the first storage unit
8635 assigned to the object represented by the tree.
8637 In the C family of languages, everything is in practice addressable
8638 at the language level, except for bit-fields. This means that these
8639 compilers will take the address of any tree that doesn't represent
8640 a bit-field reference and expect the result to be the first storage
8641 unit assigned to the object. Even in cases where this will result
8642 in unaligned accesses at run time, nothing is supposed to be done
8643 and the program is considered as erroneous instead (see PR c/18287).
8645 The implicit assumptions made in the middle-end are in keeping with
8646 the C viewpoint described above:
8647 - the address of a bit-field reference is supposed to be never
8648 taken; the compiler (generally) will stop on such a construct,
8649 - any other tree is addressable if it is formally addressable,
8650 i.e. if it is formally allowed to be the operand of ADDR_EXPR.
8652 In Ada, the viewpoint is the opposite one: nothing is addressable
8653 at the language level unless explicitly declared so. This means
8654 that the compiler will both make sure that the trees representing
8655 references to addressable ("aliased" in Ada parlance) objects are
8656 addressable and make no real attempts at ensuring that the trees
8657 representing references to non-addressable objects are addressable.
8659 In the first case, Ada is effectively equivalent to C and handing
8660 down the direct result of applying ADDR_EXPR to these trees to the
8661 middle-end works flawlessly. In the second case, Ada cannot afford
8662 to consider the program as erroneous if the address of trees that
8663 are not addressable is requested for technical reasons, unlike C;
8664 as a consequence, the Ada compiler must arrange for either making
8665 sure that this address is not requested in the middle-end or for
8666 compensating by inserting temporaries if it is requested in Gigi.
8668 The first goal can be achieved because the middle-end should not
8669 request the address of non-addressable trees on its own; the only
8670 exception is for the invocation of low-level block operations like
8671 memcpy, for which the addressability requirements are lower since
8672 the type's alignment can be disregarded. In practice, this means
8673 that Gigi must make sure that such operations cannot be applied to
8674 non-BLKmode bit-fields.
8676 The second goal is achieved by means of the addressable_p predicate,
8677 which computes whether a temporary must be inserted by Gigi when the
8678 address of a tree is requested; if so, the address of the temporary
8679 will be used in lieu of that of the original tree and some glue code
8680 generated to connect everything together. */
8682 static bool
8683 addressable_p (tree gnu_expr, tree gnu_type)
8685 /* For an integral type, the size of the actual type of the object may not
8686 be greater than that of the expected type, otherwise an indirect access
8687 in the latter type wouldn't correctly set all the bits of the object. */
8688 if (gnu_type
8689 && INTEGRAL_TYPE_P (gnu_type)
8690 && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
8691 return false;
8693 /* The size of the actual type of the object may not be smaller than that
8694 of the expected type, otherwise an indirect access in the latter type
8695 would be larger than the object. But only record types need to be
8696 considered in practice for this case. */
8697 if (gnu_type
8698 && TREE_CODE (gnu_type) == RECORD_TYPE
8699 && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
8700 return false;
8702 switch (TREE_CODE (gnu_expr))
8704 case VAR_DECL:
8705 case PARM_DECL:
8706 case FUNCTION_DECL:
8707 case RESULT_DECL:
8708 /* All DECLs are addressable: if they are in a register, we can force
8709 them to memory. */
8710 return true;
8712 case UNCONSTRAINED_ARRAY_REF:
8713 case INDIRECT_REF:
8714 /* Taking the address of a dereference yields the original pointer. */
8715 return true;
8717 case STRING_CST:
8718 case INTEGER_CST:
8719 /* Taking the address yields a pointer to the constant pool. */
8720 return true;
8722 case CONSTRUCTOR:
8723 /* Taking the address of a static constructor yields a pointer to the
8724 tree constant pool. */
8725 return TREE_STATIC (gnu_expr) ? true : false;
8727 case NULL_EXPR:
8728 case SAVE_EXPR:
8729 case CALL_EXPR:
8730 case PLUS_EXPR:
8731 case MINUS_EXPR:
8732 case BIT_IOR_EXPR:
8733 case BIT_XOR_EXPR:
8734 case BIT_AND_EXPR:
8735 case BIT_NOT_EXPR:
8736 /* All rvalues are deemed addressable since taking their address will
8737 force a temporary to be created by the middle-end. */
8738 return true;
8740 case COMPOUND_EXPR:
8741 /* The address of a compound expression is that of its 2nd operand. */
8742 return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
8744 case COND_EXPR:
8745 /* We accept &COND_EXPR as soon as both operands are addressable and
8746 expect the outcome to be the address of the selected operand. */
8747 return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
8748 && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
8750 case COMPONENT_REF:
8751 return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
8752 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
8753 the field is sufficiently aligned, in case it is subject
8754 to a pragma Component_Alignment. But we don't need to
8755 check the alignment of the containing record, as it is
8756 guaranteed to be not smaller than that of its most
8757 aligned field that is not a bit-field. */
8758 && (!STRICT_ALIGNMENT
8759 || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
8760 >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
8761 /* The field of a padding record is always addressable. */
8762 || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
8763 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8765 case ARRAY_REF: case ARRAY_RANGE_REF:
8766 case REALPART_EXPR: case IMAGPART_EXPR:
8767 case NOP_EXPR:
8768 return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
8770 case CONVERT_EXPR:
8771 return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
8772 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8774 case VIEW_CONVERT_EXPR:
8776 /* This is addressable if we can avoid a copy. */
8777 tree type = TREE_TYPE (gnu_expr);
8778 tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
8779 return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
8780 && (!STRICT_ALIGNMENT
8781 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8782 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
8783 || ((TYPE_MODE (type) == BLKmode
8784 || TYPE_MODE (inner_type) == BLKmode)
8785 && (!STRICT_ALIGNMENT
8786 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8787 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
8788 || TYPE_ALIGN_OK (type)
8789 || TYPE_ALIGN_OK (inner_type))))
8790 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8793 default:
8794 return false;
8798 /* Do the processing for the declaration of a GNAT_ENTITY, a type. If
8799 a separate Freeze node exists, delay the bulk of the processing. Otherwise
8800 make a GCC type for GNAT_ENTITY and set up the correspondence. */
8802 void
8803 process_type (Entity_Id gnat_entity)
8805 tree gnu_old
8806 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
8807 tree gnu_new;
8809 /* If we are to delay elaboration of this type, just do any
8810 elaborations needed for expressions within the declaration and
8811 make a dummy type entry for this node and its Full_View (if
8812 any) in case something points to it. Don't do this if it
8813 has already been done (the only way that can happen is if
8814 the private completion is also delayed). */
8815 if (Present (Freeze_Node (gnat_entity))
8816 || (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
8817 && Present (Full_View (gnat_entity))
8818 && Present (Freeze_Node (Full_View (gnat_entity)))
8819 && !present_gnu_tree (Full_View (gnat_entity))))
8821 elaborate_entity (gnat_entity);
8823 if (!gnu_old)
8825 tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
8826 save_gnu_tree (gnat_entity, gnu_decl, false);
8827 if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
8828 && Present (Full_View (gnat_entity)))
8830 if (Has_Completion_In_Body (gnat_entity))
8831 DECL_TAFT_TYPE_P (gnu_decl) = 1;
8832 save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
8836 return;
8839 /* If we saved away a dummy type for this node it means that this
8840 made the type that corresponds to the full type of an incomplete
8841 type. Clear that type for now and then update the type in the
8842 pointers. */
8843 if (gnu_old)
8845 gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
8846 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
8848 save_gnu_tree (gnat_entity, NULL_TREE, false);
8851 /* Now fully elaborate the type. */
8852 gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 1);
8853 gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
8855 /* If we have an old type and we've made pointers to this type, update those
8856 pointers. If this is a Taft amendment type in the main unit, we need to
8857 mark the type as used since other units referencing it don't see the full
8858 declaration and, therefore, cannot mark it as used themselves. */
8859 if (gnu_old)
8861 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
8862 TREE_TYPE (gnu_new));
8863 if (DECL_TAFT_TYPE_P (gnu_old))
8864 used_types_insert (TREE_TYPE (gnu_new));
8867 /* If this is a record type corresponding to a task or protected type
8868 that is a completion of an incomplete type, perform a similar update
8869 on the type. ??? Including protected types here is a guess. */
8870 if (IN (Ekind (gnat_entity), Record_Kind)
8871 && Is_Concurrent_Record_Type (gnat_entity)
8872 && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
8874 tree gnu_task_old
8875 = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
8877 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
8878 NULL_TREE, false);
8879 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
8880 gnu_new, false);
8882 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
8883 TREE_TYPE (gnu_new));
8887 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
8888 front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
8889 GCC type of the corresponding record type. Return the CONSTRUCTOR. */
8891 static tree
8892 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
8894 tree gnu_list = NULL_TREE, gnu_result;
8896 /* We test for GNU_FIELD being empty in the case where a variant
8897 was the last thing since we don't take things off GNAT_ASSOC in
8898 that case. We check GNAT_ASSOC in case we have a variant, but it
8899 has no fields. */
8901 for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
8903 Node_Id gnat_field = First (Choices (gnat_assoc));
8904 tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
8905 tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
8907 /* The expander is supposed to put a single component selector name
8908 in every record component association. */
8909 gcc_assert (No (Next (gnat_field)));
8911 /* Ignore fields that have Corresponding_Discriminants since we'll
8912 be setting that field in the parent. */
8913 if (Present (Corresponding_Discriminant (Entity (gnat_field)))
8914 && Is_Tagged_Type (Scope (Entity (gnat_field))))
8915 continue;
8917 /* Also ignore discriminants of Unchecked_Unions. */
8918 if (Is_Unchecked_Union (gnat_entity)
8919 && Ekind (Entity (gnat_field)) == E_Discriminant)
8920 continue;
8922 /* Before assigning a value in an aggregate make sure range checks
8923 are done if required. Then convert to the type of the field. */
8924 if (Do_Range_Check (Expression (gnat_assoc)))
8925 gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field), Empty);
8927 gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
8929 /* Add the field and expression to the list. */
8930 gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
8933 gnu_result = extract_values (gnu_list, gnu_type);
8935 #ifdef ENABLE_CHECKING
8936 /* Verify that every entry in GNU_LIST was used. */
8937 for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
8938 gcc_assert (TREE_ADDRESSABLE (gnu_list));
8939 #endif
8941 return gnu_result;
8944 /* Build a possibly nested constructor for array aggregates. GNAT_EXPR is
8945 the first element of an array aggregate. It may itself be an aggregate.
8946 GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate.
8947 GNAT_COMPONENT_TYPE is the type of the array component; it is needed
8948 for range checking. */
8950 static tree
8951 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
8952 Entity_Id gnat_component_type)
8954 tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
8955 tree gnu_expr;
8956 vec<constructor_elt, va_gc> *gnu_expr_vec = NULL;
8958 for ( ; Present (gnat_expr); gnat_expr = Next (gnat_expr))
8960 /* If the expression is itself an array aggregate then first build the
8961 innermost constructor if it is part of our array (multi-dimensional
8962 case). */
8963 if (Nkind (gnat_expr) == N_Aggregate
8964 && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
8965 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
8966 gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
8967 TREE_TYPE (gnu_array_type),
8968 gnat_component_type);
8969 else
8971 gnu_expr = gnat_to_gnu (gnat_expr);
8973 /* Before assigning the element to the array, make sure it is
8974 in range. */
8975 if (Do_Range_Check (gnat_expr))
8976 gnu_expr = emit_range_check (gnu_expr, gnat_component_type, Empty);
8979 CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
8980 convert (TREE_TYPE (gnu_array_type), gnu_expr));
8982 gnu_index = int_const_binop (PLUS_EXPR, gnu_index,
8983 convert (TREE_TYPE (gnu_index),
8984 integer_one_node));
8987 return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
8990 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
8991 some of which are from RECORD_TYPE. Return a CONSTRUCTOR consisting
8992 of the associations that are from RECORD_TYPE. If we see an internal
8993 record, make a recursive call to fill it in as well. */
8995 static tree
8996 extract_values (tree values, tree record_type)
8998 tree field, tem;
8999 vec<constructor_elt, va_gc> *v = NULL;
9001 for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
9003 tree value = 0;
9005 /* _Parent is an internal field, but may have values in the aggregate,
9006 so check for values first. */
9007 if ((tem = purpose_member (field, values)))
9009 value = TREE_VALUE (tem);
9010 TREE_ADDRESSABLE (tem) = 1;
9013 else if (DECL_INTERNAL_P (field))
9015 value = extract_values (values, TREE_TYPE (field));
9016 if (TREE_CODE (value) == CONSTRUCTOR
9017 && vec_safe_is_empty (CONSTRUCTOR_ELTS (value)))
9018 value = 0;
9020 else
9021 /* If we have a record subtype, the names will match, but not the
9022 actual FIELD_DECLs. */
9023 for (tem = values; tem; tem = TREE_CHAIN (tem))
9024 if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
9026 value = convert (TREE_TYPE (field), TREE_VALUE (tem));
9027 TREE_ADDRESSABLE (tem) = 1;
9030 if (!value)
9031 continue;
9033 CONSTRUCTOR_APPEND_ELT (v, field, value);
9036 return gnat_build_constructor (record_type, v);
9039 /* Process a N_Validate_Unchecked_Conversion node. */
9041 static void
9042 validate_unchecked_conversion (Node_Id gnat_node)
9044 tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
9045 tree gnu_target_type = gnat_to_gnu_type (Target_Type (gnat_node));
9047 /* If the target is a pointer type, see if we are either converting from a
9048 non-pointer or from a pointer to a type with a different alias set and
9049 warn if so, unless the pointer has been marked to alias everything. */
9050 if (POINTER_TYPE_P (gnu_target_type)
9051 && !TYPE_REF_CAN_ALIAS_ALL (gnu_target_type))
9053 tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
9054 ? TREE_TYPE (gnu_source_type)
9055 : NULL_TREE;
9056 tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
9057 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9059 if (target_alias_set != 0
9060 && (!POINTER_TYPE_P (gnu_source_type)
9061 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9062 target_alias_set)))
9064 post_error_ne ("?possible aliasing problem for type&",
9065 gnat_node, Target_Type (gnat_node));
9066 post_error ("\\?use -fno-strict-aliasing switch for references",
9067 gnat_node);
9068 post_error_ne ("\\?or use `pragma No_Strict_Aliasing (&);`",
9069 gnat_node, Target_Type (gnat_node));
9073 /* Likewise if the target is a fat pointer type, but we have no mechanism to
9074 mitigate the problem in this case, so we unconditionally warn. */
9075 else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
9077 tree gnu_source_desig_type
9078 = TYPE_IS_FAT_POINTER_P (gnu_source_type)
9079 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
9080 : NULL_TREE;
9081 tree gnu_target_desig_type
9082 = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
9083 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9085 if (target_alias_set != 0
9086 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
9087 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9088 target_alias_set)))
9090 post_error_ne ("?possible aliasing problem for type&",
9091 gnat_node, Target_Type (gnat_node));
9092 post_error ("\\?use -fno-strict-aliasing switch for references",
9093 gnat_node);
9098 /* EXP is to be treated as an array or record. Handle the cases when it is
9099 an access object and perform the required dereferences. */
9101 static tree
9102 maybe_implicit_deref (tree exp)
9104 /* If the type is a pointer, dereference it. */
9105 if (POINTER_TYPE_P (TREE_TYPE (exp))
9106 || TYPE_IS_FAT_POINTER_P (TREE_TYPE (exp)))
9107 exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
9109 /* If we got a padded type, remove it too. */
9110 if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
9111 exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
9113 return exp;
9116 /* Convert SLOC into LOCUS. Return true if SLOC corresponds to a source code
9117 location and false if it doesn't. In the former case, set the Gigi global
9118 variable REF_FILENAME to the simple debug file name as given by sinput.
9119 If clear_column is true, set column information to 0. */
9121 static bool
9122 Sloc_to_locus1 (Source_Ptr Sloc, location_t *locus, bool clear_column)
9124 if (Sloc == No_Location)
9125 return false;
9127 if (Sloc <= Standard_Location)
9129 *locus = BUILTINS_LOCATION;
9130 return false;
9132 else
9134 Source_File_Index file = Get_Source_File_Index (Sloc);
9135 Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
9136 Column_Number column = (clear_column ? 0 : Get_Column_Number (Sloc));
9137 struct line_map *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
9139 /* We can have zero if pragma Source_Reference is in effect. */
9140 if (line < 1)
9141 line = 1;
9143 /* Translate the location. */
9144 *locus = linemap_position_for_line_and_column (map, line, column);
9147 ref_filename
9148 = IDENTIFIER_POINTER
9149 (get_identifier
9150 (Get_Name_String (Debug_Source_Name (Get_Source_File_Index (Sloc)))));;
9152 return true;
9155 /* Similar to the above, not clearing the column information. */
9157 bool
9158 Sloc_to_locus (Source_Ptr Sloc, location_t *locus)
9160 return Sloc_to_locus1 (Sloc, locus, false);
9163 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
9164 don't do anything if it doesn't correspond to a source location. */
9166 static void
9167 set_expr_location_from_node1 (tree node, Node_Id gnat_node, bool clear_column)
9169 location_t locus;
9171 if (!Sloc_to_locus1 (Sloc (gnat_node), &locus, clear_column))
9172 return;
9174 SET_EXPR_LOCATION (node, locus);
9177 /* Similar to the above, not clearing the column information. */
9179 static void
9180 set_expr_location_from_node (tree node, Node_Id gnat_node)
9182 set_expr_location_from_node1 (node, gnat_node, false);
9185 /* More elaborate version of set_expr_location_from_node to be used in more
9186 general contexts, for example the result of the translation of a generic
9187 GNAT node. */
9189 static void
9190 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
9192 /* Set the location information on the node if it is a real expression.
9193 References can be reused for multiple GNAT nodes and they would get
9194 the location information of their last use. Also make sure not to
9195 overwrite an existing location as it is probably more precise. */
9197 switch (TREE_CODE (node))
9199 CASE_CONVERT:
9200 case NON_LVALUE_EXPR:
9201 case SAVE_EXPR:
9202 break;
9204 case COMPOUND_EXPR:
9205 if (EXPR_P (TREE_OPERAND (node, 1)))
9206 set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
9208 /* ... fall through ... */
9210 default:
9211 if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
9213 set_expr_location_from_node (node, gnat_node);
9214 set_end_locus_from_node (node, gnat_node);
9216 break;
9220 /* Return a colon-separated list of encodings contained in encoded Ada
9221 name. */
9223 static const char *
9224 extract_encoding (const char *name)
9226 char *encoding = (char *) ggc_alloc_atomic (strlen (name));
9227 get_encoding (name, encoding);
9228 return encoding;
9231 /* Extract the Ada name from an encoded name. */
9233 static const char *
9234 decode_name (const char *name)
9236 char *decoded = (char *) ggc_alloc_atomic (strlen (name) * 2 + 60);
9237 __gnat_decode (name, decoded, 0);
9238 return decoded;
9241 /* Post an error message. MSG is the error message, properly annotated.
9242 NODE is the node at which to post the error and the node to use for the
9243 '&' substitution. */
9245 void
9246 post_error (const char *msg, Node_Id node)
9248 String_Template temp;
9249 String_Pointer sp;
9251 if (No (node))
9252 return;
9254 temp.Low_Bound = 1;
9255 temp.High_Bound = strlen (msg);
9256 sp.Bounds = &temp;
9257 sp.Array = msg;
9258 Error_Msg_N (sp, node);
9261 /* Similar to post_error, but NODE is the node at which to post the error and
9262 ENT is the node to use for the '&' substitution. */
9264 void
9265 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
9267 String_Template temp;
9268 String_Pointer sp;
9270 if (No (node))
9271 return;
9273 temp.Low_Bound = 1;
9274 temp.High_Bound = strlen (msg);
9275 sp.Bounds = &temp;
9276 sp.Array = msg;
9277 Error_Msg_NE (sp, node, ent);
9280 /* Similar to post_error_ne, but NUM is the number to use for the '^'. */
9282 void
9283 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
9285 Error_Msg_Uint_1 = UI_From_Int (num);
9286 post_error_ne (msg, node, ent);
9289 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
9290 location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
9291 most sense. Return true if a sensible assignment was performed. */
9293 static bool
9294 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
9296 Node_Id gnat_end_label = Empty;
9297 location_t end_locus;
9299 /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
9300 end_locus when there is one. We consider only GNAT nodes with a possible
9301 End_Label attached. If the End_Label actually was unassigned, fallback
9302 on the original node. We'd better assign an explicit sloc associated with
9303 the outer construct in any case. */
9305 switch (Nkind (gnat_node))
9307 case N_Package_Body:
9308 case N_Subprogram_Body:
9309 case N_Block_Statement:
9310 gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
9311 break;
9313 case N_Package_Declaration:
9314 gnat_end_label = End_Label (Specification (gnat_node));
9315 break;
9317 default:
9318 return false;
9321 gnat_node = Present (gnat_end_label) ? gnat_end_label : gnat_node;
9323 /* Some expanded subprograms have neither an End_Label nor a Sloc
9324 attached. Notify that to callers. For a block statement with no
9325 End_Label, clear column information, so that the tree for a
9326 transient block does not receive the sloc of a source condition. */
9328 if (!Sloc_to_locus1 (Sloc (gnat_node), &end_locus,
9329 No (gnat_end_label) &&
9330 (Nkind (gnat_node) == N_Block_Statement)))
9331 return false;
9333 switch (TREE_CODE (gnu_node))
9335 case BIND_EXPR:
9336 BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
9337 return true;
9339 case FUNCTION_DECL:
9340 DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
9341 return true;
9343 default:
9344 return false;
9348 /* Similar to post_error_ne, but T is a GCC tree representing the number to
9349 write. If T represents a constant, the text inside curly brackets in
9350 MSG will be output (presumably including a '^'). Otherwise it will not
9351 be output and the text inside square brackets will be output instead. */
9353 void
9354 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
9356 char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
9357 char start_yes, end_yes, start_no, end_no;
9358 const char *p;
9359 char *q;
9361 if (TREE_CODE (t) == INTEGER_CST)
9363 Error_Msg_Uint_1 = UI_From_gnu (t);
9364 start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
9366 else
9367 start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
9369 for (p = msg, q = new_msg; *p; p++)
9371 if (*p == start_yes)
9372 for (p++; *p != end_yes; p++)
9373 *q++ = *p;
9374 else if (*p == start_no)
9375 for (p++; *p != end_no; p++)
9377 else
9378 *q++ = *p;
9381 *q = 0;
9383 post_error_ne (new_msg, node, ent);
9386 /* Similar to post_error_ne_tree, but NUM is a second integer to write. */
9388 void
9389 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
9390 int num)
9392 Error_Msg_Uint_2 = UI_From_Int (num);
9393 post_error_ne_tree (msg, node, ent, t);
9396 /* Initialize the table that maps GNAT codes to GCC codes for simple
9397 binary and unary operations. */
9399 static void
9400 init_code_table (void)
9402 gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
9403 gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
9405 gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
9406 gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
9407 gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
9408 gnu_codes[N_Op_Eq] = EQ_EXPR;
9409 gnu_codes[N_Op_Ne] = NE_EXPR;
9410 gnu_codes[N_Op_Lt] = LT_EXPR;
9411 gnu_codes[N_Op_Le] = LE_EXPR;
9412 gnu_codes[N_Op_Gt] = GT_EXPR;
9413 gnu_codes[N_Op_Ge] = GE_EXPR;
9414 gnu_codes[N_Op_Add] = PLUS_EXPR;
9415 gnu_codes[N_Op_Subtract] = MINUS_EXPR;
9416 gnu_codes[N_Op_Multiply] = MULT_EXPR;
9417 gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
9418 gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
9419 gnu_codes[N_Op_Minus] = NEGATE_EXPR;
9420 gnu_codes[N_Op_Abs] = ABS_EXPR;
9421 gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
9422 gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
9423 gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
9424 gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
9425 gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
9426 gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
9429 /* Return a label to branch to for the exception type in KIND or NULL_TREE
9430 if none. */
9432 tree
9433 get_exception_label (char kind)
9435 if (kind == N_Raise_Constraint_Error)
9436 return gnu_constraint_error_label_stack->last ();
9437 else if (kind == N_Raise_Storage_Error)
9438 return gnu_storage_error_label_stack->last ();
9439 else if (kind == N_Raise_Program_Error)
9440 return gnu_program_error_label_stack->last ();
9441 else
9442 return NULL_TREE;
9445 /* Return the decl for the current elaboration procedure. */
9447 tree
9448 get_elaboration_procedure (void)
9450 return gnu_elab_proc_stack->last ();
9453 #include "gt-ada-trans.h"