[Ada] Get rid of secondary stack for controlled components
[official-gcc.git] / gcc / ada / gcc-interface / trans.cc
blobb8a0d5d5d30bb8ea2ed8491610e3a2b8d9c8f973
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * T R A N S *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2022, 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 "target.h"
30 #include "function.h"
31 #include "bitmap.h"
32 #include "tree.h"
33 #include "gimple-expr.h"
34 #include "stringpool.h"
35 #include "cgraph.h"
36 #include "predict.h"
37 #include "diagnostic.h"
38 #include "alias.h"
39 #include "fold-const.h"
40 #include "stor-layout.h"
41 #include "stmt.h"
42 #include "varasm.h"
43 #include "output.h"
44 #include "debug.h"
45 #include "libfuncs.h" /* For set_stack_check_libfunc. */
46 #include "tree-iterator.h"
47 #include "gimplify.h"
48 #include "opts.h"
49 #include "common/common-target.h"
50 #include "gomp-constants.h"
51 #include "stringpool.h"
52 #include "attribs.h"
53 #include "tree-nested.h"
55 #include "ada.h"
56 #include "adadecode.h"
57 #include "types.h"
58 #include "atree.h"
59 #include "namet.h"
60 #include "nlists.h"
61 #include "snames.h"
62 #include "stringt.h"
63 #include "uintp.h"
64 #include "urealp.h"
65 #include "fe.h"
66 #include "sinfo.h"
67 #include "einfo.h"
68 #include "gadaint.h"
69 #include "ada-tree.h"
70 #include "gigi.h"
72 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
73 for fear of running out of stack space. If we need more, we use xmalloc
74 instead. */
75 #define ALLOCA_THRESHOLD 1000
77 /* Pointers to front-end tables accessed through macros. */
78 Node_Header *Node_Offsets_Ptr;
79 any_slot *Slots_Ptr;
80 Node_Id *Next_Node_Ptr;
81 Node_Id *Prev_Node_Ptr;
82 struct Elist_Header *Elists_Ptr;
83 struct Elmt_Item *Elmts_Ptr;
84 struct String_Entry *Strings_Ptr;
85 Char_Code *String_Chars_Ptr;
86 struct List_Header *List_Headers_Ptr;
88 /* Highest number in the front-end node table. */
89 int max_gnat_nodes;
91 /* True when gigi is being called on an analyzed but unexpanded
92 tree, and the only purpose of the call is to properly annotate
93 types with representation information. */
94 bool type_annotate_only;
96 /* List of N_Validate_Unchecked_Conversion nodes in the unit. */
97 static vec<Node_Id> gnat_validate_uc_list;
99 /* List of expressions of pragma Compile_Time_{Error|Warning} in the unit. */
100 static vec<Node_Id> gnat_compile_time_expr_list;
102 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
103 of unconstrained array IN parameters to avoid emitting a great deal of
104 redundant instructions to recompute them each time. */
105 struct GTY (()) parm_attr_d {
106 int id; /* GTY doesn't like Entity_Id. */
107 int dim;
108 tree first;
109 tree last;
110 tree length;
113 typedef struct parm_attr_d *parm_attr;
115 /* Structure used to record information for a function. */
116 struct GTY(()) language_function {
117 vec<parm_attr, va_gc> *parm_attr_cache;
118 bitmap named_ret_val;
119 vec<tree, va_gc> *other_ret_val;
120 int gnat_ret;
123 #define f_parm_attr_cache \
124 DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
126 #define f_named_ret_val \
127 DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
129 #define f_other_ret_val \
130 DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
132 #define f_gnat_ret \
133 DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
135 /* A structure used to gather together information about a statement group.
136 We use this to gather related statements, for example the "then" part
137 of a IF. In the case where it represents a lexical scope, we may also
138 have a BLOCK node corresponding to it and/or cleanups. */
140 struct GTY((chain_next ("%h.previous"))) stmt_group {
141 struct stmt_group *previous; /* Previous code group. */
142 tree stmt_list; /* List of statements for this code group. */
143 tree block; /* BLOCK for this code group, if any. */
144 tree cleanups; /* Cleanups for this code group, if any. */
147 static GTY(()) struct stmt_group *current_stmt_group;
149 /* List of unused struct stmt_group nodes. */
150 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
152 /* A structure used to record information on elaboration procedures
153 we've made and need to process.
155 ??? gnat_node should be Node_Id, but gengtype gets confused. */
157 struct GTY((chain_next ("%h.next"))) elab_info {
158 struct elab_info *next; /* Pointer to next in chain. */
159 tree elab_proc; /* Elaboration procedure. */
160 int gnat_node; /* The N_Compilation_Unit. */
163 static GTY(()) struct elab_info *elab_info_list;
165 /* Stack of exception pointer variables. Each entry is the VAR_DECL
166 that stores the address of the raised exception. Nonzero means we
167 are in an exception handler. Not used in the zero-cost case. */
168 static GTY(()) vec<tree, va_gc> *gnu_except_ptr_stack;
170 /* In ZCX case, current exception pointer. Used to re-raise it. */
171 static GTY(()) tree gnu_incoming_exc_ptr;
173 /* Stack for storing the current elaboration procedure decl. */
174 static GTY(()) vec<tree, va_gc> *gnu_elab_proc_stack;
176 /* Stack of labels to be used as a goto target instead of a return in
177 some functions. See processing for N_Subprogram_Body. */
178 static GTY(()) vec<tree, va_gc> *gnu_return_label_stack;
180 /* Stack of variable for the return value of a function with copy-in/copy-out
181 parameters. See processing for N_Subprogram_Body. */
182 static GTY(()) vec<tree, va_gc> *gnu_return_var_stack;
184 /* Structure used to record information for a range check. */
185 struct GTY(()) range_check_info_d {
186 tree low_bound;
187 tree high_bound;
188 tree disp;
189 bool neg_p;
190 tree type;
191 tree invariant_cond;
192 tree inserted_cond;
195 typedef struct range_check_info_d *range_check_info;
197 /* Structure used to record information for a loop. */
198 struct GTY(()) loop_info_d {
199 tree fndecl;
200 tree stmt;
201 tree loop_var;
202 tree low_bound;
203 tree high_bound;
204 tree omp_loop_clauses;
205 tree omp_construct_clauses;
206 enum tree_code omp_code;
207 vec<range_check_info, va_gc> *checks;
208 vec<tree, va_gc> *invariants;
211 typedef struct loop_info_d *loop_info;
213 /* Stack of loop_info structures associated with LOOP_STMT nodes. */
214 static GTY(()) vec<loop_info, va_gc> *gnu_loop_stack;
216 /* The stacks for N_{Push,Pop}_*_Label. */
217 static vec<Entity_Id> gnu_constraint_error_label_stack;
218 static vec<Entity_Id> gnu_storage_error_label_stack;
219 static vec<Entity_Id> gnu_program_error_label_stack;
221 /* Map GNAT tree codes to GCC tree codes for simple expressions. */
222 static enum tree_code gnu_codes[Number_Node_Kinds];
224 static void init_code_table (void);
225 static tree get_elaboration_procedure (void);
226 static void Compilation_Unit_to_gnu (Node_Id);
227 static bool empty_stmt_list_p (tree);
228 static void record_code_position (Node_Id);
229 static void insert_code_for (Node_Id);
230 static void add_cleanup (tree, Node_Id);
231 static void add_stmt_list (List_Id);
232 static tree build_stmt_group (List_Id, bool);
233 static inline bool stmt_group_may_fallthru (void);
234 static enum gimplify_status gnat_gimplify_stmt (tree *);
235 static void elaborate_all_entities (Node_Id);
236 static void process_freeze_entity (Node_Id);
237 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
238 static tree emit_check (tree, tree, int, Node_Id);
239 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
240 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
241 static tree convert_with_check (Entity_Id, tree, bool, bool, Node_Id);
242 static bool addressable_p (tree, tree);
243 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
244 static tree pos_to_constructor (Node_Id, tree);
245 static void validate_unchecked_conversion (Node_Id);
246 static void set_expr_location_from_node (tree, Node_Id, bool = false);
247 static void set_gnu_expr_location_from_node (tree, Node_Id);
248 static bool set_end_locus_from_node (tree, Node_Id);
249 static int lvalue_required_p (Node_Id, tree, bool, bool);
250 static tree build_raise_check (int, enum exception_info_kind);
251 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
252 static bool maybe_make_gnu_thunk (Entity_Id gnat_thunk, tree gnu_thunk);
254 /* This makes gigi's file_info_ptr visible in this translation unit,
255 so that Sloc_to_locus can look it up when deciding whether to map
256 decls to instances. */
258 static struct File_Info_Type *file_map;
260 /* Return the string of the identifier allocated for the file name Id. */
262 static const char*
263 File_Name_to_gnu (Name_Id Id)
265 /* __gnat_to_canonical_file_spec translates file names from pragmas
266 Source_Reference that contain host style syntax not understood by GDB. */
267 const char *name = __gnat_to_canonical_file_spec (Get_Name_String (Id));
269 /* Use the identifier table to make a permanent copy of the file name as
270 the name table gets reallocated after Gigi returns but before all the
271 debugging information is output. */
272 return IDENTIFIER_POINTER (get_identifier (name));
275 /* This is the main program of the back-end. It sets up all the table
276 structures and then generates code. */
278 void
279 gigi (Node_Id gnat_root,
280 int max_gnat_node,
281 int number_name ATTRIBUTE_UNUSED,
282 Node_Header *node_offsets_ptr,
283 any_slot *slots_ptr,
284 Node_Id *next_node_ptr,
285 Node_Id *prev_node_ptr,
286 struct Elist_Header *elists_ptr,
287 struct Elmt_Item *elmts_ptr,
288 struct String_Entry *strings_ptr,
289 Char_Code *string_chars_ptr,
290 struct List_Header *list_headers_ptr,
291 Nat number_file,
292 struct File_Info_Type *file_info_ptr,
293 Entity_Id standard_boolean,
294 Entity_Id standard_integer,
295 Entity_Id standard_character,
296 Entity_Id standard_long_long_float,
297 Entity_Id standard_exception_type,
298 Int gigi_operating_mode)
300 Node_Id gnat_iter;
301 Entity_Id gnat_literal;
302 tree t, ftype, int64_type;
303 struct elab_info *info;
304 int i;
306 max_gnat_nodes = max_gnat_node;
308 Node_Offsets_Ptr = node_offsets_ptr;
309 Slots_Ptr = slots_ptr;
310 Next_Node_Ptr = next_node_ptr;
311 Prev_Node_Ptr = prev_node_ptr;
312 Elists_Ptr = elists_ptr;
313 Elmts_Ptr = elmts_ptr;
314 Strings_Ptr = strings_ptr;
315 String_Chars_Ptr = string_chars_ptr;
316 List_Headers_Ptr = list_headers_ptr;
318 type_annotate_only = (gigi_operating_mode == 1);
320 if (Generate_SCO_Instance_Table != 0)
322 file_map = file_info_ptr;
323 maybe_create_decl_to_instance_map (number_file);
326 for (i = 0; i < number_file; i++)
328 /* We rely on the order isomorphism between files and line maps. */
329 if ((int) LINEMAPS_ORDINARY_USED (line_table) != i)
331 gcc_assert (i > 0);
332 error ("%s contains too many lines",
333 File_Name_to_gnu (file_info_ptr[i - 1].File_Name));
336 /* We create the line map for a source file at once, with a fixed number
337 of columns chosen to avoid jumping over the next power of 2. */
338 linemap_add (line_table, LC_ENTER, 0,
339 File_Name_to_gnu (file_info_ptr[i].File_Name), 1);
340 linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
341 linemap_position_for_column (line_table, 252 - 1);
342 linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
345 gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
347 /* Declare the name of the compilation unit as the first global
348 name in order to make the middle-end fully deterministic. */
349 t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
350 first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
352 /* Initialize ourselves. */
353 init_code_table ();
354 init_gnat_decl ();
355 init_gnat_utils ();
357 /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
358 errors. */
359 if (type_annotate_only)
361 TYPE_SIZE (void_type_node) = bitsize_zero_node;
362 TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
365 /* Enable GNAT stack checking method if needed */
366 if (!Stack_Check_Probes_On_Target)
367 set_stack_check_libfunc ("_gnat_stack_check");
369 /* Retrieve alignment settings. */
370 double_float_alignment = get_target_double_float_alignment ();
371 double_scalar_alignment = get_target_double_scalar_alignment ();
373 /* Record the builtin types. Define `integer' and `character' first so that
374 dbx will output them first. */
375 record_builtin_type ("integer", integer_type_node, false);
376 record_builtin_type ("character", char_type_node, false);
377 record_builtin_type ("boolean", boolean_type_node, false);
378 record_builtin_type ("void", void_type_node, false);
380 /* Save the type we made for integer as the type for Standard.Integer. */
381 save_gnu_tree (Base_Type (standard_integer),
382 TYPE_NAME (integer_type_node),
383 false);
385 /* Likewise for character as the type for Standard.Character. */
386 finish_character_type (char_type_node);
387 save_gnu_tree (Base_Type (standard_character),
388 TYPE_NAME (char_type_node),
389 false);
391 /* Likewise for boolean as the type for Standard.Boolean. */
392 save_gnu_tree (Base_Type (standard_boolean),
393 TYPE_NAME (boolean_type_node),
394 false);
395 gnat_literal = First_Literal (Base_Type (standard_boolean));
396 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
397 gcc_assert (t == boolean_false_node);
398 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
399 boolean_type_node, t, true, false, false, false, false,
400 true, false, NULL, gnat_literal);
401 save_gnu_tree (gnat_literal, t, false);
402 gnat_literal = Next_Literal (gnat_literal);
403 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
404 gcc_assert (t == boolean_true_node);
405 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
406 boolean_type_node, t, true, false, false, false, false,
407 true, false, NULL, gnat_literal);
408 save_gnu_tree (gnat_literal, t, false);
410 /* Declare the building blocks of function nodes. */
411 void_list_node = build_tree_list (NULL_TREE, void_type_node);
412 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
413 ptr_void_ftype = build_pointer_type (void_ftype);
415 /* Now declare run-time functions. */
416 malloc_decl
417 = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
418 build_function_type_list (ptr_type_node, sizetype,
419 NULL_TREE),
420 NULL_TREE, is_default, true, true, true, false,
421 false, NULL, Empty);
422 DECL_IS_MALLOC (malloc_decl) = 1;
424 free_decl
425 = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
426 build_function_type_list (void_type_node,
427 ptr_type_node, NULL_TREE),
428 NULL_TREE, is_default, true, true, true, false,
429 false, NULL, Empty);
431 realloc_decl
432 = create_subprog_decl (get_identifier ("__gnat_realloc"), NULL_TREE,
433 build_function_type_list (ptr_type_node,
434 ptr_type_node, sizetype,
435 NULL_TREE),
436 NULL_TREE, is_default, true, true, true, false,
437 false, NULL, Empty);
439 /* This is used for 64-bit multiplication with overflow checking. */
440 int64_type = gnat_type_for_size (64, 0);
441 mulv64_decl
442 = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
443 build_function_type_list (int64_type, int64_type,
444 int64_type, NULL_TREE),
445 NULL_TREE, is_default, true, true, true, false,
446 false, NULL, Empty);
448 if (Enable_128bit_Types)
450 tree int128_type = gnat_type_for_size (128, 0);
451 mulv128_decl
452 = create_subprog_decl (get_identifier ("__gnat_mulv128"), NULL_TREE,
453 build_function_type_list (int128_type,
454 int128_type,
455 int128_type,
456 NULL_TREE),
457 NULL_TREE, is_default, true, true, true, false,
458 false, NULL, Empty);
461 /* Name of the _Parent field in tagged record types. */
462 parent_name_id = get_identifier (Get_Name_String (Name_uParent));
464 /* Name of the Not_Handled_By_Others field in exception record types. */
465 not_handled_by_others_name_id = get_identifier ("not_handled_by_others");
467 /* Make the types and functions used for exception processing. */
468 except_type_node = gnat_to_gnu_type (Base_Type (standard_exception_type));
470 for (t = TYPE_FIELDS (except_type_node); t; t = DECL_CHAIN (t))
471 if (DECL_NAME (t) == not_handled_by_others_name_id)
473 not_handled_by_others_decl = t;
474 break;
476 gcc_assert (DECL_P (not_handled_by_others_decl));
478 jmpbuf_type
479 = build_array_type (gnat_type_for_mode (Pmode, 0),
480 build_index_type (size_int (5)));
481 record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
482 jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
484 /* Functions to get and set the jumpbuf pointer for the current thread. */
485 get_jmpbuf_decl
486 = create_subprog_decl
487 (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
488 NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
489 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
491 set_jmpbuf_decl
492 = create_subprog_decl
493 (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
494 NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
495 NULL_TREE),
496 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
498 get_excptr_decl
499 = create_subprog_decl
500 (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
501 build_function_type_list (build_pointer_type (except_type_node),
502 NULL_TREE),
503 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
505 /* setjmp returns an integer and has one operand, which is a pointer to
506 a jmpbuf. */
507 setjmp_decl
508 = create_subprog_decl
509 (get_identifier ("__builtin_setjmp"), NULL_TREE,
510 build_function_type_list (integer_type_node, jmpbuf_ptr_type,
511 NULL_TREE),
512 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
513 set_decl_built_in_function (setjmp_decl, BUILT_IN_NORMAL, BUILT_IN_SETJMP);
515 /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
516 address. */
517 update_setjmp_buf_decl
518 = create_subprog_decl
519 (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
520 build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
521 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
522 set_decl_built_in_function (update_setjmp_buf_decl, BUILT_IN_NORMAL,
523 BUILT_IN_UPDATE_SETJMP_BUF);
525 /* Indicate that it never returns. */
526 ftype = build_function_type_list (void_type_node,
527 build_pointer_type (except_type_node),
528 NULL_TREE);
529 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
530 raise_nodefer_decl
531 = create_subprog_decl
532 (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE, ftype,
533 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
535 set_exception_parameter_decl
536 = create_subprog_decl
537 (get_identifier ("__gnat_set_exception_parameter"), NULL_TREE,
538 build_function_type_list (void_type_node, ptr_type_node, ptr_type_node,
539 NULL_TREE),
540 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
542 /* Hooks to call when entering/leaving an exception handler. */
543 ftype = build_function_type_list (ptr_type_node,
544 ptr_type_node, NULL_TREE);
545 begin_handler_decl
546 = create_subprog_decl (get_identifier ("__gnat_begin_handler_v1"),
547 NULL_TREE, ftype, NULL_TREE,
548 is_default, true, true, true, false, false, NULL,
549 Empty);
550 /* __gnat_begin_handler_v1 is not a dummy procedure, but we arrange
551 for it not to throw. */
552 TREE_NOTHROW (begin_handler_decl) = 1;
554 ftype = build_function_type_list (ptr_type_node,
555 ptr_type_node, ptr_type_node,
556 ptr_type_node, NULL_TREE);
557 end_handler_decl
558 = create_subprog_decl (get_identifier ("__gnat_end_handler_v1"), NULL_TREE,
559 ftype, NULL_TREE,
560 is_default, true, true, true, false, false, NULL,
561 Empty);
563 ftype = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
564 unhandled_except_decl
565 = create_subprog_decl (get_identifier ("__gnat_unhandled_except_handler"),
566 NULL_TREE, ftype, NULL_TREE,
567 is_default, true, true, true, false, false, NULL,
568 Empty);
570 /* Indicate that it never returns. */
571 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
572 reraise_zcx_decl
573 = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
574 ftype, NULL_TREE,
575 is_default, true, true, true, false, false, NULL,
576 Empty);
578 /* Dummy objects to materialize "others" and "all others" in the exception
579 tables. These are exported by a-exexpr-gcc.adb, so see this unit for
580 the types to use. */
581 others_decl
582 = create_var_decl (get_identifier ("OTHERS"),
583 get_identifier ("__gnat_others_value"),
584 char_type_node, NULL_TREE,
585 true, false, true, false, false, true, false,
586 NULL, Empty);
588 all_others_decl
589 = create_var_decl (get_identifier ("ALL_OTHERS"),
590 get_identifier ("__gnat_all_others_value"),
591 char_type_node, NULL_TREE,
592 true, false, true, false, false, true, false,
593 NULL, Empty);
595 unhandled_others_decl
596 = create_var_decl (get_identifier ("UNHANDLED_OTHERS"),
597 get_identifier ("__gnat_unhandled_others_value"),
598 char_type_node, NULL_TREE,
599 true, false, true, false, false, true, false,
600 NULL, Empty);
602 /* If in no exception handlers mode, all raise statements are redirected to
603 __gnat_last_chance_handler. No need to redefine raise_nodefer_decl since
604 this procedure will never be called in this mode. */
605 if (No_Exception_Handlers_Set ())
607 /* Indicate that it never returns. */
608 ftype = build_function_type_list (void_type_node,
609 build_pointer_type (char_type_node),
610 integer_type_node, NULL_TREE);
611 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
612 tree decl
613 = create_subprog_decl
614 (get_identifier ("__gnat_last_chance_handler"), NULL_TREE, ftype,
615 NULL_TREE, is_default, true, true, true, false, false, NULL,
616 Empty);
617 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
618 gnat_raise_decls[i] = decl;
620 else
622 /* Otherwise, make one decl for each exception reason. */
623 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
624 gnat_raise_decls[i] = build_raise_check (i, exception_simple);
625 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
626 gnat_raise_decls_ext[i]
627 = build_raise_check (i,
628 i == CE_Index_Check_Failed
629 || i == CE_Range_Check_Failed
630 || i == CE_Invalid_Data
631 ? exception_range : exception_column);
634 /* Build the special descriptor type and its null node if needed. */
635 if (TARGET_VTABLE_USES_DESCRIPTORS)
637 tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
638 tree field_list = NULL_TREE;
639 int j;
640 vec<constructor_elt, va_gc> *null_vec = NULL;
641 constructor_elt *elt;
643 fdesc_type_node = make_node (RECORD_TYPE);
644 vec_safe_grow (null_vec, TARGET_VTABLE_USES_DESCRIPTORS, true);
645 elt = (null_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
647 for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
649 tree field
650 = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
651 NULL_TREE, NULL_TREE, 0, 1);
652 DECL_CHAIN (field) = field_list;
653 field_list = field;
654 elt->index = field;
655 elt->value = null_node;
656 elt--;
659 finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
660 record_builtin_type ("descriptor", fdesc_type_node, true);
661 null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
664 longest_float_type_node
665 = get_unpadded_type (Base_Type (standard_long_long_float));
667 main_identifier_node = get_identifier ("main");
669 gnat_init_gcc_eh ();
671 /* Initialize the GCC support for FP operations. */
672 gnat_init_gcc_fp ();
674 /* Install the builtins we might need, either internally or as user-available
675 facilities for Intrinsic imports. Note that this must be done after the
676 GCC exception mechanism is initialized. */
677 gnat_install_builtins ();
679 vec_safe_push (gnu_except_ptr_stack, NULL_TREE);
681 gnu_constraint_error_label_stack.safe_push (Empty);
682 gnu_storage_error_label_stack.safe_push (Empty);
683 gnu_program_error_label_stack.safe_push (Empty);
685 /* Process any Pragma Ident for the main unit. */
686 if (Present (Ident_String (Main_Unit)))
687 targetm.asm_out.output_ident
688 (TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
690 /* Force -fno-strict-aliasing if the configuration pragma was seen. */
691 if (No_Strict_Aliasing_CP)
692 flag_strict_aliasing = 0;
694 /* Save the current optimization options again after the above possible
695 global_options changes. */
696 optimization_default_node
697 = build_optimization_node (&global_options, &global_options_set);
698 optimization_current_node = optimization_default_node;
700 /* Now translate the compilation unit proper. */
701 Compilation_Unit_to_gnu (gnat_root);
703 /* Then process the N_Validate_Unchecked_Conversion nodes. We do this at
704 the very end to avoid having to second-guess the front-end when we run
705 into dummy nodes during the regular processing. */
706 for (i = 0; gnat_validate_uc_list.iterate (i, &gnat_iter); i++)
707 validate_unchecked_conversion (gnat_iter);
708 gnat_validate_uc_list.release ();
710 /* Finally see if we have any elaboration procedures to deal with. */
711 for (info = elab_info_list; info; info = info->next)
713 tree gnu_body = DECL_SAVED_TREE (info->elab_proc);
715 /* We should have a BIND_EXPR but it may not have any statements in it.
716 If it doesn't have any, we have nothing to do except for setting the
717 flag on the GNAT node. Otherwise, process the function as others. */
718 tree gnu_stmts = gnu_body;
719 if (TREE_CODE (gnu_stmts) == BIND_EXPR)
720 gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
721 if (!gnu_stmts || empty_stmt_list_p (gnu_stmts))
722 Set_Has_No_Elaboration_Code (info->gnat_node, 1);
723 else
725 begin_subprog_body (info->elab_proc);
726 end_subprog_body (gnu_body);
727 rest_of_subprog_body_compilation (info->elab_proc);
731 /* Destroy ourselves. */
732 file_map = NULL;
733 destroy_gnat_decl ();
734 destroy_gnat_utils ();
736 /* We cannot track the location of errors past this point. */
737 Current_Error_Node = Empty;
740 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
741 CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext. */
743 static tree
744 build_raise_check (int check, enum exception_info_kind kind)
746 tree result, ftype;
747 const char pfx[] = "__gnat_rcheck_";
749 strcpy (Name_Buffer, pfx);
750 Name_Len = sizeof (pfx) - 1;
751 Get_RT_Exception_Name ((enum RT_Exception_Code) check);
753 if (kind == exception_simple)
755 Name_Buffer[Name_Len] = 0;
756 ftype
757 = build_function_type_list (void_type_node,
758 build_pointer_type (char_type_node),
759 integer_type_node, NULL_TREE);
761 else
763 tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
765 strcpy (Name_Buffer + Name_Len, "_ext");
766 Name_Buffer[Name_Len + 4] = 0;
767 ftype
768 = build_function_type_list (void_type_node,
769 build_pointer_type (char_type_node),
770 integer_type_node, integer_type_node,
771 t, t, NULL_TREE);
774 /* Indicate that it never returns. */
775 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
776 result
777 = create_subprog_decl (get_identifier (Name_Buffer), NULL_TREE, ftype,
778 NULL_TREE, is_default, true, true, true, false,
779 false, NULL, Empty);
781 return result;
784 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
785 an N_Attribute_Reference. */
787 static int
788 lvalue_required_for_attribute_p (Node_Id gnat_node)
790 switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
792 case Attr_Pred:
793 case Attr_Succ:
794 case Attr_First:
795 case Attr_Last:
796 case Attr_Range_Length:
797 case Attr_Length:
798 case Attr_Object_Size:
799 case Attr_Size:
800 case Attr_Value_Size:
801 case Attr_Component_Size:
802 case Attr_Descriptor_Size:
803 case Attr_Max_Size_In_Storage_Elements:
804 case Attr_Min:
805 case Attr_Max:
806 case Attr_Null_Parameter:
807 case Attr_Passed_By_Reference:
808 case Attr_Mechanism_Code:
809 case Attr_Machine:
810 case Attr_Model:
811 return 0;
813 case Attr_Address:
814 case Attr_Access:
815 case Attr_Unchecked_Access:
816 case Attr_Unrestricted_Access:
817 case Attr_Code_Address:
818 case Attr_Pool_Address:
819 case Attr_Alignment:
820 case Attr_Bit_Position:
821 case Attr_Position:
822 case Attr_First_Bit:
823 case Attr_Last_Bit:
824 case Attr_Bit:
825 case Attr_Asm_Input:
826 case Attr_Asm_Output:
827 default:
828 return 1;
832 /* Return a positive value if an lvalue is required for GNAT_NODE. GNU_TYPE
833 is the type that will be used for GNAT_NODE in the translated GNU tree.
834 CONSTANT indicates whether the underlying object represented by GNAT_NODE
835 is constant in the Ada sense. If it is, ADDRESS_OF_CONSTANT indicates
836 whether its value is the address of another constant. If it isn't, then
837 ADDRESS_OF_CONSTANT is ignored.
839 The function climbs up the GNAT tree starting from the node and returns 1
840 upon encountering a node that effectively requires an lvalue downstream.
841 It returns int instead of bool to facilitate usage in non-purely binary
842 logic contexts. */
844 static int
845 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
846 bool address_of_constant)
848 Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
850 switch (Nkind (gnat_parent))
852 case N_Reference:
853 return 1;
855 case N_Attribute_Reference:
856 return lvalue_required_for_attribute_p (gnat_parent);
858 case N_Parameter_Association:
859 case N_Function_Call:
860 case N_Procedure_Call_Statement:
861 /* If the parameter is by reference, an lvalue is required. */
862 return (!constant
863 || must_pass_by_ref (gnu_type)
864 || default_pass_by_ref (gnu_type));
866 case N_Pragma_Argument_Association:
867 return lvalue_required_p (gnat_parent, gnu_type, constant,
868 address_of_constant);
870 case N_Pragma:
871 if (Is_Pragma_Name (Chars (Pragma_Identifier (gnat_parent))))
873 const unsigned char id
874 = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_parent)));
875 return id == Pragma_Inspection_Point;
877 else
878 return 0;
880 case N_Indexed_Component:
881 /* Only the array expression can require an lvalue. */
882 if (Prefix (gnat_parent) != gnat_node)
883 return 0;
885 /* ??? Consider that referencing an indexed component with a variable
886 index forces the whole aggregate to memory. Note that testing only
887 for literals is conservative, any static expression in the RM sense
888 could probably be accepted with some additional work. */
889 for (gnat_temp = First (Expressions (gnat_parent));
890 Present (gnat_temp);
891 gnat_temp = Next (gnat_temp))
892 if (Nkind (gnat_temp) != N_Character_Literal
893 && Nkind (gnat_temp) != N_Integer_Literal
894 && !(Is_Entity_Name (gnat_temp)
895 && Ekind (Entity (gnat_temp)) == E_Enumeration_Literal))
896 return 1;
898 /* ... fall through ... */
900 case N_Selected_Component:
901 case N_Slice:
902 /* Only the prefix expression can require an lvalue. */
903 if (Prefix (gnat_parent) != gnat_node)
904 return 0;
906 return lvalue_required_p (gnat_parent,
907 get_unpadded_type (Etype (gnat_parent)),
908 constant, address_of_constant);
910 case N_Object_Renaming_Declaration:
911 /* We need to preserve addresses through a renaming. */
912 return 1;
914 case N_Object_Declaration:
915 /* We cannot use a constructor if this is an atomic object because
916 the actual assignment might end up being done component-wise. */
917 return (!constant
918 ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
919 && Is_Full_Access (Defining_Entity (gnat_parent)))
920 /* We don't use a constructor if this is a class-wide object
921 because the effective type of the object is the equivalent
922 type of the class-wide subtype and it smashes most of the
923 data into an array of bytes to which we cannot convert. */
924 || Ekind ((Etype (Defining_Entity (gnat_parent))))
925 == E_Class_Wide_Subtype);
927 case N_Assignment_Statement:
928 /* We cannot use a constructor if the LHS is an atomic object because
929 the actual assignment might end up being done component-wise. */
930 return (!constant
931 || Name (gnat_parent) == gnat_node
932 || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
933 && Is_Entity_Name (Name (gnat_parent))
934 && Is_Full_Access (Entity (Name (gnat_parent)))));
936 case N_Unchecked_Type_Conversion:
937 if (!constant)
938 return 1;
940 /* ... fall through ... */
942 case N_Type_Conversion:
943 case N_Qualified_Expression:
944 /* We must look through all conversions because we may need to bypass
945 an intermediate conversion that is meant to be purely formal. */
946 return lvalue_required_p (gnat_parent,
947 get_unpadded_type (Etype (gnat_parent)),
948 constant, address_of_constant);
950 case N_Explicit_Dereference:
951 /* We look through dereferences for address of constant because we need
952 to handle the special cases listed above. */
953 if (constant && address_of_constant)
954 return lvalue_required_p (gnat_parent,
955 get_unpadded_type (Etype (gnat_parent)),
956 true, false);
958 /* ... fall through ... */
960 default:
961 return 0;
964 gcc_unreachable ();
967 /* Return true if an lvalue should be used for GNAT_NODE. GNU_TYPE is the type
968 that will be used for GNAT_NODE in the translated GNU tree and is assumed to
969 be an aggregate type.
971 The function climbs up the GNAT tree starting from the node and returns true
972 upon encountering a node that makes it doable to decide. lvalue_required_p
973 should have been previously invoked on the arguments and returned false. */
975 static bool
976 lvalue_for_aggregate_p (Node_Id gnat_node, tree gnu_type)
978 Node_Id gnat_parent = Parent (gnat_node);
980 switch (Nkind (gnat_parent))
982 case N_Parameter_Association:
983 case N_Function_Call:
984 case N_Procedure_Call_Statement:
985 /* Even if the parameter is by copy, prefer an lvalue. */
986 return true;
988 case N_Simple_Return_Statement:
989 /* Likewise for a return value. */
990 return true;
992 case N_Indexed_Component:
993 case N_Selected_Component:
994 /* If an elementary component is used, take it from the constant. */
995 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_parent))))
996 return false;
998 /* ... fall through ... */
1000 case N_Slice:
1001 return lvalue_for_aggregate_p (gnat_parent,
1002 get_unpadded_type (Etype (gnat_parent)));
1004 case N_Object_Declaration:
1005 /* For an aggregate object declaration, return false consistently. */
1006 return false;
1008 case N_Assignment_Statement:
1009 /* For an aggregate assignment, decide based on the size. */
1011 const HOST_WIDE_INT size = int_size_in_bytes (gnu_type);
1012 return size < 0 || size >= param_large_stack_frame / 4;
1015 case N_Unchecked_Type_Conversion:
1016 case N_Type_Conversion:
1017 case N_Qualified_Expression:
1018 return lvalue_for_aggregate_p (gnat_parent,
1019 get_unpadded_type (Etype (gnat_parent)));
1021 case N_Allocator:
1022 /* We should only reach here through the N_Qualified_Expression case.
1023 Force an lvalue for aggregate types since a block-copy to the newly
1024 allocated area of memory is made. */
1025 return true;
1027 default:
1028 return false;
1031 gcc_unreachable ();
1035 /* Return true if T is a constant DECL node that can be safely replaced
1036 by its initializer. */
1038 static bool
1039 constant_decl_with_initializer_p (tree t)
1041 if (!TREE_CONSTANT (t) || !DECL_P (t) || !DECL_INITIAL (t))
1042 return false;
1044 /* Return false for aggregate types that contain a placeholder since
1045 their initializers cannot be manipulated easily. */
1046 if (AGGREGATE_TYPE_P (TREE_TYPE (t))
1047 && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (t))
1048 && type_contains_placeholder_p (TREE_TYPE (t)))
1049 return false;
1051 return true;
1054 /* Return an expression equivalent to EXP but where constant DECL nodes
1055 have been replaced by their initializer. */
1057 static tree
1058 fold_constant_decl_in_expr (tree exp)
1060 enum tree_code code = TREE_CODE (exp);
1061 tree op0;
1063 switch (code)
1065 case CONST_DECL:
1066 case VAR_DECL:
1067 if (!constant_decl_with_initializer_p (exp))
1068 return exp;
1070 return DECL_INITIAL (exp);
1072 case COMPONENT_REF:
1073 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1074 if (op0 == TREE_OPERAND (exp, 0))
1075 return exp;
1077 return fold_build3 (COMPONENT_REF, TREE_TYPE (exp), op0,
1078 TREE_OPERAND (exp, 1), NULL_TREE);
1080 case BIT_FIELD_REF:
1081 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1082 if (op0 == TREE_OPERAND (exp, 0))
1083 return exp;
1085 return fold_build3 (BIT_FIELD_REF, TREE_TYPE (exp), op0,
1086 TREE_OPERAND (exp, 1), TREE_OPERAND (exp, 2));
1088 case ARRAY_REF:
1089 case ARRAY_RANGE_REF:
1090 /* If the index is not itself constant, then nothing can be folded. */
1091 if (!TREE_CONSTANT (TREE_OPERAND (exp, 1)))
1092 return exp;
1093 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1094 if (op0 == TREE_OPERAND (exp, 0))
1095 return exp;
1097 return fold (build4 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
1098 TREE_OPERAND (exp, 2), NULL_TREE));
1100 case REALPART_EXPR:
1101 case IMAGPART_EXPR:
1102 case VIEW_CONVERT_EXPR:
1103 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1104 if (op0 == TREE_OPERAND (exp, 0))
1105 return exp;
1107 return fold_build1 (code, TREE_TYPE (exp), op0);
1109 default:
1110 return exp;
1113 gcc_unreachable ();
1116 /* Return true if TYPE and DEF_TYPE are compatible GNAT types for Gigi. */
1118 static bool
1119 Gigi_Types_Compatible (Entity_Id type, Entity_Id def_type)
1121 /* The trivial case. */
1122 if (type == def_type)
1123 return true;
1125 /* A class-wide type is equivalent to a subtype of itself. */
1126 if (Is_Class_Wide_Type (type))
1127 return true;
1129 /* A packed array type is compatible with its implementation type. */
1130 if (Is_Packed (def_type) && type == Packed_Array_Impl_Type (def_type))
1131 return true;
1133 /* If both types are Itypes, one may be a copy of the other. */
1134 if (Is_Itype (def_type) && Is_Itype (type))
1135 return true;
1137 /* If the type is incomplete and comes from a limited context, then also
1138 consider its non-limited view. */
1139 if (Is_Incomplete_Type (def_type)
1140 && From_Limited_With (def_type)
1141 && Present (Non_Limited_View (def_type)))
1142 return Gigi_Types_Compatible (type, Non_Limited_View (def_type));
1144 /* If the type is incomplete/private, then also consider its full view. */
1145 if (Is_Incomplete_Or_Private_Type (def_type)
1146 && Present (Full_View (def_type)))
1147 return Gigi_Types_Compatible (type, Full_View (def_type));
1149 return false;
1152 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Identifier, to a GCC
1153 tree, which is returned. GNU_RESULT_TYPE_P is a pointer to where we should
1154 place the result type. */
1156 static tree
1157 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
1159 /* The entity of GNAT_NODE and its type. */
1160 Node_Id gnat_entity = (Nkind (gnat_node) == N_Defining_Identifier
1161 || Nkind (gnat_node) == N_Defining_Operator_Symbol)
1162 ? gnat_node : Entity (gnat_node);
1163 Node_Id gnat_entity_type = Etype (gnat_entity);
1164 /* If GNAT_NODE is a constant, whether we should use the initialization
1165 value instead of the constant entity, typically for scalars with an
1166 address clause when the parent doesn't require an lvalue. */
1167 bool use_constant_initializer = false;
1168 /* Whether we should require an lvalue for GNAT_NODE. Needed in
1169 specific circumstances only, so evaluated lazily. < 0 means
1170 unknown, > 0 means known true, 0 means known false. */
1171 int require_lvalue = -1;
1172 Entity_Id gnat_result_type;
1173 tree gnu_result, gnu_result_type;
1175 /* If the Etype of this node is not the same as that of the Entity, then
1176 something went wrong, probably in generic instantiation. However, this
1177 does not apply to types. Since we sometime have strange Ekind's, just
1178 do this test for objects, except for discriminants because their type
1179 may have been changed to a subtype by Exp_Ch3.Adjust_Discriminants. */
1180 gcc_assert (!Is_Object (gnat_entity)
1181 || Ekind (gnat_entity) == E_Discriminant
1182 || Etype (gnat_node) == gnat_entity_type
1183 || Gigi_Types_Compatible (Etype (gnat_node), gnat_entity_type));
1185 /* If this is a reference to a deferred constant whose partial view is an
1186 unconstrained private type, the proper type is on the full view of the
1187 constant, not on the full view of the type, which may be unconstrained.
1189 This may be a reference to a type, for example in the prefix of the
1190 attribute Position, generated for dispatching code (see Make_DT in
1191 exp_disp,adb). In that case we need the type itself, not is parent,
1192 in particular if it is a derived type */
1193 if (Ekind (gnat_entity) == E_Constant
1194 && Is_Private_Type (gnat_entity_type)
1195 && (Has_Unknown_Discriminants (gnat_entity_type)
1196 || (Present (Full_View (gnat_entity_type))
1197 && Has_Discriminants (Full_View (gnat_entity_type))))
1198 && Present (Full_View (gnat_entity)))
1200 gnat_entity = Full_View (gnat_entity);
1201 gnat_result_type = Etype (gnat_entity);
1203 else
1205 /* We use the Actual_Subtype only if it has already been elaborated,
1206 as we may be invoked precisely during its elaboration, otherwise
1207 the Etype. Avoid using it for packed arrays to simplify things,
1208 except in a return statement because we need the actual size and
1209 the front-end does not make it explicit in this case. */
1210 if ((Ekind (gnat_entity) == E_Constant
1211 || Ekind (gnat_entity) == E_Variable
1212 || Is_Formal (gnat_entity))
1213 && !(Is_Array_Type (Etype (gnat_entity))
1214 && Present (Packed_Array_Impl_Type (Etype (gnat_entity)))
1215 && Nkind (Parent (gnat_node)) != N_Simple_Return_Statement)
1216 && Present (Actual_Subtype (gnat_entity))
1217 && present_gnu_tree (Actual_Subtype (gnat_entity)))
1218 gnat_result_type = Actual_Subtype (gnat_entity);
1219 else
1220 gnat_result_type = Etype (gnat_node);
1223 /* Expand the type of this identifier first, in case it is an enumeral
1224 literal, which only get made when the type is expanded. There is no
1225 order-of-elaboration issue here. */
1226 gnu_result_type = get_unpadded_type (gnat_result_type);
1228 /* If this is a non-imported elementary constant with an address clause,
1229 retrieve the value instead of a pointer to be dereferenced unless
1230 an lvalue is required. This is generally more efficient and actually
1231 required if this is a static expression because it might be used
1232 in a context where a dereference is inappropriate, such as a case
1233 statement alternative or a record discriminant. There is no possible
1234 volatile-ness short-circuit here since Volatile constants must be
1235 imported per C.6. */
1236 if (Ekind (gnat_entity) == E_Constant
1237 && Is_Elementary_Type (gnat_result_type)
1238 && !Is_Imported (gnat_entity)
1239 && Present (Address_Clause (gnat_entity)))
1241 require_lvalue
1242 = lvalue_required_p (gnat_node, gnu_result_type, true, false);
1243 use_constant_initializer = !require_lvalue;
1246 if (use_constant_initializer)
1248 /* If this is a deferred constant, the initializer is attached to
1249 the full view. */
1250 if (Present (Full_View (gnat_entity)))
1251 gnat_entity = Full_View (gnat_entity);
1253 gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_entity)));
1255 else
1256 gnu_result = gnat_to_gnu_entity (gnat_entity, NULL_TREE, false);
1258 /* Some objects (such as parameters passed by reference, globals of
1259 variable size, and renamed objects) actually represent the address
1260 of the object. In that case, we must do the dereference. Likewise,
1261 deal with parameters to foreign convention subprograms. */
1262 if (DECL_P (gnu_result)
1263 && (DECL_BY_REF_P (gnu_result)
1264 || (TREE_CODE (gnu_result) == PARM_DECL
1265 && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1267 const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1269 /* If it's a PARM_DECL to foreign convention subprogram, convert it. */
1270 if (TREE_CODE (gnu_result) == PARM_DECL
1271 && DECL_BY_COMPONENT_PTR_P (gnu_result))
1272 gnu_result
1273 = convert (build_pointer_type (gnu_result_type), gnu_result);
1275 /* If it's a CONST_DECL, return the underlying constant like below. */
1276 else if (TREE_CODE (gnu_result) == CONST_DECL
1277 && !(DECL_CONST_ADDRESS_P (gnu_result)
1278 && lvalue_required_p (gnat_node, gnu_result_type, true,
1279 true)))
1280 gnu_result = DECL_INITIAL (gnu_result);
1282 /* Do the final dereference. */
1283 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1285 if ((TREE_CODE (gnu_result) == INDIRECT_REF
1286 || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1287 && No (Address_Clause (gnat_entity)))
1288 TREE_THIS_NOTRAP (gnu_result) = 1;
1290 if (read_only)
1291 TREE_READONLY (gnu_result) = 1;
1294 /* If we have a constant declaration and its initializer, try to return the
1295 latter to avoid the need to call fold in lots of places and the need for
1296 elaboration code if this identifier is used as an initializer itself. */
1297 if (constant_decl_with_initializer_p (gnu_result))
1299 bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1300 && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1301 bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1302 && DECL_CONST_ADDRESS_P (gnu_result));
1304 /* If there is a (corresponding) variable or this is the address of a
1305 constant, we only want to return the initializer if an lvalue isn't
1306 required. Evaluate this now if we have not already done so. */
1307 if ((!constant_only || address_of_constant) && require_lvalue < 0)
1308 require_lvalue
1309 = lvalue_required_p (gnat_node, gnu_result_type, true,
1310 address_of_constant)
1311 || (AGGREGATE_TYPE_P (gnu_result_type)
1312 && lvalue_for_aggregate_p (gnat_node, gnu_result_type));
1314 /* Finally retrieve the initializer if this is deemed valid. */
1315 if ((constant_only && !address_of_constant) || !require_lvalue)
1316 gnu_result = DECL_INITIAL (gnu_result);
1319 /* But for a constant renaming we couldn't do that incrementally for its
1320 definition because of the need to return an lvalue so, if the present
1321 context doesn't itself require an lvalue, we try again here. */
1322 else if (Ekind (gnat_entity) == E_Constant
1323 && Is_Elementary_Type (gnat_result_type)
1324 && Present (Renamed_Object (gnat_entity)))
1326 if (require_lvalue < 0)
1327 require_lvalue
1328 = lvalue_required_p (gnat_node, gnu_result_type, true, false);
1329 if (!require_lvalue)
1330 gnu_result = fold_constant_decl_in_expr (gnu_result);
1333 /* The GNAT tree has the type of a function set to its result type, so we
1334 adjust here. Also use the type of the result if the Etype is a subtype
1335 that is nominally unconstrained. Likewise if this is a deferred constant
1336 of a discriminated type whose full view can be elaborated statically, to
1337 avoid problematic conversions to the nominal subtype. But remove any
1338 padding from the resulting type. */
1339 if (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_result))
1340 || Is_Constr_Subt_For_UN_Aliased (gnat_result_type)
1341 || (Ekind (gnat_entity) == E_Constant
1342 && Present (Full_View (gnat_entity))
1343 && Has_Discriminants (gnat_result_type)
1344 && TREE_CODE (gnu_result) == CONSTRUCTOR))
1346 gnu_result_type = TREE_TYPE (gnu_result);
1347 if (TYPE_IS_PADDING_P (gnu_result_type))
1348 gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1351 *gnu_result_type_p = gnu_result_type;
1353 return gnu_result;
1356 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Pragma, to a GCC
1357 tree, which is returned. */
1359 static tree
1360 Pragma_to_gnu (Node_Id gnat_node)
1362 tree gnu_result = alloc_stmt_list ();
1363 Node_Id gnat_temp;
1365 /* Check for (and ignore) unrecognized pragmas. */
1366 if (!Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1367 return gnu_result;
1369 const unsigned char id
1370 = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
1372 /* Save the expression of pragma Compile_Time_{Error|Warning} for later. */
1373 if (id == Pragma_Compile_Time_Error || id == Pragma_Compile_Time_Warning)
1375 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1376 gnat_compile_time_expr_list.safe_push (Expression (gnat_temp));
1377 return gnu_result;
1380 /* Stop there if we are just annotating types. */
1381 if (type_annotate_only)
1382 return gnu_result;
1384 switch (id)
1386 case Pragma_Inspection_Point:
1387 /* Do nothing at top level: all such variables are already viewable. */
1388 if (global_bindings_p ())
1389 break;
1391 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1392 Present (gnat_temp);
1393 gnat_temp = Next (gnat_temp))
1395 Node_Id gnat_expr = Expression (gnat_temp);
1396 tree gnu_expr = gnat_to_gnu (gnat_expr);
1397 tree asm_constraint = NULL_TREE;
1398 #ifdef ASM_COMMENT_START
1399 char *comment;
1400 #endif
1401 gnu_expr = maybe_unconstrained_array (gnu_expr);
1402 if (TREE_CODE (gnu_expr) == CONST_DECL
1403 && DECL_CONST_CORRESPONDING_VAR (gnu_expr))
1404 gnu_expr = DECL_CONST_CORRESPONDING_VAR (gnu_expr);
1405 gnat_mark_addressable (gnu_expr);
1407 #ifdef ASM_COMMENT_START
1408 comment = concat (ASM_COMMENT_START,
1409 " inspection point: ",
1410 Get_Name_String (Chars (gnat_expr)),
1411 " is at %0",
1412 NULL);
1413 asm_constraint = build_string (strlen (comment), comment);
1414 free (comment);
1415 #endif
1416 gnu_expr = build5 (ASM_EXPR, void_type_node,
1417 asm_constraint,
1418 NULL_TREE,
1419 tree_cons
1420 (build_tree_list (NULL_TREE,
1421 build_string (1, "m")),
1422 gnu_expr, NULL_TREE),
1423 NULL_TREE, NULL_TREE);
1424 ASM_VOLATILE_P (gnu_expr) = 1;
1425 set_expr_location_from_node (gnu_expr, gnat_node);
1426 append_to_statement_list (gnu_expr, &gnu_result);
1428 break;
1430 case Pragma_Loop_Optimize:
1431 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1432 Present (gnat_temp);
1433 gnat_temp = Next (gnat_temp))
1435 tree gnu_loop_stmt = gnu_loop_stack->last ()->stmt;
1437 switch (Chars (Expression (gnat_temp)))
1439 case Name_Ivdep:
1440 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
1441 break;
1443 case Name_No_Unroll:
1444 LOOP_STMT_NO_UNROLL (gnu_loop_stmt) = 1;
1445 break;
1447 case Name_Unroll:
1448 LOOP_STMT_UNROLL (gnu_loop_stmt) = 1;
1449 break;
1451 case Name_No_Vector:
1452 LOOP_STMT_NO_VECTOR (gnu_loop_stmt) = 1;
1453 break;
1455 case Name_Vector:
1456 LOOP_STMT_VECTOR (gnu_loop_stmt) = 1;
1457 break;
1459 default:
1460 gcc_unreachable ();
1463 break;
1465 case Pragma_Optimize:
1466 switch (Chars (Expression
1467 (First (Pragma_Argument_Associations (gnat_node)))))
1469 case Name_Off:
1470 if (optimize)
1471 post_error ("must specify -O0??", gnat_node);
1472 break;
1474 case Name_Space:
1475 if (!optimize_size)
1476 post_error ("must specify -Os??", gnat_node);
1477 break;
1479 case Name_Time:
1480 if (!optimize)
1481 post_error ("insufficient -O value??", gnat_node);
1482 break;
1484 default:
1485 gcc_unreachable ();
1487 break;
1489 case Pragma_Reviewable:
1490 if (write_symbols == NO_DEBUG)
1491 post_error ("must specify -g??", gnat_node);
1492 break;
1494 case Pragma_Warning_As_Error:
1495 case Pragma_Warnings:
1497 Node_Id gnat_expr;
1498 /* Preserve the location of the pragma. */
1499 const location_t location = input_location;
1500 struct cl_option_handlers handlers;
1501 unsigned int option_index;
1502 diagnostic_t kind;
1503 bool imply;
1505 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1507 /* This is the String form: pragma Warning{s|_As_Error}(String). */
1508 if (Nkind (Expression (gnat_temp)) == N_String_Literal)
1510 switch (id)
1512 case Pragma_Warning_As_Error:
1513 kind = DK_ERROR;
1514 imply = false;
1515 break;
1517 case Pragma_Warnings:
1518 kind = DK_WARNING;
1519 imply = true;
1520 break;
1522 default:
1523 gcc_unreachable ();
1526 gnat_expr = Expression (gnat_temp);
1529 /* This is the On/Off form: pragma Warnings (On | Off [,String]). */
1530 else if (Nkind (Expression (gnat_temp)) == N_Identifier)
1532 switch (Chars (Expression (gnat_temp)))
1534 case Name_Off:
1535 kind = DK_IGNORED;
1536 break;
1538 case Name_On:
1539 kind = DK_WARNING;
1540 break;
1542 default:
1543 gcc_unreachable ();
1546 /* Deal with optional pattern (but ignore Reason => "..."). */
1547 if (Present (Next (gnat_temp))
1548 && Chars (Next (gnat_temp)) != Name_Reason)
1550 /* pragma Warnings (On | Off, Name) is handled differently. */
1551 if (Nkind (Expression (Next (gnat_temp))) != N_String_Literal)
1552 break;
1554 gnat_expr = Expression (Next (gnat_temp));
1556 else
1558 gnat_expr = Empty;
1560 /* For pragma Warnings (Off), we save the current state... */
1561 if (kind == DK_IGNORED)
1562 diagnostic_push_diagnostics (global_dc, location);
1564 /* ...so that, for pragma Warnings (On), we do not enable all
1565 the warnings but just restore the previous state. */
1566 else
1568 diagnostic_pop_diagnostics (global_dc, location);
1569 break;
1573 imply = false;
1576 else
1577 gcc_unreachable ();
1579 /* This is the same implementation as in the C family of compilers. */
1580 const unsigned int lang_mask = CL_Ada | CL_COMMON;
1581 const char *arg = NULL;
1582 if (Present (gnat_expr))
1584 tree gnu_expr = gnat_to_gnu (gnat_expr);
1585 const char *option_string = TREE_STRING_POINTER (gnu_expr);
1586 const int len = TREE_STRING_LENGTH (gnu_expr);
1587 if (len < 3 || option_string[0] != '-' || option_string[1] != 'W')
1588 break;
1589 option_index = find_opt (option_string + 1, lang_mask);
1590 if (option_index == OPT_SPECIAL_unknown)
1592 post_error ("unknown -W switch??", gnat_node);
1593 break;
1595 else if (!(cl_options[option_index].flags & CL_WARNING))
1597 post_error ("-W switch does not control warning??", gnat_node);
1598 break;
1600 else if (!(cl_options[option_index].flags & lang_mask))
1602 post_error ("-W switch not valid for Ada??", gnat_node);
1603 break;
1605 if (cl_options[option_index].flags & CL_JOINED)
1606 arg = option_string + 1 + cl_options[option_index].opt_len;
1608 else
1609 option_index = 0;
1611 set_default_handlers (&handlers, NULL);
1612 control_warning_option (option_index, (int) kind, arg, imply, location,
1613 lang_mask, &handlers, &global_options,
1614 &global_options_set, global_dc);
1616 break;
1618 default:
1619 break;
1622 return gnu_result;
1625 /* Check the inline status of nested function FNDECL wrt its parent function.
1627 If a non-inline nested function is referenced from an inline external
1628 function, we cannot honor both requests at the same time without cloning
1629 the nested function in the current unit since it is private to its unit.
1630 We could inline it as well but it's probably better to err on the side
1631 of too little inlining.
1633 This must be done only on nested functions present in the source code
1634 and not on nested functions generated by the compiler, e.g. finalizers,
1635 because they may be not marked inline and we don't want them to block
1636 the inlining of the parent function. */
1638 static void
1639 check_inlining_for_nested_subprog (tree fndecl)
1641 if (DECL_IGNORED_P (current_function_decl) || DECL_IGNORED_P (fndecl))
1642 return;
1644 if (DECL_DECLARED_INLINE_P (fndecl))
1645 return;
1647 tree parent_decl = decl_function_context (fndecl);
1648 if (DECL_EXTERNAL (parent_decl) && DECL_DECLARED_INLINE_P (parent_decl))
1650 const location_t loc1 = DECL_SOURCE_LOCATION (fndecl);
1651 const location_t loc2 = DECL_SOURCE_LOCATION (parent_decl);
1653 if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (parent_decl)))
1655 error_at (loc1, "subprogram %q+F not marked %<Inline_Always%>",
1656 fndecl);
1657 error_at (loc2, "parent subprogram cannot be inlined");
1659 else
1661 warning_at (loc1, OPT_Winline, "subprogram %q+F not marked %<Inline%>",
1662 fndecl);
1663 warning_at (loc2, OPT_Winline, "parent subprogram cannot be inlined");
1666 DECL_DECLARED_INLINE_P (parent_decl) = 0;
1667 DECL_UNINLINABLE (parent_decl) = 1;
1671 /* Return an expression for the length of TYPE, an integral type, computed in
1672 RESULT_TYPE, another integral type.
1674 We used to compute the length as MAX (hb - lb + 1, 0) which could overflow
1675 when lb == TYPE'First. We now compute it as (hb >= lb) ? hb - lb + 1 : 0
1676 which would only overflow in much rarer cases, for extremely large arrays
1677 we expect never to encounter in practice. Besides, the former computation
1678 required the use of potentially constraining signed arithmetics while the
1679 latter does not. Note that the comparison must be done in the original
1680 base index type in order to avoid any overflow during the conversion. */
1682 static tree
1683 get_type_length (tree type, tree result_type)
1685 tree comp_type = get_base_type (result_type);
1686 tree base_type = maybe_character_type (get_base_type (type));
1687 tree lb = convert (base_type, TYPE_MIN_VALUE (type));
1688 tree hb = convert (base_type, TYPE_MAX_VALUE (type));
1689 tree length
1690 = build_binary_op (PLUS_EXPR, comp_type,
1691 build_binary_op (MINUS_EXPR, comp_type,
1692 convert (comp_type, hb),
1693 convert (comp_type, lb)),
1694 build_int_cst (comp_type, 1));
1695 length
1696 = build_cond_expr (result_type,
1697 build_binary_op (GE_EXPR, boolean_type_node, hb, lb),
1698 convert (result_type, length),
1699 build_int_cst (result_type, 0));
1700 return length;
1703 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node, to a
1704 GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to where we
1705 should place the result type. ATTRIBUTE is the attribute ID. */
1707 static tree
1708 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1710 const Node_Id gnat_prefix = Prefix (gnat_node);
1711 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
1712 tree gnu_type = TREE_TYPE (gnu_prefix);
1713 tree gnu_expr, gnu_result_type, gnu_result = error_mark_node;
1714 bool prefix_unused = false;
1716 /* If the input is a NULL_EXPR, make a new one. */
1717 if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1719 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1720 *gnu_result_type_p = gnu_result_type;
1721 return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1724 switch (attribute)
1726 case Attr_Pred:
1727 case Attr_Succ:
1728 /* These just add or subtract the constant 1 since representation
1729 clauses for enumeration types are handled in the front-end. */
1730 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1731 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1732 gnu_type = maybe_character_type (gnu_result_type);
1733 if (TREE_TYPE (gnu_expr) != gnu_type)
1734 gnu_expr = convert (gnu_type, gnu_expr);
1735 gnu_result
1736 = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1737 gnu_type, gnu_expr, build_int_cst (gnu_type, 1));
1738 break;
1740 case Attr_Address:
1741 case Attr_Unrestricted_Access:
1742 /* Conversions don't change the address of references but can cause
1743 build_unary_op to miss the references below, so strip them off.
1744 On the contrary, if the address-of operation causes a temporary
1745 to be created, then it must be created with the proper type. */
1746 gnu_expr = remove_conversions (gnu_prefix,
1747 !Must_Be_Byte_Aligned (gnat_node));
1748 if (REFERENCE_CLASS_P (gnu_expr))
1749 gnu_prefix = gnu_expr;
1751 /* If we are taking 'Address of an unconstrained object, this is the
1752 pointer to the underlying array. */
1753 if (attribute == Attr_Address)
1754 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1756 /* If we are building a static dispatch table, we have to honor
1757 TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1758 with the C++ ABI. We do it in the non-static case as well,
1759 see gnat_to_gnu_entity, case E_Access_Subprogram_Type. */
1760 else if (TARGET_VTABLE_USES_DESCRIPTORS
1761 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1763 tree gnu_field, t;
1764 /* Descriptors can only be built here for top-level functions. */
1765 bool build_descriptor = (global_bindings_p () != 0);
1766 int i;
1767 vec<constructor_elt, va_gc> *gnu_vec = NULL;
1768 constructor_elt *elt;
1770 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1772 /* If we're not going to build the descriptor, we have to retrieve
1773 the one which will be built by the linker (or by the compiler
1774 later if a static chain is requested). */
1775 if (!build_descriptor)
1777 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1778 gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1779 gnu_result);
1780 gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1783 vec_safe_grow (gnu_vec, TARGET_VTABLE_USES_DESCRIPTORS, true);
1784 elt = (gnu_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
1785 for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1786 i < TARGET_VTABLE_USES_DESCRIPTORS;
1787 gnu_field = DECL_CHAIN (gnu_field), i++)
1789 if (build_descriptor)
1791 t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1792 build_int_cst (NULL_TREE, i));
1793 TREE_CONSTANT (t) = 1;
1795 else
1796 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1797 gnu_field, NULL_TREE);
1799 elt->index = gnu_field;
1800 elt->value = t;
1801 elt--;
1804 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
1805 break;
1808 /* ... fall through ... */
1810 case Attr_Access:
1811 case Attr_Unchecked_Access:
1812 case Attr_Code_Address:
1813 /* Taking the address of a type does not make sense. */
1814 gcc_assert (TREE_CODE (gnu_prefix) != TYPE_DECL);
1816 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1817 gnu_result
1818 = build_unary_op (((attribute == Attr_Address
1819 || attribute == Attr_Unrestricted_Access)
1820 && !Must_Be_Byte_Aligned (gnat_node))
1821 ? ATTR_ADDR_EXPR : ADDR_EXPR,
1822 gnu_result_type, gnu_prefix);
1824 /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1825 don't try to build a trampoline. */
1826 if (attribute == Attr_Code_Address)
1828 gnu_expr = remove_conversions (gnu_result, false);
1830 if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1831 TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1833 /* On targets for which function symbols denote a descriptor, the
1834 code address is stored within the first slot of the descriptor
1835 so we do an additional dereference:
1836 result = *((result_type *) result)
1837 where we expect result to be of some pointer type already. */
1838 if (targetm.calls.custom_function_descriptors == 0)
1839 gnu_result
1840 = build_unary_op (INDIRECT_REF, NULL_TREE,
1841 convert (build_pointer_type (gnu_result_type),
1842 gnu_result));
1845 /* For 'Access, issue an error message if the prefix is a C++ method
1846 since it can use a special calling convention on some platforms,
1847 which cannot be propagated to the access type. */
1848 else if (attribute == Attr_Access
1849 && TREE_CODE (TREE_TYPE (gnu_prefix)) == METHOD_TYPE)
1850 post_error ("access to C++ constructor or member function not allowed",
1851 gnat_node);
1853 /* For other address attributes applied to a nested function,
1854 find an inner ADDR_EXPR and annotate it so that we can issue
1855 a useful warning with -Wtrampolines. */
1856 else if (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_prefix))
1857 && (gnu_expr = remove_conversions (gnu_result, false))
1858 && TREE_CODE (gnu_expr) == ADDR_EXPR
1859 && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1861 set_expr_location_from_node (gnu_expr, gnat_node);
1863 /* Also check the inlining status. */
1864 check_inlining_for_nested_subprog (TREE_OPERAND (gnu_expr, 0));
1866 /* Moreover, for 'Access or 'Unrestricted_Access with non-
1867 foreign-compatible representation, mark the ADDR_EXPR so
1868 that we can build a descriptor instead of a trampoline. */
1869 if ((attribute == Attr_Access
1870 || attribute == Attr_Unrestricted_Access)
1871 && targetm.calls.custom_function_descriptors > 0
1872 && Can_Use_Internal_Rep (Underlying_Type (Etype (gnat_node))))
1873 FUNC_ADDR_BY_DESCRIPTOR (gnu_expr) = 1;
1875 /* Otherwise, we need to check that we are not violating the
1876 No_Implicit_Dynamic_Code restriction. */
1877 else if (targetm.calls.custom_function_descriptors != 0)
1878 Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1880 break;
1882 case Attr_Pool_Address:
1884 tree gnu_ptr = gnu_prefix;
1885 tree gnu_obj_type;
1887 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1889 /* If this is fat pointer, the object must have been allocated with the
1890 template in front of the array. So compute the template address; do
1891 it by converting to a thin pointer. */
1892 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1893 gnu_ptr
1894 = convert (build_pointer_type
1895 (TYPE_OBJECT_RECORD_TYPE
1896 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1897 gnu_ptr);
1899 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1901 /* If this is a thin pointer, the object must have been allocated with
1902 the template in front of the array. So compute the template address
1903 and return it. */
1904 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
1905 gnu_ptr
1906 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
1907 gnu_ptr,
1908 fold_build1 (NEGATE_EXPR, sizetype,
1909 byte_position
1910 (DECL_CHAIN
1911 TYPE_FIELDS ((gnu_obj_type)))));
1913 gnu_result = convert (gnu_result_type, gnu_ptr);
1915 break;
1917 case Attr_Size:
1918 case Attr_Object_Size:
1919 case Attr_Value_Size:
1920 case Attr_Max_Size_In_Storage_Elements:
1921 /* Strip NOPs, conversions between original and packable versions, and
1922 unpadding from GNU_PREFIX. Note that we cannot simply strip every
1923 VIEW_CONVERT_EXPR because some of them may give the actual size, e.g.
1924 for nominally unconstrained packed array. We use GNU_EXPR to see
1925 if a COMPONENT_REF was involved. */
1926 while (CONVERT_EXPR_P (gnu_prefix)
1927 || TREE_CODE (gnu_prefix) == NON_LVALUE_EXPR
1928 || (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
1929 && TREE_CODE (TREE_TYPE (gnu_prefix)) == RECORD_TYPE
1930 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))
1931 == RECORD_TYPE
1932 && TYPE_NAME (TREE_TYPE (gnu_prefix))
1933 == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
1934 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1935 gnu_expr = gnu_prefix;
1936 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1937 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1938 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1939 prefix_unused = true;
1940 gnu_type = TREE_TYPE (gnu_prefix);
1942 /* Replace an unconstrained array type with the type of the underlying
1943 array, except for 'Max_Size_In_Storage_Elements because we need to
1944 return the (maximum) size requested for an allocator. */
1945 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1947 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1948 if (attribute != Attr_Max_Size_In_Storage_Elements)
1949 gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
1952 /* The type must be frozen at this point. */
1953 gcc_assert (COMPLETE_TYPE_P (gnu_type));
1955 /* If we're looking for the size of a field, return the field size. */
1956 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1957 gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1959 /* Otherwise, if the prefix is an object, or if we are looking for
1960 'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1961 GCC size of the type. We make an exception for padded objects,
1962 as we do not take into account alignment promotions for the size.
1963 This is in keeping with the object case of gnat_to_gnu_entity. */
1964 else if ((TREE_CODE (gnu_prefix) != TYPE_DECL
1965 && !(TYPE_IS_PADDING_P (gnu_type)
1966 && TREE_CODE (gnu_expr) == COMPONENT_REF
1967 && pad_type_has_rm_size (gnu_type)))
1968 || attribute == Attr_Object_Size
1969 || attribute == Attr_Max_Size_In_Storage_Elements)
1971 /* If this is a dereference and we have a special dynamic constrained
1972 subtype on the prefix, use it to compute the size; otherwise, use
1973 the designated subtype. */
1974 if (Nkind (gnat_prefix) == N_Explicit_Dereference)
1976 Node_Id gnat_actual_subtype
1977 = Actual_Designated_Subtype (gnat_prefix);
1978 tree gnu_ptr_type
1979 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_prefix)));
1981 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1982 && Present (gnat_actual_subtype))
1984 tree gnu_actual_obj_type
1985 = gnat_to_gnu_type (gnat_actual_subtype);
1986 gnu_type
1987 = build_unc_object_type_from_ptr (gnu_ptr_type,
1988 gnu_actual_obj_type,
1989 get_identifier ("SIZE"),
1990 false);
1994 gnu_result = TYPE_SIZE (gnu_type);
1997 /* Otherwise, the result is the RM size of the type. */
1998 else
1999 gnu_result = rm_size (gnu_type);
2001 /* Deal with a self-referential size by qualifying the size with the
2002 object or returning the maximum size for a type. */
2003 if (TREE_CODE (gnu_prefix) != TYPE_DECL)
2004 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2005 else if (CONTAINS_PLACEHOLDER_P (gnu_result))
2006 gnu_result = max_size (gnu_result, true);
2008 /* If the type contains a template, subtract the padded size of the
2009 template, except for 'Max_Size_In_Storage_Elements because we need
2010 to return the (maximum) size requested for an allocator. */
2011 if (TREE_CODE (gnu_type) == RECORD_TYPE
2012 && TYPE_CONTAINS_TEMPLATE_P (gnu_type)
2013 && attribute != Attr_Max_Size_In_Storage_Elements)
2014 gnu_result
2015 = size_binop (MINUS_EXPR, gnu_result,
2016 bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type))));
2018 /* For 'Max_Size_In_Storage_Elements, adjust the unit. */
2019 if (attribute == Attr_Max_Size_In_Storage_Elements)
2020 gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
2022 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2023 break;
2025 case Attr_Alignment:
2027 unsigned int align;
2029 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2030 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2031 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2033 gnu_type = TREE_TYPE (gnu_prefix);
2034 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2035 prefix_unused = true;
2037 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2038 align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
2039 else
2041 Entity_Id gnat_type = Etype (gnat_prefix);
2042 unsigned int double_align;
2043 bool is_capped_double, align_clause;
2045 /* If the default alignment of "double" or larger scalar types is
2046 specifically capped and there is an alignment clause neither
2047 on the type nor on the prefix itself, return the cap. */
2048 if ((double_align = double_float_alignment) > 0)
2049 is_capped_double
2050 = is_double_float_or_array (gnat_type, &align_clause);
2051 else if ((double_align = double_scalar_alignment) > 0)
2052 is_capped_double
2053 = is_double_scalar_or_array (gnat_type, &align_clause);
2054 else
2055 is_capped_double = align_clause = false;
2057 if (is_capped_double
2058 && Nkind (gnat_prefix) == N_Identifier
2059 && Present (Alignment_Clause (Entity (gnat_prefix))))
2060 align_clause = true;
2062 if (is_capped_double && !align_clause)
2063 align = double_align;
2064 else
2065 align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
2068 gnu_result = size_int (align);
2070 break;
2072 case Attr_First:
2073 case Attr_Last:
2074 case Attr_Range_Length:
2075 prefix_unused = true;
2077 if (INTEGRAL_TYPE_P (gnu_type) || SCALAR_FLOAT_TYPE_P (gnu_type))
2079 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2081 if (attribute == Attr_First)
2082 gnu_result = TYPE_MIN_VALUE (gnu_type);
2083 else if (attribute == Attr_Last)
2084 gnu_result = TYPE_MAX_VALUE (gnu_type);
2085 else
2086 gnu_result = get_type_length (gnu_type, gnu_result_type);
2087 break;
2090 /* ... fall through ... */
2092 case Attr_Length:
2094 int Dimension = (Present (Expressions (gnat_node))
2095 ? UI_To_Int (Intval (First (Expressions (gnat_node))))
2096 : 1), i;
2097 struct parm_attr_d *pa = NULL;
2098 Entity_Id gnat_param = Empty;
2099 bool unconstrained_ptr_deref = false;
2101 gnu_prefix = maybe_padded_object (gnu_prefix);
2102 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
2104 /* We treat unconstrained array In parameters specially. We also note
2105 whether we are dereferencing a pointer to unconstrained array. */
2106 if (!Is_Constrained (Etype (gnat_prefix)))
2107 switch (Nkind (gnat_prefix))
2109 case N_Identifier:
2110 /* This is the direct case. */
2111 if (Ekind (Entity (gnat_prefix)) == E_In_Parameter)
2112 gnat_param = Entity (gnat_prefix);
2113 break;
2115 case N_Explicit_Dereference:
2116 /* This is the indirect case. Note that we need to be sure that
2117 the access value cannot be null as we'll hoist the load. */
2118 if (Nkind (Prefix (gnat_prefix)) == N_Identifier
2119 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter)
2121 if (Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
2122 gnat_param = Entity (Prefix (gnat_prefix));
2124 else
2125 unconstrained_ptr_deref = true;
2126 break;
2128 default:
2129 break;
2132 /* If the prefix is the view conversion of a constrained array to an
2133 unconstrained form, we retrieve the constrained array because we
2134 might not be able to substitute the PLACEHOLDER_EXPR coming from
2135 the conversion. This can occur with the 'Old attribute applied
2136 to a parameter with an unconstrained type, which gets rewritten
2137 into a constrained local variable very late in the game. */
2138 if (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
2139 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (gnu_prefix)))
2140 && !CONTAINS_PLACEHOLDER_P
2141 (TYPE_SIZE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
2142 gnu_type = TREE_TYPE (TREE_OPERAND (gnu_prefix, 0));
2143 else
2144 gnu_type = TREE_TYPE (gnu_prefix);
2146 prefix_unused = true;
2147 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2149 if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
2151 int ndim;
2152 tree gnu_type_temp;
2154 for (ndim = 1, gnu_type_temp = gnu_type;
2155 TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
2156 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
2157 ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
2160 Dimension = ndim + 1 - Dimension;
2163 for (i = 1; i < Dimension; i++)
2164 gnu_type = TREE_TYPE (gnu_type);
2166 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2168 /* When not optimizing, look up the slot associated with the parameter
2169 and the dimension in the cache and create a new one on failure.
2170 Don't do this when the actual subtype needs debug info (this happens
2171 with -gnatD): in elaborate_expression_1, we create variables that
2172 hold the bounds, so caching attributes isn't very interesting and
2173 causes dependency issues between these variables and cached
2174 expressions. */
2175 if (!optimize
2176 && Present (gnat_param)
2177 && !(Present (Actual_Subtype (gnat_param))
2178 && Needs_Debug_Info (Actual_Subtype (gnat_param))))
2180 FOR_EACH_VEC_SAFE_ELT (f_parm_attr_cache, i, pa)
2181 if (pa->id == gnat_param && pa->dim == Dimension)
2182 break;
2184 if (!pa)
2186 pa = ggc_cleared_alloc<parm_attr_d> ();
2187 pa->id = gnat_param;
2188 pa->dim = Dimension;
2189 vec_safe_push (f_parm_attr_cache, pa);
2193 /* Return the cached expression or build a new one. */
2194 if (attribute == Attr_First)
2196 if (pa && pa->first)
2198 gnu_result = pa->first;
2199 break;
2202 gnu_result
2203 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2206 else if (attribute == Attr_Last)
2208 if (pa && pa->last)
2210 gnu_result = pa->last;
2211 break;
2214 gnu_result
2215 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2218 else /* attribute == Attr_Range_Length || attribute == Attr_Length */
2220 if (pa && pa->length)
2222 gnu_result = pa->length;
2223 break;
2226 gnu_result
2227 = get_type_length (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)),
2228 gnu_result_type);
2231 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2232 handling. Note that these attributes could not have been used on
2233 an unconstrained array type. */
2234 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2236 /* Cache the expression we have just computed. Since we want to do it
2237 at run time, we force the use of a SAVE_EXPR and let the gimplifier
2238 create the temporary in the outermost binding level. We will make
2239 sure in Subprogram_Body_to_gnu that it is evaluated on all possible
2240 paths by forcing its evaluation on entry of the function. */
2241 if (pa)
2243 gnu_result
2244 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2245 switch (attribute)
2247 case Attr_First:
2248 pa->first = gnu_result;
2249 break;
2251 case Attr_Last:
2252 pa->last = gnu_result;
2253 break;
2255 case Attr_Length:
2256 case Attr_Range_Length:
2257 pa->length = gnu_result;
2258 break;
2260 default:
2261 gcc_unreachable ();
2265 /* Otherwise, evaluate it each time it is referenced. */
2266 else
2267 switch (attribute)
2269 case Attr_First:
2270 case Attr_Last:
2271 /* If we are dereferencing a pointer to unconstrained array, we
2272 need to capture the value because the pointed-to bounds may
2273 subsequently be released. */
2274 if (unconstrained_ptr_deref)
2275 gnu_result
2276 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2277 break;
2279 case Attr_Length:
2280 case Attr_Range_Length:
2281 /* Set the source location onto the predicate of the condition
2282 but not if the expression is cached to avoid messing up the
2283 debug info. */
2284 if (TREE_CODE (gnu_result) == COND_EXPR
2285 && EXPR_P (TREE_OPERAND (gnu_result, 0)))
2286 set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
2287 gnat_node);
2288 break;
2290 default:
2291 gcc_unreachable ();
2294 break;
2297 case Attr_Bit_Position:
2298 case Attr_Position:
2299 case Attr_First_Bit:
2300 case Attr_Last_Bit:
2301 case Attr_Bit:
2303 poly_int64 bitsize;
2304 poly_int64 bitpos;
2305 tree gnu_offset;
2306 tree gnu_field_bitpos;
2307 tree gnu_field_offset;
2308 tree gnu_inner;
2309 machine_mode mode;
2310 int unsignedp, reversep, volatilep;
2312 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2313 gnu_prefix = remove_conversions (gnu_prefix, true);
2314 prefix_unused = true;
2316 /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
2317 the result is 0. Don't allow 'Bit on a bare component, though. */
2318 if (attribute == Attr_Bit
2319 && TREE_CODE (gnu_prefix) != COMPONENT_REF
2320 && TREE_CODE (gnu_prefix) != FIELD_DECL)
2322 gnu_result = integer_zero_node;
2323 break;
2326 else
2327 gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
2328 || (attribute == Attr_Bit_Position
2329 && TREE_CODE (gnu_prefix) == FIELD_DECL));
2331 get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
2332 &mode, &unsignedp, &reversep, &volatilep);
2334 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2336 gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
2337 gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
2339 for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
2340 TREE_CODE (gnu_inner) == COMPONENT_REF
2341 && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
2342 gnu_inner = TREE_OPERAND (gnu_inner, 0))
2344 gnu_field_bitpos
2345 = size_binop (PLUS_EXPR, gnu_field_bitpos,
2346 bit_position (TREE_OPERAND (gnu_inner, 1)));
2347 gnu_field_offset
2348 = size_binop (PLUS_EXPR, gnu_field_offset,
2349 byte_position (TREE_OPERAND (gnu_inner, 1)));
2352 else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
2354 gnu_field_bitpos = bit_position (gnu_prefix);
2355 gnu_field_offset = byte_position (gnu_prefix);
2357 else
2359 gnu_field_bitpos = bitsize_zero_node;
2360 gnu_field_offset = size_zero_node;
2363 switch (attribute)
2365 case Attr_Position:
2366 gnu_result = gnu_field_offset;
2367 break;
2369 case Attr_First_Bit:
2370 case Attr_Bit:
2371 gnu_result = size_int (num_trailing_bits (bitpos));
2372 break;
2374 case Attr_Last_Bit:
2375 gnu_result = bitsize_int (num_trailing_bits (bitpos));
2376 gnu_result = size_binop (PLUS_EXPR, gnu_result,
2377 TYPE_SIZE (TREE_TYPE (gnu_prefix)));
2378 /* ??? Avoid a large unsigned result that will overflow when
2379 converted to the signed universal_integer. */
2380 if (integer_zerop (gnu_result))
2381 gnu_result = integer_minus_one_node;
2382 else
2383 gnu_result
2384 = size_binop (MINUS_EXPR, gnu_result, bitsize_one_node);
2385 break;
2387 case Attr_Bit_Position:
2388 gnu_result = gnu_field_bitpos;
2389 break;
2392 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2393 handling. */
2394 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2395 break;
2398 case Attr_Min:
2399 case Attr_Max:
2401 tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
2402 tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
2404 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2406 /* The result of {MIN,MAX}_EXPR is unspecified if either operand is
2407 a NaN so we implement the semantics of C99 f{min,max} to make it
2408 predictable in this case: if either operand is a NaN, the other
2409 is returned; if both operands are NaN's, a NaN is returned. */
2410 if (SCALAR_FLOAT_TYPE_P (gnu_result_type)
2411 && !Machine_Overflows_On_Target)
2413 const bool lhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_lhs);
2414 const bool rhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_rhs);
2415 tree t = builtin_decl_explicit (BUILT_IN_ISNAN);
2416 tree lhs_is_nan, rhs_is_nan;
2418 /* If the operands have side-effects, they need to be evaluated
2419 only once in spite of the multiple references in the result. */
2420 if (lhs_side_effects_p)
2421 gnu_lhs = gnat_protect_expr (gnu_lhs);
2422 if (rhs_side_effects_p)
2423 gnu_rhs = gnat_protect_expr (gnu_rhs);
2425 lhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2426 build_call_expr (t, 1, gnu_lhs),
2427 integer_zero_node);
2429 rhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2430 build_call_expr (t, 1, gnu_rhs),
2431 integer_zero_node);
2433 gnu_result = build_binary_op (attribute == Attr_Min
2434 ? MIN_EXPR : MAX_EXPR,
2435 gnu_result_type, gnu_lhs, gnu_rhs);
2436 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2437 rhs_is_nan, gnu_lhs, gnu_result);
2438 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2439 lhs_is_nan, gnu_rhs, gnu_result);
2441 /* If the operands have side-effects, they need to be evaluated
2442 before doing the tests above since the place they otherwise
2443 would end up being evaluated at run time could be wrong. */
2444 if (lhs_side_effects_p)
2445 gnu_result
2446 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_lhs, gnu_result);
2448 if (rhs_side_effects_p)
2449 gnu_result
2450 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_rhs, gnu_result);
2452 else
2453 gnu_result = build_binary_op (attribute == Attr_Min
2454 ? MIN_EXPR : MAX_EXPR,
2455 gnu_result_type, gnu_lhs, gnu_rhs);
2457 break;
2459 case Attr_Passed_By_Reference:
2460 gnu_result = size_int (default_pass_by_ref (gnu_type)
2461 || must_pass_by_ref (gnu_type));
2462 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2463 break;
2465 case Attr_Component_Size:
2466 gnu_prefix = maybe_padded_object (gnu_prefix);
2467 gnu_type = TREE_TYPE (gnu_prefix);
2469 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2470 gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
2472 while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
2473 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
2474 gnu_type = TREE_TYPE (gnu_type);
2476 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2478 /* Note this size cannot be self-referential. */
2479 gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
2480 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2481 prefix_unused = true;
2482 break;
2484 case Attr_Descriptor_Size:
2485 gnu_type = TREE_TYPE (gnu_prefix);
2486 gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
2488 /* Return the padded size of the template in the object record type. */
2489 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2490 gnu_result = bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2491 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2492 prefix_unused = true;
2493 break;
2495 case Attr_Null_Parameter:
2496 /* This is just a zero cast to the pointer type for our prefix and
2497 dereferenced. */
2498 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2499 gnu_result
2500 = build_unary_op (INDIRECT_REF, NULL_TREE,
2501 convert (build_pointer_type (gnu_result_type),
2502 integer_zero_node));
2503 break;
2505 case Attr_Mechanism_Code:
2507 Entity_Id gnat_obj = Entity (gnat_prefix);
2508 int code;
2510 prefix_unused = true;
2511 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2512 if (Present (Expressions (gnat_node)))
2514 int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
2516 for (gnat_obj = First_Formal (gnat_obj); i > 1;
2517 i--, gnat_obj = Next_Formal (gnat_obj))
2521 code = Mechanism (gnat_obj);
2522 if (code == Default)
2523 code = ((present_gnu_tree (gnat_obj)
2524 && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
2525 || ((TREE_CODE (get_gnu_tree (gnat_obj))
2526 == PARM_DECL)
2527 && (DECL_BY_COMPONENT_PTR_P
2528 (get_gnu_tree (gnat_obj))))))
2529 ? By_Reference : By_Copy);
2530 gnu_result = convert (gnu_result_type, size_int (- code));
2532 break;
2534 case Attr_Model:
2535 /* We treat Model as identical to Machine. This is true for at least
2536 IEEE and some other nice floating-point systems. */
2538 /* ... fall through ... */
2540 case Attr_Machine:
2541 /* The trick is to force the compiler to store the result in memory so
2542 that we do not have extra precision used. But do this only when this
2543 is necessary, i.e. if FP_ARITH_MAY_WIDEN is true and the precision of
2544 the type is lower than that of the longest floating-point type. */
2545 prefix_unused = true;
2546 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2547 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2548 gnu_result = convert (gnu_result_type, gnu_expr);
2550 if (TREE_CODE (gnu_result) != REAL_CST
2551 && fp_arith_may_widen
2552 && TYPE_PRECISION (gnu_result_type)
2553 < TYPE_PRECISION (longest_float_type_node))
2555 tree rec_type = make_node (RECORD_TYPE);
2556 tree field
2557 = create_field_decl (get_identifier ("OBJ"), gnu_result_type,
2558 rec_type, NULL_TREE, NULL_TREE, 0, 0);
2559 tree rec_val, asm_expr;
2561 finish_record_type (rec_type, field, 0, false);
2563 rec_val = build_constructor_single (rec_type, field, gnu_result);
2564 rec_val = build1 (SAVE_EXPR, rec_type, rec_val);
2566 asm_expr
2567 = build5 (ASM_EXPR, void_type_node,
2568 build_string (0, ""),
2569 tree_cons (build_tree_list (NULL_TREE,
2570 build_string (2, "=m")),
2571 rec_val, NULL_TREE),
2572 tree_cons (build_tree_list (NULL_TREE,
2573 build_string (1, "m")),
2574 rec_val, NULL_TREE),
2575 NULL_TREE, NULL_TREE);
2576 ASM_VOLATILE_P (asm_expr) = 1;
2578 gnu_result
2579 = build_compound_expr (gnu_result_type, asm_expr,
2580 build_component_ref (rec_val, field,
2581 false));
2583 break;
2585 case Attr_Deref:
2586 prefix_unused = true;
2587 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2588 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2589 /* This can be a random address so build an alias-all pointer type. */
2590 gnu_expr
2591 = convert (build_pointer_type_for_mode (gnu_result_type, ptr_mode,
2592 true),
2593 gnu_expr);
2594 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_expr);
2595 break;
2597 default:
2598 /* This abort means that we have an unimplemented attribute. */
2599 gcc_unreachable ();
2602 /* If this is an attribute where the prefix was unused, force a use of it if
2603 it has a side-effect. But don't do it if the prefix is just an entity
2604 name. However, if an access check is needed, we must do it. See second
2605 example in AARM 11.6(5.e). */
2606 if (prefix_unused
2607 && TREE_SIDE_EFFECTS (gnu_prefix)
2608 && !Is_Entity_Name (gnat_prefix))
2609 gnu_result
2610 = build_compound_expr (TREE_TYPE (gnu_result), gnu_prefix, gnu_result);
2612 *gnu_result_type_p = gnu_result_type;
2613 return gnu_result;
2616 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Case_Statement, to a
2617 GCC tree, which is returned. */
2619 static tree
2620 Case_Statement_to_gnu (Node_Id gnat_node)
2622 tree gnu_result, gnu_expr, gnu_type, gnu_label;
2623 Node_Id gnat_when;
2624 location_t end_locus;
2625 bool may_fallthru = false;
2627 gnu_expr = gnat_to_gnu (Expression (gnat_node));
2628 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2629 gnu_expr = maybe_character_value (gnu_expr);
2630 gnu_type = TREE_TYPE (gnu_expr);
2632 /* We build a SWITCH_EXPR that contains the code with interspersed
2633 CASE_LABEL_EXPRs for each label. */
2634 if (!Sloc_to_locus (End_Location (gnat_node), &end_locus))
2635 end_locus = input_location;
2636 gnu_label = create_artificial_label (end_locus);
2637 start_stmt_group ();
2639 for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
2640 Present (gnat_when);
2641 gnat_when = Next_Non_Pragma (gnat_when))
2643 bool choices_added_p = false;
2644 Node_Id gnat_choice;
2646 /* First compile all the different case choices for the current WHEN
2647 alternative. */
2648 for (gnat_choice = First (Discrete_Choices (gnat_when));
2649 Present (gnat_choice);
2650 gnat_choice = Next (gnat_choice))
2652 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2653 tree label = create_artificial_label (input_location);
2655 switch (Nkind (gnat_choice))
2657 case N_Range:
2658 gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
2659 gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
2660 break;
2662 case N_Subtype_Indication:
2663 gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
2664 (Constraint (gnat_choice))));
2665 gnu_high = gnat_to_gnu (High_Bound (Range_Expression
2666 (Constraint (gnat_choice))));
2667 break;
2669 case N_Identifier:
2670 case N_Expanded_Name:
2671 /* This represents either a subtype range or a static value of
2672 some kind; Ekind says which. */
2673 if (Is_Type (Entity (gnat_choice)))
2675 tree gnu_type = get_unpadded_type (Entity (gnat_choice));
2677 gnu_low = TYPE_MIN_VALUE (gnu_type);
2678 gnu_high = TYPE_MAX_VALUE (gnu_type);
2679 break;
2682 /* ... fall through ... */
2684 case N_Character_Literal:
2685 case N_Integer_Literal:
2686 gnu_low = gnat_to_gnu (gnat_choice);
2687 break;
2689 case N_Others_Choice:
2690 break;
2692 default:
2693 gcc_unreachable ();
2696 /* Everything should be folded into constants at this point. */
2697 gcc_assert (!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST);
2698 gcc_assert (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST);
2700 if (gnu_low && TREE_TYPE (gnu_low) != gnu_type)
2701 gnu_low = convert (gnu_type, gnu_low);
2702 if (gnu_high && TREE_TYPE (gnu_high) != gnu_type)
2703 gnu_high = convert (gnu_type, gnu_high);
2705 add_stmt_with_node (build_case_label (gnu_low, gnu_high, label),
2706 gnat_choice);
2707 choices_added_p = true;
2710 /* This construct doesn't define a scope so we shouldn't push a binding
2711 level around the statement list. Except that we have always done so
2712 historically and this makes it possible to reduce stack usage. As a
2713 compromise, we keep doing it for case statements, for which this has
2714 never been problematic, but not for case expressions in Ada 2012. */
2715 if (choices_added_p)
2717 const bool is_case_expression
2718 = (Nkind (Parent (gnat_node)) == N_Expression_With_Actions);
2719 tree group
2720 = build_stmt_group (Statements (gnat_when), !is_case_expression);
2721 bool group_may_fallthru = block_may_fallthru (group);
2722 add_stmt (group);
2723 if (group_may_fallthru)
2725 tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
2726 SET_EXPR_LOCATION (stmt, end_locus);
2727 add_stmt (stmt);
2728 may_fallthru = true;
2733 /* Now emit a definition of the label the cases branch to, if any. */
2734 if (may_fallthru)
2735 add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
2736 gnu_result = build2 (SWITCH_EXPR, gnu_type, gnu_expr, end_stmt_group ());
2738 return gnu_result;
2741 /* Return true if we are in the body of a loop. */
2743 static inline bool
2744 inside_loop_p (void)
2746 return !vec_safe_is_empty (gnu_loop_stack);
2749 /* Find out whether EXPR is a simple additive expression based on the iteration
2750 variable of some enclosing loop in the current function. If so, return the
2751 loop and set *DISP to the displacement and *NEG_P to true if this is for a
2752 subtraction; otherwise, return NULL. */
2754 static struct loop_info_d *
2755 find_loop_for (tree expr, tree *disp, bool *neg_p)
2757 tree var, add, cst;
2758 bool minus_p;
2759 struct loop_info_d *iter = NULL;
2760 unsigned int i;
2762 if (is_simple_additive_expression (expr, &add, &cst, &minus_p))
2764 var = add;
2765 if (disp)
2766 *disp = cst;
2767 if (neg_p)
2768 *neg_p = minus_p;
2770 else
2772 var = expr;
2773 if (disp)
2774 *disp = NULL_TREE;
2775 if (neg_p)
2776 *neg_p = false;
2779 var = remove_conversions (var, false);
2781 if (TREE_CODE (var) != VAR_DECL)
2782 return NULL;
2784 gcc_checking_assert (vec_safe_length (gnu_loop_stack) > 0);
2786 FOR_EACH_VEC_ELT_REVERSE (*gnu_loop_stack, i, iter)
2787 if (iter->loop_var == var && iter->fndecl == current_function_decl)
2788 break;
2790 return iter;
2793 /* Return the innermost enclosing loop in the current function. */
2795 static struct loop_info_d *
2796 find_loop (void)
2798 struct loop_info_d *iter = NULL;
2799 unsigned int i;
2801 gcc_checking_assert (vec_safe_length (gnu_loop_stack) > 0);
2803 FOR_EACH_VEC_ELT_REVERSE (*gnu_loop_stack, i, iter)
2804 if (iter->fndecl == current_function_decl)
2805 break;
2807 return iter;
2810 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
2811 false, or the maximum value if MAX is true, of TYPE. */
2813 static bool
2814 can_equal_min_or_max_val_p (tree val, tree type, bool max)
2816 tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
2818 if (TREE_CODE (min_or_max_val) != INTEGER_CST)
2819 return true;
2821 if (TREE_CODE (val) == NOP_EXPR)
2822 val = (max
2823 ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
2824 : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
2826 if (TREE_CODE (val) != INTEGER_CST)
2827 return true;
2829 if (max)
2830 return tree_int_cst_lt (val, min_or_max_val) == 0;
2831 else
2832 return tree_int_cst_lt (min_or_max_val, val) == 0;
2835 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
2836 If REVERSE is true, minimum value is taken as maximum value. */
2838 static inline bool
2839 can_equal_min_val_p (tree val, tree type, bool reverse)
2841 return can_equal_min_or_max_val_p (val, type, reverse);
2844 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
2845 If REVERSE is true, maximum value is taken as minimum value. */
2847 static inline bool
2848 can_equal_max_val_p (tree val, tree type, bool reverse)
2850 return can_equal_min_or_max_val_p (val, type, !reverse);
2853 /* Replace EXPR1 and EXPR2 by invariant expressions if possible. Return
2854 true if both expressions have been replaced and false otherwise. */
2856 static bool
2857 make_invariant (tree *expr1, tree *expr2)
2859 tree inv_expr1 = gnat_invariant_expr (*expr1);
2860 tree inv_expr2 = gnat_invariant_expr (*expr2);
2862 if (inv_expr1)
2863 *expr1 = inv_expr1;
2865 if (inv_expr2)
2866 *expr2 = inv_expr2;
2868 return inv_expr1 && inv_expr2;
2871 /* Helper function for walk_tree, used by independent_iterations_p below. */
2873 static tree
2874 scan_rhs_r (tree *tp, int *walk_subtrees, void *data)
2876 bitmap *params = (bitmap *)data;
2877 tree t = *tp;
2879 /* No need to walk into types or decls. */
2880 if (IS_TYPE_OR_DECL_P (t))
2881 *walk_subtrees = 0;
2883 if (TREE_CODE (t) == PARM_DECL && bitmap_bit_p (*params, DECL_UID (t)))
2884 return t;
2886 return NULL_TREE;
2889 /* Return true if STMT_LIST generates independent iterations in a loop. */
2891 static bool
2892 independent_iterations_p (tree stmt_list)
2894 tree_stmt_iterator tsi;
2895 bitmap params = BITMAP_GGC_ALLOC();
2896 auto_vec<tree, 16> rhs;
2897 tree iter;
2898 int i;
2900 if (TREE_CODE (stmt_list) == BIND_EXPR)
2901 stmt_list = BIND_EXPR_BODY (stmt_list);
2903 /* Scan the list and return false on anything that is not either a check
2904 or an assignment to a parameter with restricted aliasing. */
2905 for (tsi = tsi_start (stmt_list); !tsi_end_p (tsi); tsi_next (&tsi))
2907 tree stmt = tsi_stmt (tsi);
2909 switch (TREE_CODE (stmt))
2911 case COND_EXPR:
2913 if (COND_EXPR_ELSE (stmt))
2914 return false;
2915 if (TREE_CODE (COND_EXPR_THEN (stmt)) != CALL_EXPR)
2916 return false;
2917 tree func = get_callee_fndecl (COND_EXPR_THEN (stmt));
2918 if (!(func && TREE_THIS_VOLATILE (func)))
2919 return false;
2920 break;
2923 case MODIFY_EXPR:
2925 tree lhs = TREE_OPERAND (stmt, 0);
2926 while (handled_component_p (lhs))
2927 lhs = TREE_OPERAND (lhs, 0);
2928 if (TREE_CODE (lhs) != INDIRECT_REF)
2929 return false;
2930 lhs = TREE_OPERAND (lhs, 0);
2931 if (!(TREE_CODE (lhs) == PARM_DECL
2932 && DECL_RESTRICTED_ALIASING_P (lhs)))
2933 return false;
2934 bitmap_set_bit (params, DECL_UID (lhs));
2935 rhs.safe_push (TREE_OPERAND (stmt, 1));
2936 break;
2939 default:
2940 return false;
2944 /* At this point we know that the list contains only statements that will
2945 modify parameters with restricted aliasing. Check that the statements
2946 don't at the time read from these parameters. */
2947 FOR_EACH_VEC_ELT (rhs, i, iter)
2948 if (walk_tree_without_duplicates (&iter, scan_rhs_r, &params))
2949 return false;
2951 return true;
2954 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Loop_Statement, to a
2955 GCC tree, which is returned. */
2957 static tree
2958 Loop_Statement_to_gnu (Node_Id gnat_node)
2960 const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2961 struct loop_info_d *gnu_loop_info = ggc_cleared_alloc<loop_info_d> ();
2962 tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
2963 NULL_TREE, NULL_TREE, NULL_TREE);
2964 tree gnu_loop_label = create_artificial_label (input_location);
2965 tree gnu_cond_expr = NULL_TREE, gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2966 tree gnu_result;
2968 /* Push the loop_info structure associated with the LOOP_STMT. */
2969 gnu_loop_info->fndecl = current_function_decl;
2970 gnu_loop_info->stmt = gnu_loop_stmt;
2971 vec_safe_push (gnu_loop_stack, gnu_loop_info);
2973 /* Set location information for statement and end label. */
2974 set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2975 Sloc_to_locus (Sloc (End_Label (gnat_node)),
2976 &DECL_SOURCE_LOCATION (gnu_loop_label));
2977 LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
2979 /* Set the condition under which the loop must keep going. If we have an
2980 explicit condition, use it to set the location information throughout
2981 the translation of the loop statement to avoid having multiple SLOCs.
2983 For the case "LOOP .... END LOOP;" the condition is always true. */
2984 if (No (gnat_iter_scheme))
2987 /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate. */
2988 else if (Present (Condition (gnat_iter_scheme)))
2990 LOOP_STMT_COND (gnu_loop_stmt)
2991 = gnat_to_gnu (Condition (gnat_iter_scheme));
2993 set_expr_location_from_node (gnu_loop_stmt, gnat_iter_scheme);
2996 /* Otherwise we have an iteration scheme and the condition is given by the
2997 bounds of the subtype of the iteration variable. */
2998 else
3000 Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
3001 Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
3002 Entity_Id gnat_type = Etype (gnat_loop_var);
3003 tree gnu_type = get_unpadded_type (gnat_type);
3004 tree gnu_base_type = maybe_character_type (get_base_type (gnu_type));
3005 tree gnu_one_node = build_int_cst (gnu_base_type, 1);
3006 tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
3007 enum tree_code update_code, test_code, shift_code;
3008 bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
3010 gnu_low = convert (gnu_base_type, TYPE_MIN_VALUE (gnu_type));
3011 gnu_high = convert (gnu_base_type, TYPE_MAX_VALUE (gnu_type));
3013 /* We must disable modulo reduction for the iteration variable, if any,
3014 in order for the loop comparison to be effective. */
3015 if (reverse)
3017 gnu_first = gnu_high;
3018 gnu_last = gnu_low;
3019 update_code = MINUS_NOMOD_EXPR;
3020 test_code = GE_EXPR;
3021 shift_code = PLUS_NOMOD_EXPR;
3023 else
3025 gnu_first = gnu_low;
3026 gnu_last = gnu_high;
3027 update_code = PLUS_NOMOD_EXPR;
3028 test_code = LE_EXPR;
3029 shift_code = MINUS_NOMOD_EXPR;
3032 /* We use two different strategies to translate the loop, depending on
3033 whether optimization is enabled.
3035 If it is, we generate the canonical loop form expected by the loop
3036 optimizer and the loop vectorizer, which is the do-while form:
3038 ENTRY_COND
3039 loop:
3040 TOP_UPDATE
3041 BODY
3042 BOTTOM_COND
3043 GOTO loop
3045 This avoids an implicit dependency on loop header copying and makes
3046 it possible to turn BOTTOM_COND into an inequality test.
3048 If optimization is disabled, loop header copying doesn't come into
3049 play and we try to generate the loop form with the fewer conditional
3050 branches. First, the default form, which is:
3052 loop:
3053 TOP_COND
3054 BODY
3055 BOTTOM_UPDATE
3056 GOTO loop
3058 It should catch most loops with constant ending point. Then, if we
3059 cannot, we try to generate the shifted form:
3061 loop:
3062 TOP_COND
3063 TOP_UPDATE
3064 BODY
3065 GOTO loop
3067 which should catch loops with constant starting point. Otherwise, if
3068 we cannot, we generate the fallback form:
3070 ENTRY_COND
3071 loop:
3072 BODY
3073 BOTTOM_COND
3074 BOTTOM_UPDATE
3075 GOTO loop
3077 which works in all cases. */
3079 if (optimize && !optimize_debug)
3081 /* We can use the do-while form directly if GNU_FIRST-1 doesn't
3082 overflow. */
3083 if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
3086 /* Otherwise, use the do-while form with the help of a special
3087 induction variable in the unsigned version of the base type
3088 or the unsigned version of the size type, whichever is the
3089 largest, in order to have wrap-around arithmetics for it. */
3090 else
3092 if (TYPE_PRECISION (gnu_base_type)
3093 > TYPE_PRECISION (size_type_node))
3094 gnu_base_type
3095 = gnat_type_for_size (TYPE_PRECISION (gnu_base_type), 1);
3096 else
3097 gnu_base_type = size_type_node;
3099 gnu_first = convert (gnu_base_type, gnu_first);
3100 gnu_last = convert (gnu_base_type, gnu_last);
3101 gnu_one_node = build_int_cst (gnu_base_type, 1);
3102 use_iv = true;
3105 gnu_first
3106 = build_binary_op (shift_code, gnu_base_type, gnu_first,
3107 gnu_one_node);
3108 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
3109 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
3111 else
3113 /* We can use the default form if GNU_LAST+1 doesn't overflow. */
3114 if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
3117 /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
3118 GNU_LAST-1 does. */
3119 else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
3120 && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
3122 gnu_first
3123 = build_binary_op (shift_code, gnu_base_type, gnu_first,
3124 gnu_one_node);
3125 gnu_last
3126 = build_binary_op (shift_code, gnu_base_type, gnu_last,
3127 gnu_one_node);
3128 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
3131 /* Otherwise, use the fallback form. */
3132 else
3133 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
3136 /* If we use the BOTTOM_COND, we can turn the test into an inequality
3137 test but we have to add ENTRY_COND to protect the empty loop. */
3138 if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
3140 test_code = NE_EXPR;
3141 gnu_cond_expr
3142 = build3 (COND_EXPR, void_type_node,
3143 build_binary_op (LE_EXPR, boolean_type_node,
3144 gnu_low, gnu_high),
3145 NULL_TREE, alloc_stmt_list ());
3146 set_expr_location_from_node (gnu_cond_expr, gnat_iter_scheme);
3149 /* Open a new nesting level that will surround the loop to declare the
3150 iteration variable. */
3151 start_stmt_group ();
3152 gnat_pushlevel ();
3154 /* If we use the special induction variable, create it and set it to
3155 its initial value. Morever, the regular iteration variable cannot
3156 itself be initialized, lest the initial value wrapped around. */
3157 if (use_iv)
3159 gnu_loop_iv
3160 = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
3161 add_stmt (gnu_stmt);
3162 gnu_first = NULL_TREE;
3164 else
3165 gnu_loop_iv = NULL_TREE;
3167 /* Declare the iteration variable and set it to its initial value. */
3168 gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, true);
3169 if (DECL_BY_REF_P (gnu_loop_var))
3170 gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
3171 else if (use_iv)
3173 gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
3174 SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
3176 gnu_loop_info->loop_var = gnu_loop_var;
3177 gnu_loop_info->low_bound = gnu_low;
3178 gnu_loop_info->high_bound = gnu_high;
3180 /* Do all the arithmetics in the base type. */
3181 gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
3183 /* Set either the top or bottom exit condition. */
3184 if (use_iv)
3185 LOOP_STMT_COND (gnu_loop_stmt)
3186 = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
3187 gnu_last);
3188 else
3189 LOOP_STMT_COND (gnu_loop_stmt)
3190 = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
3191 gnu_last);
3193 /* Set either the top or bottom update statement and give it the source
3194 location of the iteration for better coverage info. */
3195 if (use_iv)
3197 gnu_stmt
3198 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
3199 build_binary_op (update_code, gnu_base_type,
3200 gnu_loop_iv, gnu_one_node));
3201 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3202 append_to_statement_list (gnu_stmt,
3203 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3204 gnu_stmt
3205 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3206 gnu_loop_iv);
3207 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3208 append_to_statement_list (gnu_stmt,
3209 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3211 else
3213 gnu_stmt
3214 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3215 build_binary_op (update_code, gnu_base_type,
3216 gnu_loop_var, gnu_one_node));
3217 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3218 LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
3221 set_expr_location_from_node (gnu_loop_stmt, gnat_iter_scheme);
3224 /* If the loop was named, have the name point to this loop. In this case,
3225 the association is not a DECL node, but the end label of the loop. */
3226 if (Present (Identifier (gnat_node)))
3227 save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
3229 /* Make the loop body into its own block, so any allocated storage will be
3230 released every iteration. This is needed for stack allocation. */
3231 LOOP_STMT_BODY (gnu_loop_stmt)
3232 = build_stmt_group (Statements (gnat_node), true);
3233 TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
3235 /* If we have an iteration scheme, then we are in a statement group. Add
3236 the LOOP_STMT to it, finish it and make it the "loop". */
3237 if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
3239 /* First, if we have computed invariant conditions for range (or index)
3240 checks applied to the iteration variable, find out whether they can
3241 be evaluated to false at compile time; otherwise, if there are not
3242 too many of them, combine them with the original checks. If loop
3243 unswitching is enabled, do not require the loop bounds to be also
3244 invariant, as their evaluation will still be ahead of the loop. */
3245 if (vec_safe_length (gnu_loop_info->checks) > 0
3246 && (make_invariant (&gnu_low, &gnu_high) || optimize >= 3))
3248 struct range_check_info_d *rci;
3249 unsigned int i, n_remaining_checks = 0;
3251 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3253 tree low_ok, high_ok;
3255 if (rci->low_bound)
3257 tree gnu_adjusted_low = convert (rci->type, gnu_low);
3258 if (rci->disp)
3259 gnu_adjusted_low
3260 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3261 rci->type, gnu_adjusted_low, rci->disp);
3262 low_ok
3263 = build_binary_op (GE_EXPR, boolean_type_node,
3264 gnu_adjusted_low, rci->low_bound);
3266 else
3267 low_ok = boolean_true_node;
3269 if (rci->high_bound)
3271 tree gnu_adjusted_high = convert (rci->type, gnu_high);
3272 if (rci->disp)
3273 gnu_adjusted_high
3274 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3275 rci->type, gnu_adjusted_high, rci->disp);
3276 high_ok
3277 = build_binary_op (LE_EXPR, boolean_type_node,
3278 gnu_adjusted_high, rci->high_bound);
3280 else
3281 high_ok = boolean_true_node;
3283 tree range_ok
3284 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
3285 low_ok, high_ok);
3287 rci->invariant_cond
3288 = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
3290 if (rci->invariant_cond == boolean_false_node)
3291 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3292 else
3293 n_remaining_checks++;
3296 /* Note that loop unswitching can only be applied a small number of
3297 times to a given loop (PARAM_MAX_UNSWITCH_LEVEL default to 3). */
3298 if (IN_RANGE (n_remaining_checks, 1, 3)
3299 && optimize >= 2
3300 && !optimize_size)
3301 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3302 if (rci->invariant_cond != boolean_false_node)
3304 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3306 if (optimize >= 3)
3307 add_stmt_with_node_force (rci->inserted_cond, gnat_node);
3311 /* Second, if we have recorded invariants to be hoisted, emit them. */
3312 if (vec_safe_length (gnu_loop_info->invariants) > 0)
3314 tree *iter;
3315 unsigned int i;
3316 FOR_EACH_VEC_ELT (*gnu_loop_info->invariants, i, iter)
3317 add_stmt_with_node_force (*iter, gnat_node);
3320 /* Third, if loop vectorization is enabled and the iterations of the
3321 loop can easily be proved as independent, mark the loop. */
3322 if (optimize >= 3
3323 && independent_iterations_p (LOOP_STMT_BODY (gnu_loop_stmt)))
3324 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
3326 add_stmt (gnu_loop_stmt);
3327 gnat_poplevel ();
3328 gnu_loop_stmt = end_stmt_group ();
3331 /* If we have an outer COND_EXPR, that's our result and this loop is its
3332 "true" statement. Otherwise, the result is the LOOP_STMT. */
3333 if (gnu_cond_expr)
3335 COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
3336 TREE_SIDE_EFFECTS (gnu_cond_expr) = 1;
3337 gnu_result = gnu_cond_expr;
3339 else
3340 gnu_result = gnu_loop_stmt;
3342 gnu_loop_stack->pop ();
3344 return gnu_result;
3347 /* This page implements a form of Named Return Value optimization modeled
3348 on the C++ optimization of the same name. The main difference is that
3349 we disregard any semantical considerations when applying it here, the
3350 counterpart being that we don't try to apply it to semantically loaded
3351 return types, i.e. types with the TYPE_BY_REFERENCE_P flag set.
3353 We consider a function body of the following GENERIC form:
3355 return_type R1;
3356 [...]
3357 RETURN_EXPR [<retval> = ...]
3358 [...]
3359 RETURN_EXPR [<retval> = R1]
3360 [...]
3361 return_type Ri;
3362 [...]
3363 RETURN_EXPR [<retval> = ...]
3364 [...]
3365 RETURN_EXPR [<retval> = Ri]
3366 [...]
3368 where the Ri are not addressable and we try to fulfill a simple criterion
3369 that would make it possible to replace one or several Ri variables by the
3370 single RESULT_DECL of the function.
3372 The first observation is that RETURN_EXPRs that don't directly reference
3373 any of the Ri variables on the RHS of their assignment are transparent wrt
3374 the optimization. This is because the Ri variables aren't addressable so
3375 any transformation applied to them doesn't affect the RHS; moreover, the
3376 assignment writes the full <retval> object so existing values are entirely
3377 discarded.
3379 This property can be extended to some forms of RETURN_EXPRs that reference
3380 the Ri variables, for example CONSTRUCTORs, but isn't true in the general
3381 case, in particular when function calls are involved.
3383 Therefore the algorithm is as follows:
3385 1. Collect the list of candidates for a Named Return Value (Ri variables
3386 on the RHS of assignments of RETURN_EXPRs) as well as the list of the
3387 other expressions on the RHS of such assignments.
3389 2. Prune the members of the first list (candidates) that are referenced
3390 by a member of the second list (expressions).
3392 3. Extract a set of candidates with non-overlapping live ranges from the
3393 first list. These are the Named Return Values.
3395 4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
3396 Named Return Values in the function with the RESULT_DECL.
3398 If the function returns an unconstrained type, things are a bit different
3399 because the anonymous return object is allocated on the secondary stack
3400 and RESULT_DECL is only a pointer to it. Each return object can be of a
3401 different size and is allocated separately so we need not care about the
3402 addressability and the aforementioned overlapping issues. Therefore, we
3403 don't collect the other expressions and skip step #2 in the algorithm. */
3405 struct nrv_data
3407 bitmap nrv;
3408 tree result;
3409 Node_Id gnat_ret;
3410 hash_set<tree> *visited;
3413 /* Return true if T is a Named Return Value. */
3415 static inline bool
3416 is_nrv_p (bitmap nrv, tree t)
3418 return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
3421 /* Helper function for walk_tree, used by finalize_nrv below. */
3423 static tree
3424 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
3426 struct nrv_data *dp = (struct nrv_data *)data;
3427 tree t = *tp;
3429 /* No need to walk into types or decls. */
3430 if (IS_TYPE_OR_DECL_P (t))
3431 *walk_subtrees = 0;
3433 if (is_nrv_p (dp->nrv, t))
3434 bitmap_clear_bit (dp->nrv, DECL_UID (t));
3436 return NULL_TREE;
3439 /* Prune Named Return Values in BLOCK and return true if there is still a
3440 Named Return Value in BLOCK or one of its sub-blocks. */
3442 static bool
3443 prune_nrv_in_block (bitmap nrv, tree block)
3445 bool has_nrv = false;
3446 tree t;
3448 /* First recurse on the sub-blocks. */
3449 for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
3450 has_nrv |= prune_nrv_in_block (nrv, t);
3452 /* Then make sure to keep at most one NRV per block. */
3453 for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
3454 if (is_nrv_p (nrv, t))
3456 if (has_nrv)
3457 bitmap_clear_bit (nrv, DECL_UID (t));
3458 else
3459 has_nrv = true;
3462 return has_nrv;
3465 /* Helper function for walk_tree, used by finalize_nrv below. */
3467 static tree
3468 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
3470 struct nrv_data *dp = (struct nrv_data *)data;
3471 tree t = *tp;
3473 /* No need to walk into types. */
3474 if (TYPE_P (t))
3475 *walk_subtrees = 0;
3477 /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
3478 nop, but differs from using NULL_TREE in that it indicates that we care
3479 about the value of the RESULT_DECL. */
3480 else if (TREE_CODE (t) == RETURN_EXPR
3481 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3483 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
3485 /* Strip useless conversions around the return value. */
3486 if (gnat_useless_type_conversion (ret_val))
3487 ret_val = TREE_OPERAND (ret_val, 0);
3489 if (is_nrv_p (dp->nrv, ret_val))
3490 TREE_OPERAND (t, 0) = dp->result;
3493 /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
3494 if needed. */
3495 else if (TREE_CODE (t) == DECL_EXPR
3496 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3498 tree var = DECL_EXPR_DECL (t), init;
3500 if (DECL_INITIAL (var))
3502 init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
3503 DECL_INITIAL (var));
3504 SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
3505 DECL_INITIAL (var) = NULL_TREE;
3507 else
3508 init = build_empty_stmt (EXPR_LOCATION (t));
3509 *tp = init;
3511 /* Identify the NRV to the RESULT_DECL for debugging purposes. */
3512 SET_DECL_VALUE_EXPR (var, dp->result);
3513 DECL_HAS_VALUE_EXPR_P (var) = 1;
3514 /* ??? Kludge to avoid an assertion failure during inlining. */
3515 DECL_SIZE (var) = bitsize_unit_node;
3516 DECL_SIZE_UNIT (var) = size_one_node;
3519 /* And replace all uses of NRVs with the RESULT_DECL. */
3520 else if (is_nrv_p (dp->nrv, t))
3521 *tp = convert (TREE_TYPE (t), dp->result);
3523 /* Avoid walking into the same tree more than once. Unfortunately, we
3524 can't just use walk_tree_without_duplicates because it would only
3525 call us for the first occurrence of NRVs in the function body. */
3526 if (dp->visited->add (*tp))
3527 *walk_subtrees = 0;
3529 return NULL_TREE;
3532 /* Likewise, but used when the function returns an unconstrained type. */
3534 static tree
3535 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
3537 struct nrv_data *dp = (struct nrv_data *)data;
3538 tree t = *tp;
3540 /* No need to walk into types. */
3541 if (TYPE_P (t))
3542 *walk_subtrees = 0;
3544 /* We need to see the DECL_EXPR of NRVs before any other references so we
3545 walk the body of BIND_EXPR before walking its variables. */
3546 else if (TREE_CODE (t) == BIND_EXPR)
3547 walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
3549 /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
3550 return value built by the allocator instead of the whole construct. */
3551 else if (TREE_CODE (t) == RETURN_EXPR
3552 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3554 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
3556 /* This is the construct returned by the allocator. */
3557 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3558 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
3560 tree rhs = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3562 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
3563 ret_val = CONSTRUCTOR_ELT (rhs, 1)->value;
3564 else
3565 ret_val = rhs;
3568 /* Strip useless conversions around the return value. */
3569 if (gnat_useless_type_conversion (ret_val)
3570 || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
3571 ret_val = TREE_OPERAND (ret_val, 0);
3573 /* Strip unpadding around the return value. */
3574 if (TREE_CODE (ret_val) == COMPONENT_REF
3575 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
3576 ret_val = TREE_OPERAND (ret_val, 0);
3578 /* Assign the new return value to the RESULT_DECL. */
3579 if (is_nrv_p (dp->nrv, ret_val))
3580 TREE_OPERAND (TREE_OPERAND (t, 0), 1)
3581 = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
3584 /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
3585 into a new variable. */
3586 else if (TREE_CODE (t) == DECL_EXPR
3587 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3589 tree saved_current_function_decl = current_function_decl;
3590 tree var = DECL_EXPR_DECL (t);
3591 tree alloc, p_array, new_var, new_ret;
3592 vec<constructor_elt, va_gc> *v;
3593 vec_alloc (v, 2);
3595 /* Create an artificial context to build the allocation. */
3596 current_function_decl = decl_function_context (var);
3597 start_stmt_group ();
3598 gnat_pushlevel ();
3600 /* This will return a COMPOUND_EXPR with the allocation in the first
3601 arm and the final return value in the second arm. */
3602 alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
3603 TREE_TYPE (dp->result),
3604 Procedure_To_Call (dp->gnat_ret),
3605 Storage_Pool (dp->gnat_ret),
3606 Empty, false);
3608 /* The new variable is built as a reference to the allocated space. */
3609 new_var
3610 = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
3611 build_reference_type (TREE_TYPE (var)));
3612 DECL_BY_REFERENCE (new_var) = 1;
3614 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
3616 tree cst = TREE_OPERAND (alloc, 1);
3618 /* The new initial value is a COMPOUND_EXPR with the allocation in
3619 the first arm and the value of P_ARRAY in the second arm. */
3620 DECL_INITIAL (new_var)
3621 = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
3622 TREE_OPERAND (alloc, 0),
3623 CONSTRUCTOR_ELT (cst, 0)->value);
3625 /* Build a modified CONSTRUCTOR that references NEW_VAR. */
3626 p_array = TYPE_FIELDS (TREE_TYPE (alloc));
3627 CONSTRUCTOR_APPEND_ELT (v, p_array,
3628 fold_convert (TREE_TYPE (p_array), new_var));
3629 CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
3630 CONSTRUCTOR_ELT (cst, 1)->value);
3631 new_ret = build_constructor (TREE_TYPE (alloc), v);
3633 else
3635 /* The new initial value is just the allocation. */
3636 DECL_INITIAL (new_var) = alloc;
3637 new_ret = fold_convert (TREE_TYPE (alloc), new_var);
3640 gnat_pushdecl (new_var, Empty);
3642 /* Destroy the artificial context and insert the new statements. */
3643 gnat_zaplevel ();
3644 *tp = end_stmt_group ();
3645 current_function_decl = saved_current_function_decl;
3647 /* Chain NEW_VAR immediately after VAR and ignore the latter. */
3648 DECL_CHAIN (new_var) = DECL_CHAIN (var);
3649 DECL_CHAIN (var) = new_var;
3650 DECL_IGNORED_P (var) = 1;
3652 /* Save the new return value and the dereference of NEW_VAR. */
3653 DECL_INITIAL (var)
3654 = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
3655 build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
3656 /* ??? Kludge to avoid messing up during inlining. */
3657 DECL_CONTEXT (var) = NULL_TREE;
3660 /* And replace all uses of NRVs with the dereference of NEW_VAR. */
3661 else if (is_nrv_p (dp->nrv, t))
3662 *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
3664 /* Avoid walking into the same tree more than once. Unfortunately, we
3665 can't just use walk_tree_without_duplicates because it would only
3666 call us for the first occurrence of NRVs in the function body. */
3667 if (dp->visited->add (*tp))
3668 *walk_subtrees = 0;
3670 return NULL_TREE;
3673 /* Apply FUNC to all the sub-trees of nested functions in NODE. FUNC is called
3674 with the DATA and the address of each sub-tree. If FUNC returns a non-NULL
3675 value, the traversal is stopped. */
3677 static void
3678 walk_nesting_tree (struct cgraph_node *node, walk_tree_fn func, void *data)
3680 for (node = first_nested_function (node);
3681 node; node = next_nested_function (node))
3683 walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), func, data);
3684 walk_nesting_tree (node, func, data);
3688 /* Finalize the Named Return Value optimization for FNDECL. The NRV bitmap
3689 contains the candidates for Named Return Value and OTHER is a list of
3690 the other return values. GNAT_RET is a representative return node. */
3692 static void
3693 finalize_nrv (tree fndecl, bitmap nrv, vec<tree, va_gc> *other, Node_Id gnat_ret)
3695 struct nrv_data data;
3696 walk_tree_fn func;
3697 unsigned int i;
3698 tree iter;
3700 /* We shouldn't be applying the optimization to return types that we aren't
3701 allowed to manipulate freely. */
3702 gcc_assert (!TYPE_IS_BY_REFERENCE_P (TREE_TYPE (TREE_TYPE (fndecl))));
3704 /* Prune the candidates that are referenced by other return values. */
3705 data.nrv = nrv;
3706 data.result = NULL_TREE;
3707 data.gnat_ret = Empty;
3708 data.visited = NULL;
3709 FOR_EACH_VEC_SAFE_ELT (other, i, iter)
3710 walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
3711 if (bitmap_empty_p (nrv))
3712 return;
3714 /* Prune also the candidates that are referenced by nested functions. */
3715 walk_nesting_tree (cgraph_node::get_create (fndecl), prune_nrv_r, &data);
3716 if (bitmap_empty_p (nrv))
3717 return;
3719 /* Extract a set of NRVs with non-overlapping live ranges. */
3720 if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
3721 return;
3723 /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs. */
3724 data.nrv = nrv;
3725 data.result = DECL_RESULT (fndecl);
3726 data.gnat_ret = gnat_ret;
3727 data.visited = new hash_set<tree>;
3728 if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
3729 func = finalize_nrv_unc_r;
3730 else
3731 func = finalize_nrv_r;
3732 walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
3733 delete data.visited;
3736 /* Return true if RET_VAL can be used as a Named Return Value for the
3737 anonymous return object RET_OBJ. */
3739 static bool
3740 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
3742 if (TREE_CODE (ret_val) != VAR_DECL)
3743 return false;
3745 if (TREE_THIS_VOLATILE (ret_val))
3746 return false;
3748 if (DECL_CONTEXT (ret_val) != current_function_decl)
3749 return false;
3751 if (TREE_STATIC (ret_val))
3752 return false;
3754 /* For the constrained case, test for addressability. */
3755 if (ret_obj && TREE_ADDRESSABLE (ret_val))
3756 return false;
3758 /* For the constrained case, test for overalignment. */
3759 if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
3760 return false;
3762 /* For the unconstrained case, test for bogus initialization. */
3763 if (!ret_obj
3764 && DECL_INITIAL (ret_val)
3765 && TREE_CODE (DECL_INITIAL (ret_val)) == NULL_EXPR)
3766 return false;
3768 return true;
3771 /* Build a RETURN_EXPR. If RET_VAL is non-null, build a RETURN_EXPR around
3772 the assignment of RET_VAL to RET_OBJ. Otherwise build a bare RETURN_EXPR
3773 around RESULT_OBJ, which may be null in this case. */
3775 static tree
3776 build_return_expr (tree ret_obj, tree ret_val)
3778 tree result_expr;
3780 if (ret_val)
3782 /* The gimplifier explicitly enforces the following invariant:
3784 RETURN_EXPR
3786 INIT_EXPR
3789 RET_OBJ ...
3791 As a consequence, type consistency dictates that we use the type
3792 of the RET_OBJ as the operation type. */
3793 tree operation_type = TREE_TYPE (ret_obj);
3795 /* Convert the right operand to the operation type. Note that this is
3796 the transformation applied in the INIT_EXPR case of build_binary_op,
3797 with the assumption that the type cannot involve a placeholder. */
3798 if (operation_type != TREE_TYPE (ret_val))
3799 ret_val = convert (operation_type, ret_val);
3801 /* We always can use an INIT_EXPR for the return object. */
3802 result_expr = build2 (INIT_EXPR, void_type_node, ret_obj, ret_val);
3804 /* If the function returns an aggregate type, find out whether this is
3805 a candidate for Named Return Value. If so, record it. Otherwise,
3806 if this is an expression of some kind, record it elsewhere. */
3807 if (optimize
3808 && !optimize_debug
3809 && AGGREGATE_TYPE_P (operation_type)
3810 && !TYPE_IS_FAT_POINTER_P (operation_type)
3811 && TYPE_MODE (operation_type) == BLKmode
3812 && aggregate_value_p (operation_type, current_function_decl))
3814 /* Strip useless conversions around the return value. */
3815 if (gnat_useless_type_conversion (ret_val))
3816 ret_val = TREE_OPERAND (ret_val, 0);
3818 /* Now apply the test to the return value. */
3819 if (return_value_ok_for_nrv_p (ret_obj, ret_val))
3821 if (!f_named_ret_val)
3822 f_named_ret_val = BITMAP_GGC_ALLOC ();
3823 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
3826 /* Note that we need not care about CONSTRUCTORs here, as they are
3827 totally transparent given the read-compose-write semantics of
3828 assignments from CONSTRUCTORs. */
3829 else if (EXPR_P (ret_val))
3830 vec_safe_push (f_other_ret_val, ret_val);
3833 else
3834 result_expr = ret_obj;
3836 return build1 (RETURN_EXPR, void_type_node, result_expr);
3839 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Subprogram_Body. */
3841 static void
3842 Subprogram_Body_to_gnu (Node_Id gnat_node)
3844 /* The defining identifier for the subprogram body. Note that if a
3845 specification has appeared before for this body, then the identifier
3846 occurring in that specification will also be a defining identifier
3847 and calls to this subprogram will point to that specification. */
3848 Entity_Id gnat_subprog
3849 = (Present (Corresponding_Spec (gnat_node))
3850 ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
3851 /* The FUNCTION_DECL node corresponding to the defining identifier. */
3852 tree gnu_subprog;
3853 /* Its RESULT_DECL node. */
3854 tree gnu_result_decl;
3855 /* Its FUNCTION_TYPE node. */
3856 tree gnu_subprog_type;
3857 /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any. */
3858 tree gnu_cico_list;
3859 /* The entry in the CI_CO_LIST that represents a function return, if any. */
3860 tree gnu_return_var_elmt;
3861 /* Its source location. */
3862 location_t locus;
3864 /* If this is a generic subprogram or it has been eliminated, ignore it. */
3865 if (Is_Generic_Subprogram (gnat_subprog) || Is_Eliminated (gnat_subprog))
3866 return;
3868 /* If this subprogram acts as its own spec, define it. Otherwise, just get
3869 the already-elaborated tree node. However, if this subprogram had its
3870 elaboration deferred, we will already have made a tree node for it. So
3871 treat it as not being defined in that case. Such a subprogram cannot
3872 have an address clause or a freeze node, so this test is safe, though it
3873 does disable some otherwise-useful error checking. */
3874 gnu_subprog
3875 = gnat_to_gnu_entity (gnat_subprog, NULL_TREE,
3876 Acts_As_Spec (gnat_node)
3877 && !present_gnu_tree (gnat_subprog));
3878 DECL_FUNCTION_IS_DEF (gnu_subprog) = true;
3879 gnu_result_decl = DECL_RESULT (gnu_subprog);
3880 gnu_subprog_type = TREE_TYPE (gnu_subprog);
3881 gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3882 if (gnu_cico_list && TREE_VALUE (gnu_cico_list) == void_type_node)
3883 gnu_return_var_elmt = gnu_cico_list;
3884 else
3885 gnu_return_var_elmt = NULL_TREE;
3887 /* If the function returns by invisible reference, make it explicit in the
3888 function body. See gnat_to_gnu_subprog_type for more details. */
3889 if (TREE_ADDRESSABLE (gnu_subprog_type))
3891 TREE_TYPE (gnu_result_decl)
3892 = build_reference_type (TREE_TYPE (gnu_result_decl));
3893 relayout_decl (gnu_result_decl);
3896 /* Set the line number in the decl to correspond to that of the body. */
3897 if (DECL_IGNORED_P (gnu_subprog))
3898 locus = UNKNOWN_LOCATION;
3899 else if (!Sloc_to_locus (Sloc (gnat_node), &locus, false, gnu_subprog))
3900 locus = input_location;
3901 DECL_SOURCE_LOCATION (gnu_subprog) = locus;
3903 /* Try to create a bona-fide thunk and hand it over to the middle-end. */
3904 if (Is_Thunk (gnat_subprog)
3905 && maybe_make_gnu_thunk (gnat_subprog, gnu_subprog))
3906 return;
3908 /* Initialize the information structure for the function. */
3909 allocate_struct_function (gnu_subprog, false);
3910 language_function *gnu_subprog_lang = ggc_cleared_alloc<language_function> ();
3911 DECL_STRUCT_FUNCTION (gnu_subprog)->language = gnu_subprog_lang;
3912 DECL_STRUCT_FUNCTION (gnu_subprog)->function_start_locus = locus;
3913 set_cfun (NULL);
3915 begin_subprog_body (gnu_subprog);
3917 /* If there are copy-in/copy-out parameters, we need to ensure that they are
3918 properly copied out by the return statement. We do this by making a new
3919 block and converting any return into a goto to a label at the end of the
3920 block. */
3921 if (gnu_cico_list)
3923 tree gnu_return_var;
3925 vec_safe_push (gnu_return_label_stack,
3926 create_artificial_label (input_location));
3928 start_stmt_group ();
3929 gnat_pushlevel ();
3931 /* If this is a function with copy-in/copy-out parameters and which does
3932 not return by invisible reference, we also need a variable for the
3933 return value to be placed. */
3934 if (gnu_return_var_elmt && !TREE_ADDRESSABLE (gnu_subprog_type))
3936 tree gnu_return_type
3937 = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
3939 gnu_return_var
3940 = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
3941 gnu_return_type, NULL_TREE,
3942 false, false, false, false, false,
3943 true, false, NULL, gnat_subprog);
3944 TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
3946 else
3947 gnu_return_var = NULL_TREE;
3949 vec_safe_push (gnu_return_var_stack, gnu_return_var);
3951 /* See whether there are parameters for which we don't have a GCC tree
3952 yet. These must be Out parameters. Make a VAR_DECL for them and
3953 put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
3954 We can match up the entries because TYPE_CI_CO_LIST is in the order
3955 of the parameters. */
3956 for (Entity_Id gnat_param = First_Formal_With_Extras (gnat_subprog);
3957 Present (gnat_param);
3958 gnat_param = Next_Formal_With_Extras (gnat_param))
3959 if (!present_gnu_tree (gnat_param))
3961 tree gnu_cico_entry = gnu_cico_list;
3962 tree gnu_decl;
3964 /* Skip any entries that have been already filled in; they must
3965 correspond to In Out parameters. */
3966 while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
3967 gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
3969 /* Do any needed dereferences for by-ref objects. */
3970 gnu_decl = gnat_to_gnu_entity (gnat_param, NULL_TREE, true);
3971 gcc_assert (DECL_P (gnu_decl));
3972 if (DECL_BY_REF_P (gnu_decl))
3973 gnu_decl = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_decl);
3975 /* Do any needed references for padded types. */
3976 TREE_VALUE (gnu_cico_entry)
3977 = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)), gnu_decl);
3980 else
3981 vec_safe_push (gnu_return_label_stack, NULL_TREE);
3983 /* Get a tree corresponding to the code for the subprogram. */
3984 start_stmt_group ();
3985 gnat_pushlevel ();
3987 /* First translate the declarations of the subprogram. */
3988 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
3990 /* Then generate the code of the subprogram itself. A return statement will
3991 be present and any Out parameters will be handled there. */
3992 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
3994 gnat_poplevel ();
3995 tree gnu_result = end_stmt_group ();
3997 /* Attempt setting the end_locus of our GCC body tree, typically a BIND_EXPR,
3998 then the end_locus of our GCC subprogram declaration tree. */
3999 set_end_locus_from_node (gnu_result, gnat_node);
4000 set_end_locus_from_node (gnu_subprog, gnat_node);
4002 /* If we populated the parameter attributes cache, we need to make sure that
4003 the cached expressions are evaluated on all the possible paths leading to
4004 their uses. So we force their evaluation on entry of the function. */
4005 vec<parm_attr, va_gc> *cache = gnu_subprog_lang->parm_attr_cache;
4006 if (cache)
4008 struct parm_attr_d *pa;
4009 int i;
4011 start_stmt_group ();
4013 FOR_EACH_VEC_ELT (*cache, i, pa)
4015 if (pa->first)
4016 add_stmt_with_node_force (pa->first, gnat_node);
4017 if (pa->last)
4018 add_stmt_with_node_force (pa->last, gnat_node);
4019 if (pa->length)
4020 add_stmt_with_node_force (pa->length, gnat_node);
4023 add_stmt (gnu_result);
4024 gnu_result = end_stmt_group ();
4026 gnu_subprog_lang->parm_attr_cache = NULL;
4029 /* If we are dealing with a return from an Ada procedure with parameters
4030 passed by copy-in/copy-out, we need to return a record containing the
4031 final values of these parameters. If the list contains only one entry,
4032 return just that entry though.
4034 For a full description of the copy-in/copy-out parameter mechanism, see
4035 the part of the gnat_to_gnu_entity routine dealing with the translation
4036 of subprograms.
4038 We need to make a block that contains the definition of that label and
4039 the copying of the return value. It first contains the function, then
4040 the label and copy statement. */
4041 if (gnu_cico_list)
4043 const Node_Id gnat_end_label
4044 = End_Label (Handled_Statement_Sequence (gnat_node));
4046 gnu_return_var_stack->pop ();
4048 add_stmt (gnu_result);
4049 add_stmt (build1 (LABEL_EXPR, void_type_node,
4050 gnu_return_label_stack->last ()));
4052 /* If this is a function which returns by invisible reference, the
4053 return value has already been dealt with at the return statements,
4054 so we only need to indirectly copy out the parameters. */
4055 if (TREE_ADDRESSABLE (gnu_subprog_type))
4057 tree gnu_ret_deref
4058 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result_decl);
4059 tree t;
4061 gcc_assert (TREE_VALUE (gnu_cico_list) == void_type_node);
4063 for (t = TREE_CHAIN (gnu_cico_list); t; t = TREE_CHAIN (t))
4065 tree gnu_field_deref
4066 = build_component_ref (gnu_ret_deref, TREE_PURPOSE (t), true);
4067 gnu_result = build2 (MODIFY_EXPR, void_type_node,
4068 gnu_field_deref, TREE_VALUE (t));
4069 add_stmt_with_node (gnu_result, gnat_end_label);
4073 /* Otherwise, if this is a procedure or a function which does not return
4074 by invisible reference, we can do a direct block-copy out. */
4075 else
4077 tree gnu_retval;
4079 if (list_length (gnu_cico_list) == 1)
4080 gnu_retval = TREE_VALUE (gnu_cico_list);
4081 else
4082 gnu_retval
4083 = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
4084 gnu_cico_list);
4086 gnu_result = build_return_expr (gnu_result_decl, gnu_retval);
4087 add_stmt_with_node (gnu_result, gnat_end_label);
4090 gnat_poplevel ();
4091 gnu_result = end_stmt_group ();
4094 gnu_return_label_stack->pop ();
4096 /* On SEH targets, install an exception handler around the main entry
4097 point to catch unhandled exceptions. */
4098 if (DECL_NAME (gnu_subprog) == main_identifier_node
4099 && targetm_common.except_unwind_info (&global_options) == UI_SEH)
4101 tree t;
4102 tree etype;
4104 t = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
4105 1, integer_zero_node);
4106 t = build_call_n_expr (unhandled_except_decl, 1, t);
4108 etype = build_unary_op (ADDR_EXPR, NULL_TREE, unhandled_others_decl);
4109 etype = tree_cons (NULL_TREE, etype, NULL_TREE);
4111 t = build2 (CATCH_EXPR, void_type_node, etype, t);
4112 gnu_result = build2 (TRY_CATCH_EXPR, TREE_TYPE (gnu_result),
4113 gnu_result, t);
4116 end_subprog_body (gnu_result);
4118 /* Finally annotate the parameters and disconnect the trees for parameters
4119 that we have turned into variables since they are now unusable. */
4120 for (Entity_Id gnat_param = First_Formal_With_Extras (gnat_subprog);
4121 Present (gnat_param);
4122 gnat_param = Next_Formal_With_Extras (gnat_param))
4124 tree gnu_param = get_gnu_tree (gnat_param);
4125 bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
4127 annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
4128 DECL_BY_REF_P (gnu_param));
4130 if (is_var_decl)
4131 save_gnu_tree (gnat_param, NULL_TREE, false);
4134 /* Disconnect the variable created for the return value. */
4135 if (gnu_return_var_elmt)
4136 TREE_VALUE (gnu_return_var_elmt) = void_type_node;
4138 /* If the function returns an aggregate type and we have candidates for
4139 a Named Return Value, finalize the optimization. */
4140 if (optimize && !optimize_debug && gnu_subprog_lang->named_ret_val)
4142 finalize_nrv (gnu_subprog,
4143 gnu_subprog_lang->named_ret_val,
4144 gnu_subprog_lang->other_ret_val,
4145 gnu_subprog_lang->gnat_ret);
4146 gnu_subprog_lang->named_ret_val = NULL;
4147 gnu_subprog_lang->other_ret_val = NULL;
4150 /* If this is an inlined external function that has been marked uninlinable,
4151 drop the body and stop there. Otherwise compile the body. */
4152 if (DECL_EXTERNAL (gnu_subprog) && DECL_UNINLINABLE (gnu_subprog))
4153 DECL_SAVED_TREE (gnu_subprog) = NULL_TREE;
4154 else
4155 rest_of_subprog_body_compilation (gnu_subprog);
4158 /* The type of an atomic access. */
4160 typedef enum { NOT_ATOMIC, SIMPLE_ATOMIC, OUTER_ATOMIC } atomic_acces_t;
4162 /* Return true if GNAT_NODE references an Atomic entity. This is modeled on
4163 the Is_Atomic_Object predicate of the front-end, but additionally handles
4164 explicit dereferences. */
4166 static bool
4167 node_is_atomic (Node_Id gnat_node)
4169 Entity_Id gnat_entity;
4171 switch (Nkind (gnat_node))
4173 case N_Identifier:
4174 case N_Expanded_Name:
4175 gnat_entity = Entity (gnat_node);
4176 if (Ekind (gnat_entity) != E_Variable)
4177 break;
4178 return Is_Atomic (gnat_entity) || Is_Atomic (Etype (gnat_entity));
4180 case N_Selected_Component:
4181 return Is_Atomic (Etype (gnat_node))
4182 || Is_Atomic (Entity (Selector_Name (gnat_node)));
4184 case N_Indexed_Component:
4185 return Is_Atomic (Etype (gnat_node))
4186 || Has_Atomic_Components (Etype (Prefix (gnat_node)))
4187 || (Is_Entity_Name (Prefix (gnat_node))
4188 && Has_Atomic_Components (Entity (Prefix (gnat_node))));
4190 case N_Explicit_Dereference:
4191 return Is_Atomic (Etype (gnat_node));
4193 default:
4194 break;
4197 return false;
4200 /* Return true if GNAT_NODE references a Volatile_Full_Access entity. This is
4201 modeled on the Is_Volatile_Full_Access_Object predicate of the front-end,
4202 but additionally handles explicit dereferences. */
4204 static bool
4205 node_is_volatile_full_access (Node_Id gnat_node)
4207 Entity_Id gnat_entity;
4209 switch (Nkind (gnat_node))
4211 case N_Identifier:
4212 case N_Expanded_Name:
4213 gnat_entity = Entity (gnat_node);
4214 if (!Is_Object (gnat_entity))
4215 break;
4216 return Is_Volatile_Full_Access (gnat_entity)
4217 || Is_Volatile_Full_Access (Etype (gnat_entity));
4219 case N_Selected_Component:
4220 return Is_Volatile_Full_Access (Etype (gnat_node))
4221 || Is_Volatile_Full_Access (Entity (Selector_Name (gnat_node)));
4223 case N_Indexed_Component:
4224 case N_Explicit_Dereference:
4225 return Is_Volatile_Full_Access (Etype (gnat_node));
4227 default:
4228 break;
4231 return false;
4234 /* Return true if GNAT_NODE references a component of a larger object. */
4236 static inline bool
4237 node_is_component (Node_Id gnat_node)
4239 const Node_Kind k = Nkind (gnat_node);
4240 return
4241 (k == N_Indexed_Component || k == N_Selected_Component || k == N_Slice);
4244 /* Compute whether GNAT_NODE requires atomic access and set TYPE to the type
4245 of access and SYNC according to the associated synchronization setting.
4247 We implement 3 different semantics of atomicity in this function:
4249 1. the Ada 95/2005/2012 semantics of the Atomic aspect/pragma,
4250 2. the Ada 2022 semantics of the Atomic aspect/pragma,
4251 3. the semantics of the Volatile_Full_Access GNAT aspect/pragma.
4253 They are mutually exclusive and the FE should have rejected conflicts. */
4255 static void
4256 get_atomic_access (Node_Id gnat_node, atomic_acces_t *type, bool *sync)
4258 Node_Id gnat_parent, gnat_temp;
4259 unsigned char attr_id;
4261 /* First, scan the parent to filter out irrelevant cases. */
4262 gnat_parent = Parent (gnat_node);
4263 switch (Nkind (gnat_parent))
4265 case N_Attribute_Reference:
4266 attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
4267 /* Do not mess up machine code insertions. */
4268 if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
4269 goto not_atomic;
4271 /* Nothing to do if we are the prefix of an attribute, since we do not
4272 want an atomic access for things like 'Size. */
4274 /* ... fall through ... */
4276 case N_Reference:
4277 /* The N_Reference node is like an attribute. */
4278 if (Prefix (gnat_parent) == gnat_node)
4279 goto not_atomic;
4280 break;
4282 case N_Object_Renaming_Declaration:
4283 /* Nothing to do for the identifier in an object renaming declaration,
4284 the renaming itself does not need atomic access. */
4285 goto not_atomic;
4287 default:
4288 break;
4291 /* Now strip any type conversion from GNAT_NODE. */
4292 if (Nkind (gnat_node) == N_Type_Conversion
4293 || Nkind (gnat_node) == N_Unchecked_Type_Conversion)
4294 gnat_node = Expression (gnat_node);
4296 /* Up to Ada 2012, for Atomic itself, only reads and updates of the object as
4297 a whole require atomic access (RM C.6(15)). But, starting with Ada 2022,
4298 reads of or writes to a nonatomic subcomponent of the object also require
4299 atomic access (RM C.6(19)). */
4300 if (node_is_atomic (gnat_node))
4302 bool as_a_whole = true;
4304 /* If we are the prefix of the parent, then the access is partial. */
4305 for (gnat_temp = gnat_node, gnat_parent = Parent (gnat_temp);
4306 node_is_component (gnat_parent) && Prefix (gnat_parent) == gnat_temp;
4307 gnat_temp = gnat_parent, gnat_parent = Parent (gnat_temp))
4308 if (Ada_Version < Ada_2022 || node_is_atomic (gnat_parent))
4309 goto not_atomic;
4310 else
4311 as_a_whole = false;
4313 /* We consider that partial accesses are not sequential actions and,
4314 therefore, do not require synchronization. */
4315 *type = SIMPLE_ATOMIC;
4316 *sync = as_a_whole ? Atomic_Sync_Required (gnat_node) : false;
4317 return;
4320 /* Look for an outer atomic access of a nonatomic subcomponent. Note that,
4321 for VFA, we do this before looking at the node itself because we need to
4322 access the outermost VFA object atomically, unlike for Atomic where it is
4323 the innermost atomic object (RM C.6(19)). */
4324 for (gnat_temp = gnat_node;
4325 node_is_component (gnat_temp);
4326 gnat_temp = Prefix (gnat_temp))
4327 if ((Ada_Version >= Ada_2022 && node_is_atomic (Prefix (gnat_temp)))
4328 || node_is_volatile_full_access (Prefix (gnat_temp)))
4330 *type = OUTER_ATOMIC;
4331 *sync = false;
4332 return;
4335 /* Unlike Atomic, accessing a VFA object always requires atomic access. */
4336 if (node_is_volatile_full_access (gnat_node))
4338 *type = SIMPLE_ATOMIC;
4339 *sync = false;
4340 return;
4343 not_atomic:
4344 *type = NOT_ATOMIC;
4345 *sync = false;
4348 /* Return true if GNAT_NODE requires simple atomic access and, if so, set SYNC
4349 according to the associated synchronization setting. */
4351 static inline bool
4352 simple_atomic_access_required_p (Node_Id gnat_node, bool *sync)
4354 atomic_acces_t type;
4355 get_atomic_access (gnat_node, &type, sync);
4356 return type == SIMPLE_ATOMIC;
4359 /* Create a temporary variable with PREFIX and TYPE, and return it. */
4361 static tree
4362 create_temporary (const char *prefix, tree type)
4364 tree gnu_temp
4365 = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
4366 type, NULL_TREE,
4367 false, false, false, false, false,
4368 true, false, NULL, Empty);
4369 return gnu_temp;
4372 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
4373 Put the initialization statement into GNU_INIT_STMT and annotate it with
4374 the SLOC of GNAT_NODE. Return the temporary variable. */
4376 static tree
4377 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
4378 Node_Id gnat_node)
4380 tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
4382 *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
4383 set_expr_location_from_node (*gnu_init_stmt, gnat_node);
4385 return gnu_temp;
4388 /* Return true if TYPE is an array of scalar type. */
4390 static bool
4391 is_array_of_scalar_type (tree type)
4393 if (TREE_CODE (type) != ARRAY_TYPE)
4394 return false;
4396 type = TREE_TYPE (type);
4398 return !AGGREGATE_TYPE_P (type) && !POINTER_TYPE_P (type);
4401 /* Helper function for walk_tree, used by return_slot_opt_for_pure_call_p. */
4403 static tree
4404 find_decls_r (tree *tp, int *walk_subtrees, void *data)
4406 bitmap decls = (bitmap) data;
4408 if (TYPE_P (*tp))
4409 *walk_subtrees = 0;
4411 else if (DECL_P (*tp))
4412 bitmap_set_bit (decls, DECL_UID (*tp));
4414 return NULL_TREE;
4417 /* Return whether the assignment TARGET = CALL can be subject to the return
4418 slot optimization, under the assumption that the called function be pure
4419 in the Ada sense and return an array of scalar type. */
4421 static bool
4422 return_slot_opt_for_pure_call_p (tree target, tree call)
4424 /* Check that the target is a DECL. */
4425 if (!DECL_P (target))
4426 return false;
4428 const bitmap decls = BITMAP_GGC_ALLOC ();
4429 call_expr_arg_iterator iter;
4430 tree arg;
4432 /* Check that all the arguments have either a scalar type (we assume that
4433 this means by-copy passing mechanism) or array of scalar type. */
4434 FOR_EACH_CALL_EXPR_ARG (arg, iter, call)
4436 tree arg_type = TREE_TYPE (arg);
4437 if (TREE_CODE (arg_type) == REFERENCE_TYPE)
4438 arg_type = TREE_TYPE (arg_type);
4440 if (is_array_of_scalar_type (arg_type))
4441 walk_tree_without_duplicates (&arg, find_decls_r, decls);
4443 else if (AGGREGATE_TYPE_P (arg_type) || POINTER_TYPE_P (arg_type))
4444 return false;
4447 /* Check that the target is not referenced by the non-scalar arguments. */
4448 return !bitmap_bit_p (decls, DECL_UID (target));
4451 /* Elaborate types referenced in the profile (FIRST_FORMAL, RESULT_TYPE). */
4453 static void
4454 elaborate_profile (Entity_Id first_formal, Entity_Id result_type)
4456 Entity_Id formal;
4458 for (formal = first_formal;
4459 Present (formal);
4460 formal = Next_Formal_With_Extras (formal))
4461 (void) gnat_to_gnu_type (Etype (formal));
4463 if (Present (result_type) && Ekind (result_type) != E_Void)
4464 (void) gnat_to_gnu_type (result_type);
4467 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Function_Call
4468 or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
4469 GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
4470 If GNU_TARGET is non-null, this must be a function call on the RHS of a
4471 N_Assignment_Statement and the result is to be placed into that object.
4472 ATOMIC_ACCESS is the type of atomic access to be used for the assignment
4473 to GNU_TARGET. If, in addition, ATOMIC_SYNC is true, then the assignment
4474 to GNU_TARGET requires atomic synchronization. */
4476 static tree
4477 Call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
4478 atomic_acces_t atomic_access, bool atomic_sync)
4480 const bool function_call = (Nkind (gnat_node) == N_Function_Call);
4481 const bool returning_value = (function_call && !gnu_target);
4482 /* The GCC node corresponding to the GNAT subprogram name. This can either
4483 be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
4484 or an indirect reference expression (an INDIRECT_REF node) pointing to a
4485 subprogram. */
4486 const Node_Id gnat_subprog = Name (gnat_node);
4487 tree gnu_subprog = gnat_to_gnu (gnat_subprog);
4488 /* The FUNCTION_TYPE node giving the GCC type of the subprogram. */
4489 tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
4490 /* The return type of the FUNCTION_TYPE. */
4491 tree gnu_result_type;;
4492 const bool frontend_builtin
4493 = (TREE_CODE (gnu_subprog) == FUNCTION_DECL
4494 && DECL_BUILT_IN_CLASS (gnu_subprog) == BUILT_IN_FRONTEND);
4495 auto_vec<tree, 16> gnu_actual_vec;
4496 tree gnu_name_list = NULL_TREE;
4497 tree gnu_stmt_list = NULL_TREE;
4498 tree gnu_after_list = NULL_TREE;
4499 tree gnu_retval = NULL_TREE;
4500 tree gnu_call, gnu_result;
4501 bool went_into_elab_proc;
4502 bool pushed_binding_level;
4503 bool variadic;
4504 bool by_descriptor;
4505 Entity_Id gnat_formal;
4506 Entity_Id gnat_result_type;
4507 Node_Id gnat_actual;
4508 atomic_acces_t aa_type;
4509 bool aa_sync;
4511 /* The only way we can make a call via an access type is if GNAT_NAME is an
4512 explicit dereference. In that case, get the list of formal args from the
4513 type the access type is pointing to. Otherwise, get the formals from the
4514 entity being called. */
4515 if (Nkind (gnat_subprog) == N_Explicit_Dereference)
4517 const Entity_Id gnat_prefix_type
4518 = Underlying_Type (Etype (Prefix (gnat_subprog)));
4520 gnat_formal = First_Formal_With_Extras (Etype (gnat_subprog));
4521 gnat_result_type = Etype (Etype (gnat_subprog));
4522 variadic = IN (Convention (gnat_prefix_type), Convention_C_Variadic);
4524 /* If the access type doesn't require foreign-compatible representation,
4525 be prepared for descriptors. */
4526 by_descriptor
4527 = targetm.calls.custom_function_descriptors > 0
4528 && Can_Use_Internal_Rep (gnat_prefix_type);
4531 else if (Nkind (gnat_subprog) == N_Attribute_Reference)
4533 /* Assume here that this must be 'Elab_Body or 'Elab_Spec. */
4534 gnat_formal = Empty;
4535 gnat_result_type = Empty;
4536 variadic = false;
4537 by_descriptor = false;
4540 else
4542 gcc_checking_assert (Is_Entity_Name (gnat_subprog));
4544 gnat_formal = First_Formal_With_Extras (Entity (gnat_subprog));
4545 gnat_result_type = Etype (Entity_Id (gnat_subprog));
4546 variadic = IN (Convention (Entity (gnat_subprog)), Convention_C_Variadic);
4547 by_descriptor = false;
4549 /* If we are calling a stubbed function, then raise Program_Error, but
4550 elaborate all our args first. */
4551 if (Convention (Entity (gnat_subprog)) == Convention_Stubbed)
4553 tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
4554 gnat_node, N_Raise_Program_Error);
4556 for (gnat_actual = First_Actual (gnat_node);
4557 Present (gnat_actual);
4558 gnat_actual = Next_Actual (gnat_actual))
4559 add_stmt (gnat_to_gnu (gnat_actual));
4561 if (returning_value)
4563 gnu_result_type = TREE_TYPE (gnu_subprog_type);
4564 *gnu_result_type_p = gnu_result_type;
4565 return build1 (NULL_EXPR, gnu_result_type, call_expr);
4568 return call_expr;
4572 /* We must elaborate the entire profile now because, if it references types
4573 that were initially incomplete,, their elaboration changes the contents
4574 of GNU_SUBPROG_TYPE and, in particular, may change the result type. */
4575 elaborate_profile (gnat_formal, gnat_result_type);
4577 gcc_assert (FUNC_OR_METHOD_TYPE_P (gnu_subprog_type));
4578 gnu_result_type = TREE_TYPE (gnu_subprog_type);
4580 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL)
4582 /* For a call to a nested function, check the inlining status. */
4583 if (decl_function_context (gnu_subprog))
4584 check_inlining_for_nested_subprog (gnu_subprog);
4586 /* For a recursive call, avoid explosion due to recursive inlining. */
4587 if (gnu_subprog == current_function_decl)
4588 DECL_DISREGARD_INLINE_LIMITS (gnu_subprog) = 0;
4591 /* The lifetime of the temporaries created for the call ends right after the
4592 return value is copied, so we can give them the scope of the elaboration
4593 routine at top level. */
4594 if (!current_function_decl)
4596 current_function_decl = get_elaboration_procedure ();
4597 went_into_elab_proc = true;
4599 else
4600 went_into_elab_proc = false;
4602 /* First, create the temporary for the return value when:
4604 1. There is no target and the function has copy-in/copy-out parameters,
4605 because we need to preserve the return value before copying back the
4606 parameters.
4608 2. There is no target and the call is made for neither the declaration
4609 of an object (regular or renaming), nor a return statement, nor an
4610 allocator, nor an aggregate, and the return type has variable size
4611 because in this case the gimplifier cannot create the temporary, or
4612 more generally is an aggregate type, because the gimplifier would
4613 create the temporary in the outermost scope instead of locally here.
4614 But there is an exception for an allocator of unconstrained record
4615 type with default discriminant because we allocate the actual size
4616 in this case, unlike in the other cases, so we need a temporary to
4617 fetch the discriminant and we create it here.
4619 3. There is a target and it is a slice or an array with fixed size,
4620 and the return type has variable size, because the gimplifier
4621 doesn't handle these cases.
4623 4. There is a target which is a bit-field and the function returns an
4624 unconstrained record type with default discriminant, because the
4625 return may copy more data than the bit-field can contain.
4627 5. There is no target and we have misaligned In Out or Out parameters
4628 passed by reference, because we need to preserve the return value
4629 before copying back the parameters. However, in this case, we'll
4630 defer creating the temporary, see below.
4632 This must be done before we push a binding level around the call, since
4633 we will pop it before copying the return value. */
4634 if (function_call
4635 && ((!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))
4636 || (!gnu_target
4637 && Nkind (Parent (gnat_node)) != N_Object_Declaration
4638 && Nkind (Parent (gnat_node)) != N_Object_Renaming_Declaration
4639 && Nkind (Parent (gnat_node)) != N_Simple_Return_Statement
4640 && (!(Nkind (Parent (gnat_node)) == N_Qualified_Expression
4641 && Nkind (Parent (Parent (gnat_node))) == N_Allocator)
4642 || type_is_padding_self_referential (gnu_result_type))
4643 && Nkind (Parent (gnat_node)) != N_Aggregate
4644 && AGGREGATE_TYPE_P (gnu_result_type)
4645 && !TYPE_IS_FAT_POINTER_P (gnu_result_type))
4646 || (gnu_target
4647 && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
4648 || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
4649 && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
4650 == INTEGER_CST))
4651 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)
4652 || (gnu_target
4653 && TREE_CODE (gnu_target) == COMPONENT_REF
4654 && DECL_BIT_FIELD (TREE_OPERAND (gnu_target, 1))
4655 && DECL_SIZE (TREE_OPERAND (gnu_target, 1))
4656 != TYPE_SIZE (TREE_TYPE (gnu_target))
4657 && type_is_padding_self_referential (gnu_result_type))))
4659 gnu_retval = create_temporary ("R", gnu_result_type);
4660 DECL_RETURN_VALUE_P (gnu_retval) = 1;
4663 /* If we don't need a value or have already created it, push a binding level
4664 around the call. This will narrow the lifetime of the temporaries we may
4665 need to make when translating the parameters as much as possible. */
4666 if (!returning_value || gnu_retval)
4668 start_stmt_group ();
4669 gnat_pushlevel ();
4670 pushed_binding_level = true;
4672 else
4673 pushed_binding_level = false;
4675 /* Create the list of the actual parameters as GCC expects it, namely a
4676 chain of TREE_LIST nodes in which the TREE_VALUE field of each node
4677 is an expression and the TREE_PURPOSE field is null. But skip Out
4678 parameters not passed by reference and that need not be copied in. */
4679 for (gnat_actual = First_Actual (gnat_node);
4680 Present (gnat_actual);
4681 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4682 gnat_actual = Next_Actual (gnat_actual))
4684 Entity_Id gnat_formal_type = Etype (gnat_formal);
4685 tree gnu_formal_type = gnat_to_gnu_type (gnat_formal_type);
4686 tree gnu_formal = present_gnu_tree (gnat_formal)
4687 ? get_gnu_tree (gnat_formal) : NULL_TREE;
4688 const bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
4689 const bool is_true_formal_parm
4690 = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
4691 const bool is_by_ref_formal_parm
4692 = is_true_formal_parm
4693 && (DECL_BY_REF_P (gnu_formal)
4694 || DECL_BY_COMPONENT_PTR_P (gnu_formal));
4695 /* In the In Out or Out case, we must suppress conversions that yield
4696 an lvalue but can nevertheless cause the creation of a temporary,
4697 because we need the real object in this case, either to pass its
4698 address if it's passed by reference or as target of the back copy
4699 done after the call if it uses the copy-in/copy-out mechanism.
4700 We do it in the In case too, except for an unchecked conversion
4701 to an elementary type or a constrained composite type because it
4702 alone can cause the actual to be misaligned and the addressability
4703 test is applied to the real object. */
4704 const bool suppress_type_conversion
4705 = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
4706 && (!in_param
4707 || !is_by_ref_formal_parm
4708 || (Is_Composite_Type (Underlying_Type (gnat_formal_type))
4709 && !Is_Constrained (Underlying_Type (gnat_formal_type)))))
4710 || (Nkind (gnat_actual) == N_Type_Conversion
4711 && Is_Composite_Type (Underlying_Type (gnat_formal_type))));
4712 Node_Id gnat_name = suppress_type_conversion
4713 ? Expression (gnat_actual) : gnat_actual;
4714 tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
4716 /* If it's possible we may need to use this expression twice, make sure
4717 that any side-effects are handled via SAVE_EXPRs; likewise if we need
4718 to force side-effects before the call. */
4719 if (!in_param && !is_by_ref_formal_parm)
4721 tree init = NULL_TREE;
4722 gnu_name = gnat_stabilize_reference (gnu_name, true, &init);
4723 if (init)
4724 gnu_name
4725 = build_compound_expr (TREE_TYPE (gnu_name), init, gnu_name);
4728 /* If we are passing a non-addressable parameter by reference, pass the
4729 address of a copy. In the In Out or Out case, set up to copy back
4730 out after the call. */
4731 if (is_by_ref_formal_parm
4732 && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
4733 && !addressable_p (gnu_name, gnu_name_type))
4735 tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
4737 /* Do not issue warnings for CONSTRUCTORs since this is not a copy
4738 but sort of an instantiation for them. */
4739 if (TREE_CODE (remove_conversions (gnu_name, true)) == CONSTRUCTOR)
4742 /* If the formal is passed by reference, a copy is not allowed. */
4743 else if (TYPE_IS_BY_REFERENCE_P (gnu_formal_type)
4744 || Is_Aliased (gnat_formal))
4745 post_error ("misaligned actual cannot be passed by reference",
4746 gnat_actual);
4748 /* If the mechanism was forced to by-ref, a copy is not allowed but
4749 we issue only a warning because this case is not strict Ada. */
4750 else if (DECL_FORCED_BY_REF_P (gnu_formal))
4751 post_error ("misaligned actual cannot be passed by reference??",
4752 gnat_actual);
4754 /* If the actual type of the object is already the nominal type,
4755 we have nothing to do, except if the size is self-referential
4756 in which case we'll remove the unpadding below. */
4757 if (TREE_TYPE (gnu_name) == gnu_name_type
4758 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
4761 /* Otherwise remove the unpadding from all the objects. */
4762 else if (TREE_CODE (gnu_name) == COMPONENT_REF
4763 && TYPE_IS_PADDING_P
4764 (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
4765 gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
4767 /* Otherwise convert to the nominal type of the object if needed.
4768 There are several cases in which we need to make the temporary
4769 using this type instead of the actual type of the object when
4770 they are distinct, because the expectations of the callee would
4771 otherwise not be met:
4772 - if it's a justified modular type,
4773 - if the actual type is a smaller form of it,
4774 - if it's a smaller form of the actual type. */
4775 else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
4776 && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
4777 || smaller_form_type_p (TREE_TYPE (gnu_name),
4778 gnu_name_type)))
4779 || (INTEGRAL_TYPE_P (gnu_name_type)
4780 && smaller_form_type_p (gnu_name_type,
4781 TREE_TYPE (gnu_name))))
4782 gnu_name = convert (gnu_name_type, gnu_name);
4784 /* If this is an In Out or Out parameter and we're returning a value,
4785 we need to create a temporary for the return value because we must
4786 preserve it before copying back at the very end. */
4787 if (!in_param && returning_value && !gnu_retval)
4789 gnu_retval = create_temporary ("R", gnu_result_type);
4790 DECL_RETURN_VALUE_P (gnu_retval) = 1;
4793 /* If we haven't pushed a binding level, push it now. This will
4794 narrow the lifetime of the temporary we are about to make as
4795 much as possible. */
4796 if (!pushed_binding_level && (!returning_value || gnu_retval))
4798 start_stmt_group ();
4799 gnat_pushlevel ();
4800 pushed_binding_level = true;
4803 /* Create an explicit temporary holding the copy. */
4804 /* Do not initialize it for the _Init parameter of an initialization
4805 procedure since no data is meant to be passed in. */
4806 if (Ekind (gnat_formal) == E_Out_Parameter
4807 && Is_Entity_Name (gnat_subprog)
4808 && Is_Init_Proc (Entity (gnat_subprog)))
4809 gnu_name = gnu_temp = create_temporary ("A", TREE_TYPE (gnu_name));
4811 /* Initialize it on the fly like for an implicit temporary in the
4812 other cases, as we don't necessarily have a statement list. */
4813 else
4815 gnu_temp = create_init_temporary ("A", gnu_name, &gnu_stmt,
4816 gnat_actual);
4817 gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
4818 gnu_temp);
4821 /* Set up to move the copy back to the original if needed. */
4822 if (!in_param)
4824 /* If the original is a COND_EXPR whose first arm isn't meant to
4825 be further used, just deal with the second arm. This is very
4826 likely the conditional expression built for a check. */
4827 if (TREE_CODE (gnu_orig) == COND_EXPR
4828 && TREE_CODE (TREE_OPERAND (gnu_orig, 1)) == COMPOUND_EXPR
4829 && integer_zerop
4830 (TREE_OPERAND (TREE_OPERAND (gnu_orig, 1), 1)))
4831 gnu_orig = TREE_OPERAND (gnu_orig, 2);
4833 gnu_stmt
4834 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig, gnu_temp);
4835 set_expr_location_from_node (gnu_stmt, gnat_node);
4837 append_to_statement_list (gnu_stmt, &gnu_after_list);
4841 /* Start from the real object and build the actual. */
4842 tree gnu_actual = gnu_name;
4844 /* If atomic access is required for an In or In Out actual parameter,
4845 build the atomic load. */
4846 if (is_true_formal_parm
4847 && !is_by_ref_formal_parm
4848 && Ekind (gnat_formal) != E_Out_Parameter
4849 && simple_atomic_access_required_p (gnat_actual, &aa_sync))
4850 gnu_actual = build_atomic_load (gnu_actual, aa_sync);
4852 /* If this was a procedure call, we may not have removed any padding.
4853 So do it here for the part we will use as an input, if any. */
4854 if (Ekind (gnat_formal) != E_Out_Parameter
4855 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4856 gnu_actual
4857 = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
4859 /* Put back the conversion we suppressed above in the computation of the
4860 real object. And even if we didn't suppress any conversion there, we
4861 may have suppressed a conversion to the Etype of the actual earlier,
4862 since the parent is a procedure call, so put it back here. Note that
4863 we might have a dummy type here if the actual is the dereference of a
4864 pointer to it, but that's OK when the formal is passed by reference.
4865 We also do not put back a conversion between an actual and a formal
4866 that are unconstrained array types to avoid creating local bounds. */
4867 tree gnu_actual_type = get_unpadded_type (Etype (gnat_actual));
4868 if (TYPE_IS_DUMMY_P (gnu_actual_type))
4869 gcc_assert (is_true_formal_parm && DECL_BY_REF_P (gnu_formal));
4870 else if (suppress_type_conversion
4871 && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4872 gnu_actual = unchecked_convert (gnu_actual_type, gnu_actual,
4873 No_Truncation (gnat_actual));
4874 else if ((TREE_CODE (TREE_TYPE (gnu_actual)) == UNCONSTRAINED_ARRAY_TYPE
4875 || (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
4876 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))))
4877 && TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4879 else
4880 gnu_actual = convert (gnu_actual_type, gnu_actual);
4882 gigi_checking_assert (!Do_Range_Check (gnat_actual));
4884 /* First see if the parameter is passed by reference. */
4885 if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
4887 if (!in_param)
4889 /* In Out or Out parameters passed by reference don't use the
4890 copy-in/copy-out mechanism so the address of the real object
4891 must be passed to the function. */
4892 gnu_actual = gnu_name;
4894 /* If we have a padded type, be sure we've removed padding. */
4895 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4896 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
4897 gnu_actual);
4899 /* If we have the constructed subtype of an aliased object
4900 with an unconstrained nominal subtype, the type of the
4901 actual includes the template, although it is formally
4902 constrained. So we need to convert it back to the real
4903 constructed subtype to retrieve the constrained part
4904 and takes its address. */
4905 if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
4906 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
4907 && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
4908 && Is_Array_Type (Underlying_Type (Etype (gnat_actual))))
4909 gnu_actual = convert (gnu_actual_type, gnu_actual);
4912 /* There is no need to convert the actual to the formal's type before
4913 taking its address. The only exception is for unconstrained array
4914 types because of the way we build fat pointers. */
4915 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4917 /* Put back the conversion we suppressed above for In Out or Out
4918 parameters, since it may set the bounds of the actual. */
4919 if (!in_param && suppress_type_conversion)
4920 gnu_actual = convert (gnu_actual_type, gnu_actual);
4921 gnu_actual = convert (gnu_formal_type, gnu_actual);
4924 /* Take the address of the object and convert to the proper pointer
4925 type. */
4926 gnu_formal_type = TREE_TYPE (gnu_formal);
4927 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4930 /* Then see if the parameter is an array passed to a foreign convention
4931 subprogram. */
4932 else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
4934 gnu_actual = maybe_padded_object (gnu_actual);
4935 gnu_actual = maybe_unconstrained_array (gnu_actual);
4937 /* Take the address of the object and convert to the proper pointer
4938 type. We'd like to actually compute the address of the beginning
4939 of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
4940 possibility that the ARRAY_REF might return a constant and we'd be
4941 getting the wrong address. Neither approach is exactly correct,
4942 but this is the most likely to work in all cases. */
4943 gnu_formal_type = TREE_TYPE (gnu_formal);
4944 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4947 /* Then see if the parameter is passed by copy. */
4948 else if (is_true_formal_parm)
4950 if (!in_param)
4951 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
4953 gnu_actual = convert (gnu_formal_type, gnu_actual);
4955 /* If this is a front-end built-in function, there is no need to
4956 convert to the type used to pass the argument. */
4957 if (!frontend_builtin)
4958 gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
4961 /* Then see if this is an unnamed parameter in a variadic C function. */
4962 else if (variadic)
4964 /* This is based on the processing done in gnat_to_gnu_param, but
4965 we expect the mechanism to be set in (almost) all cases. */
4966 const Mechanism_Type mech = Mechanism (gnat_formal);
4968 /* Strip off possible padding type. */
4969 if (TYPE_IS_PADDING_P (gnu_formal_type))
4970 gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
4972 /* Arrays are passed as pointers to element type. First check for
4973 unconstrained array and get the underlying array. */
4974 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4975 gnu_formal_type
4976 = TREE_TYPE
4977 (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_formal_type))));
4979 /* Arrays are passed as pointers to element type. */
4980 if (mech != By_Copy && TREE_CODE (gnu_formal_type) == ARRAY_TYPE)
4982 gnu_actual = maybe_padded_object (gnu_actual);
4983 gnu_actual = maybe_unconstrained_array (gnu_actual);
4985 /* Strip off any multi-dimensional entries, then strip
4986 off the last array to get the component type. */
4987 while (TREE_CODE (TREE_TYPE (gnu_formal_type)) == ARRAY_TYPE
4988 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_formal_type)))
4989 gnu_formal_type = TREE_TYPE (gnu_formal_type);
4991 gnu_formal_type = TREE_TYPE (gnu_formal_type);
4992 gnu_formal_type = build_pointer_type (gnu_formal_type);
4993 gnu_actual
4994 = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4997 /* Fat pointers are passed as thin pointers. */
4998 else if (TYPE_IS_FAT_POINTER_P (gnu_formal_type))
4999 gnu_formal_type
5000 = make_type_from_size (gnu_formal_type,
5001 size_int (POINTER_SIZE), 0);
5003 /* If we were requested or muss pass by reference, do so.
5004 If we were requested to pass by copy, do so.
5005 Otherwise, pass In Out or Out parameters or aggregates by
5006 reference. */
5007 else if (mech == By_Reference
5008 || must_pass_by_ref (gnu_formal_type)
5009 || (mech != By_Copy
5010 && (!in_param || AGGREGATE_TYPE_P (gnu_formal_type))))
5012 gnu_formal_type = build_reference_type (gnu_formal_type);
5013 gnu_actual
5014 = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
5017 /* Otherwise pass by copy after applying default C promotions. */
5018 else
5020 if (INTEGRAL_TYPE_P (gnu_formal_type)
5021 && TYPE_PRECISION (gnu_formal_type)
5022 < TYPE_PRECISION (integer_type_node))
5023 gnu_formal_type = integer_type_node;
5025 else if (SCALAR_FLOAT_TYPE_P (gnu_formal_type)
5026 && TYPE_PRECISION (gnu_formal_type)
5027 < TYPE_PRECISION (double_type_node))
5028 gnu_formal_type = double_type_node;
5031 gnu_actual = convert (gnu_formal_type, gnu_actual);
5034 /* If we didn't create a PARM_DECL for the formal, this means that
5035 it is an Out parameter not passed by reference and that need not
5036 be copied in. In this case, the value of the actual need not be
5037 read. However, we still need to make sure that its side-effects
5038 are evaluated before the call, so we evaluate its address. */
5039 else
5041 if (!in_param)
5042 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
5044 if (TREE_SIDE_EFFECTS (gnu_name))
5046 tree addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_name);
5047 append_to_statement_list (addr, &gnu_stmt_list);
5050 continue;
5053 gnu_actual_vec.safe_push (gnu_actual);
5056 if (frontend_builtin)
5058 tree pred_cst = build_int_cst (integer_type_node, PRED_BUILTIN_EXPECT);
5059 enum internal_fn icode = IFN_BUILTIN_EXPECT;
5061 switch (DECL_FE_FUNCTION_CODE (gnu_subprog))
5063 case BUILT_IN_EXPECT:
5064 break;
5065 case BUILT_IN_LIKELY:
5066 gnu_actual_vec.safe_push (boolean_true_node);
5067 break;
5068 case BUILT_IN_UNLIKELY:
5069 gnu_actual_vec.safe_push (boolean_false_node);
5070 break;
5071 default:
5072 gcc_unreachable ();
5075 gnu_actual_vec.safe_push (pred_cst);
5077 gnu_call
5078 = build_call_expr_internal_loc_array (UNKNOWN_LOCATION,
5079 icode,
5080 gnu_result_type,
5081 gnu_actual_vec.length (),
5082 gnu_actual_vec.begin ());
5084 else
5086 gnu_call
5087 = build_call_array_loc (UNKNOWN_LOCATION,
5088 gnu_result_type,
5089 build_unary_op (ADDR_EXPR, NULL_TREE,
5090 gnu_subprog),
5091 gnu_actual_vec.length (),
5092 gnu_actual_vec.begin ());
5093 CALL_EXPR_BY_DESCRIPTOR (gnu_call) = by_descriptor;
5096 set_expr_location_from_node (gnu_call, gnat_node);
5098 /* If we have created a temporary for the return value, initialize it. */
5099 if (gnu_retval)
5101 tree gnu_stmt
5102 = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
5103 set_expr_location_from_node (gnu_stmt, gnat_node);
5104 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
5105 gnu_call = gnu_retval;
5108 /* If this is a subprogram with copy-in/copy-out parameters, we need to
5109 unpack the valued returned from the function into the In Out or Out
5110 parameters. We deal with the function return (if this is an Ada
5111 function) below. */
5112 if (TYPE_CI_CO_LIST (gnu_subprog_type))
5114 /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
5115 copy-out parameters. */
5116 tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
5117 const int length = list_length (gnu_cico_list);
5119 /* The call sequence must contain one and only one call, even though the
5120 function is pure. Save the result into a temporary if needed. */
5121 if (length > 1)
5123 if (!gnu_retval)
5125 tree gnu_stmt;
5126 gnu_call
5127 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
5128 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
5131 gnu_name_list = nreverse (gnu_name_list);
5134 /* The first entry is for the actual return value if this is a
5135 function, so skip it. */
5136 if (function_call)
5137 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
5139 if (Nkind (gnat_subprog) == N_Explicit_Dereference)
5140 gnat_formal = First_Formal_With_Extras (Etype (gnat_subprog));
5141 else
5142 gnat_formal = First_Formal_With_Extras (Entity (gnat_subprog));
5144 for (gnat_actual = First_Actual (gnat_node);
5145 Present (gnat_actual);
5146 gnat_formal = Next_Formal_With_Extras (gnat_formal),
5147 gnat_actual = Next_Actual (gnat_actual))
5148 /* If we are dealing with a copy-in/copy-out parameter, we must
5149 retrieve its value from the record returned in the call. */
5150 if (!(present_gnu_tree (gnat_formal)
5151 && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
5152 && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
5153 || DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))))
5154 && Ekind (gnat_formal) != E_In_Parameter)
5156 /* Get the value to assign to this In Out or Out parameter. It is
5157 either the result of the function if there is only a single such
5158 parameter or the appropriate field from the record returned. */
5159 tree gnu_result
5160 = length == 1
5161 ? gnu_call
5162 : build_component_ref (gnu_call, TREE_PURPOSE (gnu_cico_list),
5163 false);
5165 /* If the actual is a conversion, get the inner expression, which
5166 will be the real destination, and convert the result to the
5167 type of the actual parameter. */
5168 tree gnu_actual
5169 = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
5171 /* If the result is padded, remove the padding. */
5172 gnu_result = maybe_padded_object (gnu_result);
5174 /* If the actual is a type conversion, the real target object is
5175 denoted by the inner Expression and we need to convert the
5176 result to the associated type.
5177 We also need to convert our gnu assignment target to this type
5178 if the corresponding GNU_NAME was constructed from the GNAT
5179 conversion node and not from the inner Expression. */
5180 if (Nkind (gnat_actual) == N_Type_Conversion)
5182 const Node_Id gnat_expr = Expression (gnat_actual);
5184 gigi_checking_assert (!Do_Range_Check (gnat_expr));
5186 gnu_result
5187 = convert_with_check (Etype (gnat_expr), gnu_result,
5188 Do_Overflow_Check (gnat_actual),
5189 Float_Truncate (gnat_actual),
5190 gnat_actual);
5192 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
5193 gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
5196 /* Unchecked conversions as actuals for Out parameters are not
5197 allowed in user code because they are not variables, but do
5198 occur in front-end expansions. The associated GNU_NAME is
5199 always obtained from the inner expression in such cases. */
5200 else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
5201 gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
5202 gnu_result,
5203 No_Truncation (gnat_actual));
5204 else
5206 gigi_checking_assert (!Do_Range_Check (gnat_actual));
5208 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
5209 && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
5210 gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
5213 get_atomic_access (gnat_actual, &aa_type, &aa_sync);
5215 /* If an outer atomic access is required for an actual parameter,
5216 build the load-modify-store sequence. */
5217 if (aa_type == OUTER_ATOMIC)
5218 gnu_result
5219 = build_load_modify_store (gnu_actual, gnu_result, gnat_node);
5221 /* Or else, if a simple atomic access is required, build the atomic
5222 store. */
5223 else if (aa_type == SIMPLE_ATOMIC)
5224 gnu_result
5225 = build_atomic_store (gnu_actual, gnu_result, aa_sync);
5227 /* Otherwise build a regular assignment. */
5228 else
5229 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
5230 gnu_actual, gnu_result);
5232 if (EXPR_P (gnu_result))
5233 set_expr_location_from_node (gnu_result, gnat_node);
5234 append_to_statement_list (gnu_result, &gnu_stmt_list);
5235 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
5236 gnu_name_list = TREE_CHAIN (gnu_name_list);
5240 /* If this is a function call, the result is the call expression unless a
5241 target is specified, in which case we copy the result into the target
5242 and return the assignment statement. */
5243 if (function_call)
5245 /* If this is a function with copy-in/copy-out parameters, extract the
5246 return value from it and update the return type. */
5247 if (TYPE_CI_CO_LIST (gnu_subprog_type))
5249 tree gnu_elmt = TYPE_CI_CO_LIST (gnu_subprog_type);
5250 gnu_call
5251 = build_component_ref (gnu_call, TREE_PURPOSE (gnu_elmt), false);
5252 gnu_result_type = TREE_TYPE (gnu_call);
5255 /* If the function returns an unconstrained array or by direct reference,
5256 we have to dereference the pointer. */
5257 if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
5258 || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
5259 gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
5261 if (gnu_target)
5263 Node_Id gnat_parent = Parent (gnat_node);
5264 enum tree_code op_code;
5266 gigi_checking_assert (!Do_Range_Check (gnat_node));
5268 /* ??? If the return type has variable size, then force the return
5269 slot optimization as we would not be able to create a temporary.
5270 That's what has been done historically. */
5271 if (return_type_with_variable_size_p (gnu_result_type))
5272 op_code = INIT_EXPR;
5274 /* If this is a call to a pure function returning an array of scalar
5275 type, try to apply the return slot optimization. */
5276 else if ((TYPE_READONLY (gnu_subprog_type)
5277 || TYPE_RESTRICT (gnu_subprog_type))
5278 && is_array_of_scalar_type (gnu_result_type)
5279 && TYPE_MODE (gnu_result_type) == BLKmode
5280 && aggregate_value_p (gnu_result_type, gnu_subprog_type)
5281 && return_slot_opt_for_pure_call_p (gnu_target, gnu_call))
5282 op_code = INIT_EXPR;
5284 else
5285 op_code = MODIFY_EXPR;
5287 /* Use the required method to move the result to the target. */
5288 if (atomic_access == OUTER_ATOMIC)
5289 gnu_call
5290 = build_load_modify_store (gnu_target, gnu_call, gnat_node);
5291 else if (atomic_access == SIMPLE_ATOMIC)
5292 gnu_call = build_atomic_store (gnu_target, gnu_call, atomic_sync);
5293 else
5294 gnu_call
5295 = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
5297 if (EXPR_P (gnu_call))
5298 set_expr_location_from_node (gnu_call, gnat_parent);
5299 append_to_statement_list (gnu_call, &gnu_stmt_list);
5301 else
5302 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5305 /* Otherwise, if this is a procedure call statement without copy-in/copy-out
5306 parameters, the result is just the call statement. */
5307 else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
5308 append_to_statement_list (gnu_call, &gnu_stmt_list);
5310 /* Finally, add the copy back statements, if any. */
5311 append_to_statement_list (gnu_after_list, &gnu_stmt_list);
5313 if (went_into_elab_proc)
5314 current_function_decl = NULL_TREE;
5316 /* If we have pushed a binding level, pop it and finish up the enclosing
5317 statement group. */
5318 if (pushed_binding_level)
5320 add_stmt (gnu_stmt_list);
5321 gnat_poplevel ();
5322 gnu_result = end_stmt_group ();
5325 /* Otherwise, retrieve the statement list, if any. */
5326 else if (gnu_stmt_list)
5327 gnu_result = gnu_stmt_list;
5329 /* Otherwise, just return the call expression. */
5330 else
5331 return gnu_call;
5333 /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
5334 But first simplify if we have only one statement in the list. */
5335 if (returning_value)
5337 tree first = expr_first (gnu_result), last = expr_last (gnu_result);
5338 if (first == last)
5339 gnu_result = first;
5340 gnu_result
5341 = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
5344 return gnu_result;
5347 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an
5348 N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned. */
5350 static tree
5351 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
5353 /* If just annotating, ignore all EH and cleanups. */
5354 const bool gcc_eh
5355 = !type_annotate_only && Present (Exception_Handlers (gnat_node));
5356 const bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
5357 const bool binding_for_block = (at_end || gcc_eh);
5358 tree gnu_inner_block; /* The statement(s) for the block itself. */
5359 tree gnu_result;
5360 Node_Id gnat_temp;
5362 /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes.
5363 To call the GCC mechanism, we call add_cleanup, and when we leave the
5364 binding, end_stmt_group will create the TRY_FINALLY_EXPR construct.
5366 ??? The region level calls down there have been specifically put in place
5367 for a ZCX context and currently the order in which things are emitted
5368 (region/handlers) is different from the SJLJ case. Instead of putting
5369 other calls with different conditions at other places for the SJLJ case,
5370 it seems cleaner to reorder things for the SJLJ case and generalize the
5371 condition to make it not ZCX specific.
5373 If there are any exceptions or cleanup processing involved, we need an
5374 outer statement group and binding level. */
5375 if (binding_for_block)
5377 start_stmt_group ();
5378 gnat_pushlevel ();
5381 /* If we are to call a function when exiting this block, add a cleanup
5382 to the binding level we made above. Note that add_cleanup is FIFO
5383 so we must register this cleanup after the EH cleanup just above. */
5384 if (at_end)
5386 tree proc_decl = gnat_to_gnu (At_End_Proc (gnat_node));
5388 /* When not optimizing, disable inlining of finalizers as this can
5389 create a more complex CFG in the parent function. */
5390 if (!optimize || optimize_debug)
5391 DECL_DECLARED_INLINE_P (proc_decl) = 0;
5393 /* If there is no end label attached, we use the location of the At_End
5394 procedure because Expand_Cleanup_Actions might reset the location of
5395 the enclosing construct to that of an inner statement. */
5396 add_cleanup (build_call_n_expr (proc_decl, 0),
5397 Present (End_Label (gnat_node))
5398 ? End_Label (gnat_node) : At_End_Proc (gnat_node));
5401 /* Now build the tree for the declarations and statements inside this
5402 block. */
5403 start_stmt_group ();
5405 if (Present (First_Real_Statement (gnat_node)))
5406 process_decls (Statements (gnat_node), Empty,
5407 First_Real_Statement (gnat_node), true, true);
5409 /* Generate code for each statement in the block. */
5410 for (gnat_temp = (Present (First_Real_Statement (gnat_node))
5411 ? First_Real_Statement (gnat_node)
5412 : First (Statements (gnat_node)));
5413 Present (gnat_temp); gnat_temp = Next (gnat_temp))
5414 add_stmt (gnat_to_gnu (gnat_temp));
5416 gnu_inner_block = end_stmt_group ();
5418 if (gcc_eh)
5420 tree gnu_handlers;
5421 location_t locus;
5423 /* First make a block containing the handlers. */
5424 start_stmt_group ();
5425 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
5426 Present (gnat_temp);
5427 gnat_temp = Next_Non_Pragma (gnat_temp))
5428 add_stmt (gnat_to_gnu (gnat_temp));
5429 gnu_handlers = end_stmt_group ();
5431 /* Now make the TRY_CATCH_EXPR for the block. */
5432 gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
5433 gnu_inner_block, gnu_handlers);
5434 /* Set a location. We need to find a unique location for the dispatching
5435 code, otherwise we can get coverage or debugging issues. Try with
5436 the location of the end label. */
5437 if (Present (End_Label (gnat_node))
5438 && Sloc_to_locus (Sloc (End_Label (gnat_node)), &locus))
5439 SET_EXPR_LOCATION (gnu_result, locus);
5440 else
5441 /* Clear column information so that the exception handler of an
5442 implicit transient block does not incorrectly inherit the slocs
5443 of a decision, which would otherwise confuse control flow based
5444 coverage analysis tools. */
5445 set_expr_location_from_node (gnu_result, gnat_node, true);
5447 else
5448 gnu_result = gnu_inner_block;
5450 /* Now close our outer block, if we had to make one. */
5451 if (binding_for_block)
5453 add_stmt (gnu_result);
5454 gnat_poplevel ();
5455 gnu_result = end_stmt_group ();
5458 return gnu_result;
5461 /* Return true if no statement in GNAT_LIST can alter the control flow. */
5463 static bool
5464 stmt_list_cannot_alter_control_flow_p (List_Id gnat_list)
5466 if (No (gnat_list))
5467 return true;
5469 /* This is very conservative, we reject everything except for simple
5470 assignments between identifiers or literals. */
5471 for (Node_Id gnat_node = First (gnat_list);
5472 Present (gnat_node);
5473 gnat_node = Next (gnat_node))
5475 if (Nkind (gnat_node) != N_Assignment_Statement)
5476 return false;
5478 if (Nkind (Name (gnat_node)) != N_Identifier)
5479 return false;
5481 Node_Kind nkind = Nkind (Expression (gnat_node));
5482 if (nkind != N_Identifier
5483 && nkind != N_Integer_Literal
5484 && nkind != N_Real_Literal)
5485 return false;
5488 return true;
5491 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Exception_Handler,
5492 to a GCC tree, which is returned. */
5494 static tree
5495 Exception_Handler_to_gnu (Node_Id gnat_node)
5497 tree gnu_etypes_list = NULL_TREE;
5499 /* We build a TREE_LIST of nodes representing what exception types this
5500 handler can catch, with special cases for others and all others cases.
5502 Each exception type is actually identified by a pointer to the exception
5503 id, or to a dummy object for "others" and "all others". */
5504 for (Node_Id gnat_temp = First (Exception_Choices (gnat_node));
5505 gnat_temp;
5506 gnat_temp = Next (gnat_temp))
5508 tree gnu_expr, gnu_etype;
5510 if (Nkind (gnat_temp) == N_Others_Choice)
5512 gnu_expr = All_Others (gnat_temp) ? all_others_decl : others_decl;
5513 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
5515 else if (Nkind (gnat_temp) == N_Identifier
5516 || Nkind (gnat_temp) == N_Expanded_Name)
5518 Entity_Id gnat_ex_id = Entity (gnat_temp);
5520 /* Exception may be a renaming. Recover original exception which is
5521 the one elaborated and registered. */
5522 if (Present (Renamed_Object (gnat_ex_id)))
5523 gnat_ex_id = Renamed_Object (gnat_ex_id);
5525 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, false);
5526 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
5528 else
5529 gcc_unreachable ();
5531 /* The GCC interface expects NULL to be passed for catch all handlers, so
5532 it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
5533 is integer_zero_node. It would not work, however, because GCC's
5534 notion of "catch all" is stronger than our notion of "others". Until
5535 we correctly use the cleanup interface as well, doing that would
5536 prevent the "all others" handlers from being seen, because nothing
5537 can be caught beyond a catch all from GCC's point of view. */
5538 gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
5541 start_stmt_group ();
5542 gnat_pushlevel ();
5544 /* Expand a call to the begin_handler hook at the beginning of the
5545 handler, and arrange for a call to the end_handler hook to occur
5546 on every possible exit path. GDB sets a breakpoint in the
5547 begin_handler for catchpoints.
5549 A v1 begin handler saves the cleanup from the exception object,
5550 and marks the exception as in use, so that it will not be
5551 released by other handlers. A v1 end handler restores the
5552 cleanup and releases the exception object, unless it is still
5553 claimed, or the exception is being propagated (reraised).
5555 __builtin_eh_pointer references the exception occurrence being
5556 handled or propagated. Within the handler region, it is the
5557 former, but within the else branch of the EH_ELSE_EXPR, i.e. the
5558 exceptional cleanup path, it is the latter, so we must save the
5559 occurrence being handled early on, so that, should an exception
5560 be (re)raised, we can release the current exception, or figure
5561 out we're not to release it because we're propagating a reraise
5562 thereof.
5564 We use local variables to retrieve the incoming value at handler
5565 entry time (EXPTR), the saved cleanup (EXCLN) and the token
5566 (EXVTK), and reuse them to feed the end_handler hook's argument
5567 at exit. */
5569 /* CODE: void *EXPTR = __builtin_eh_pointer (0); */
5570 tree gnu_current_exc_ptr
5571 = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
5572 1, integer_zero_node);
5573 tree exc_ptr
5574 = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
5575 ptr_type_node, gnu_current_exc_ptr,
5576 true, false, false, false, false, true, true,
5577 NULL, gnat_node);
5579 tree prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
5580 gnu_incoming_exc_ptr = exc_ptr;
5582 /* begin_handler_decl must not throw, so we can use it as an
5583 initializer for a variable used in cleanups.
5585 CODE: void *EXCLN = __gnat_begin_handler_v1 (EXPTR); */
5586 tree exc_cleanup
5587 = create_var_decl (get_identifier ("EXCLN"), NULL_TREE,
5588 ptr_type_node,
5589 build_call_n_expr (begin_handler_decl, 1,
5590 exc_ptr),
5591 true, false, false, false, false,
5592 true, true, NULL, gnat_node);
5594 /* Declare and initialize the choice parameter, if present. */
5595 if (Present (Choice_Parameter (gnat_node)))
5597 tree gnu_param
5598 = gnat_to_gnu_entity (Choice_Parameter (gnat_node), NULL_TREE, true);
5600 /* CODE: __gnat_set_exception_parameter (&choice_param, EXPTR); */
5601 add_stmt (build_call_n_expr
5602 (set_exception_parameter_decl, 2,
5603 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_param),
5604 gnu_incoming_exc_ptr));
5607 /* CODE: <handler proper> */
5608 add_stmt_list (Statements (gnat_node));
5610 tree call = build_call_n_expr (end_handler_decl, 3,
5611 exc_ptr,
5612 exc_cleanup,
5613 null_pointer_node);
5614 /* If the handler can only end by falling off the end, don't bother
5615 with cleanups. */
5616 if (stmt_list_cannot_alter_control_flow_p (Statements (gnat_node)))
5617 /* CODE: __gnat_end_handler_v1 (EXPTR, EXCLN, NULL); */
5618 add_stmt_with_node (call, gnat_node);
5619 /* Otherwise, all of the above is after
5620 CODE: try {
5622 The call above will appear after
5623 CODE: } finally {
5625 And the code below will appear after
5626 CODE: } else {
5628 The else block to a finally block is taken instead of the finally
5629 block when an exception propagates out of the try block. */
5630 else
5632 start_stmt_group ();
5633 gnat_pushlevel ();
5634 /* CODE: void *EXPRP = __builtin_eh_handler (0); */
5635 tree prop_ptr
5636 = create_var_decl (get_identifier ("EXPRP"), NULL_TREE,
5637 ptr_type_node,
5638 build_call_expr (builtin_decl_explicit
5639 (BUILT_IN_EH_POINTER),
5640 1, integer_zero_node),
5641 true, false, false, false, false,
5642 true, true, NULL, gnat_node);
5644 /* CODE: __gnat_end_handler_v1 (EXPTR, EXCLN, EXPRP); */
5645 tree ecall = build_call_n_expr (end_handler_decl, 3,
5646 exc_ptr,
5647 exc_cleanup,
5648 prop_ptr);
5650 add_stmt_with_node (ecall, gnat_node);
5652 /* CODE: } */
5653 gnat_poplevel ();
5654 tree eblk = end_stmt_group ();
5655 tree ehls = build2 (EH_ELSE_EXPR, void_type_node, call, eblk);
5656 add_cleanup (ehls, gnat_node);
5659 gnat_poplevel ();
5661 gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
5663 return
5664 build2 (CATCH_EXPR, void_type_node, gnu_etypes_list, end_stmt_group ());
5667 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Compilation_Unit. */
5669 static void
5670 Compilation_Unit_to_gnu (Node_Id gnat_node)
5672 const Node_Id gnat_unit = Unit (gnat_node);
5673 const bool body_p = (Nkind (gnat_unit) == N_Package_Body
5674 || Nkind (gnat_unit) == N_Subprogram_Body);
5675 const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
5676 Entity_Id gnat_entity;
5677 Node_Id gnat_pragma, gnat_iter;
5678 /* Make the decl for the elaboration procedure. Emit debug info for it, so
5679 that users can break into their elaboration code in debuggers. Kludge:
5680 don't consider it as a definition so that we have a line map for its
5681 body, but no subprogram description in debug info. In addition, don't
5682 qualify it as artificial, even though it is not a user subprogram per se,
5683 in particular for specs. Unlike, say, clones created internally by the
5684 compiler, this subprogram materializes specific user code and flagging it
5685 artificial would take elab code away from gcov's analysis. */
5686 tree gnu_elab_proc_decl
5687 = create_subprog_decl
5688 (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
5689 NULL_TREE, void_ftype, NULL_TREE,
5690 is_default, true, false, false, true, false, NULL, gnat_unit);
5691 struct elab_info *info;
5693 vec_safe_push (gnu_elab_proc_stack, gnu_elab_proc_decl);
5694 DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
5696 /* Initialize the information structure for the function. */
5697 allocate_struct_function (gnu_elab_proc_decl, false);
5698 set_cfun (NULL);
5700 current_function_decl = NULL_TREE;
5702 start_stmt_group ();
5703 gnat_pushlevel ();
5705 /* For a body, first process the spec if there is one. */
5706 if (Nkind (gnat_unit) == N_Package_Body
5707 || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
5708 add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
5710 if (type_annotate_only && gnat_node == Cunit (Main_Unit))
5712 elaborate_all_entities (gnat_node);
5714 if (Nkind (gnat_unit) == N_Subprogram_Declaration
5715 || Nkind (gnat_unit) == N_Generic_Package_Declaration
5716 || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
5717 return;
5720 /* Then process any pragmas and declarations preceding the unit. */
5721 for (gnat_pragma = First (Context_Items (gnat_node));
5722 Present (gnat_pragma);
5723 gnat_pragma = Next (gnat_pragma))
5724 if (Nkind (gnat_pragma) == N_Pragma)
5725 add_stmt (gnat_to_gnu (gnat_pragma));
5726 process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
5727 true, true);
5729 /* Process the unit itself. */
5730 add_stmt (gnat_to_gnu (gnat_unit));
5732 /* Generate code for all the inlined subprograms. */
5733 for (gnat_entity = First_Inlined_Subprogram (gnat_node);
5734 Present (gnat_entity);
5735 gnat_entity = Next_Inlined_Subprogram (gnat_entity))
5737 Node_Id gnat_body;
5739 /* Without optimization, process only the required subprograms. */
5740 if (!optimize && !Has_Pragma_Inline_Always (gnat_entity))
5741 continue;
5743 /* The set of inlined subprograms is computed from data recorded early
5744 during expansion and it can be a strict superset of the final set
5745 computed after semantic analysis, for example if a call to such a
5746 subprogram occurs in a pragma Assert and assertions are disabled.
5747 In that case, semantic analysis resets Is_Public to false but the
5748 entry for the subprogram in the inlining tables is stalled. */
5749 if (!Is_Public (gnat_entity))
5750 continue;
5752 gnat_body = Parent (Declaration_Node (gnat_entity));
5753 if (Nkind (gnat_body) != N_Subprogram_Body)
5755 /* ??? This happens when only the spec of a package is provided. */
5756 if (No (Corresponding_Body (gnat_body)))
5757 continue;
5759 gnat_body
5760 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
5763 /* Define the entity first so we set DECL_EXTERNAL. */
5764 gnat_to_gnu_entity (gnat_entity, NULL_TREE, false);
5765 add_stmt (gnat_to_gnu (gnat_body));
5768 /* Process any pragmas and actions following the unit. */
5769 add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
5770 add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
5771 finalize_from_limited_with ();
5773 /* Then process the expressions of pragma Compile_Time_{Error|Warning} to
5774 annotate types referenced therein if they have not been annotated. */
5775 for (int i = 0; gnat_compile_time_expr_list.iterate (i, &gnat_iter); i++)
5776 (void) gnat_to_gnu_external (gnat_iter);
5777 gnat_compile_time_expr_list.release ();
5779 /* Save away what we've made so far and finish it up. */
5780 set_current_block_context (gnu_elab_proc_decl);
5781 gnat_poplevel ();
5782 DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
5783 set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
5784 gnu_elab_proc_stack->pop ();
5786 /* Record this potential elaboration procedure for later processing. */
5787 info = ggc_alloc<elab_info> ();
5788 info->next = elab_info_list;
5789 info->elab_proc = gnu_elab_proc_decl;
5790 info->gnat_node = gnat_node;
5791 elab_info_list = info;
5793 /* Force the processing for all nodes that remain in the queue. */
5794 process_deferred_decl_context (true);
5797 /* Mark COND, a boolean expression, as predicating a call to a noreturn
5798 function, i.e. predict that it is very likely false, and return it.
5800 The compiler will automatically predict the last edge leading to a call
5801 to a noreturn function as very unlikely taken. This function makes it
5802 possible to extend the prediction to predecessors in case the condition
5803 is made up of several short-circuit operators. */
5805 static tree
5806 build_noreturn_cond (tree cond)
5808 tree pred_cst = build_int_cst (integer_type_node, PRED_NORETURN);
5809 return
5810 build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_BUILTIN_EXPECT,
5811 boolean_type_node, 3, cond,
5812 boolean_false_node, pred_cst);
5815 /* Subroutine of gnat_to_gnu to translate GNAT_RANGE, a node representing a
5816 range of values, into GNU_LOW and GNU_HIGH bounds. */
5818 static void
5819 Range_to_gnu (Node_Id gnat_range, tree *gnu_low, tree *gnu_high)
5821 /* GNAT_RANGE is either an N_Range or an identifier denoting a subtype. */
5822 switch (Nkind (gnat_range))
5824 case N_Range:
5825 *gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
5826 *gnu_high = gnat_to_gnu (High_Bound (gnat_range));
5827 break;
5829 case N_Expanded_Name:
5830 case N_Identifier:
5832 tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
5833 tree gnu_range_base_type = get_base_type (gnu_range_type);
5835 *gnu_low
5836 = convert (gnu_range_base_type, TYPE_MIN_VALUE (gnu_range_type));
5837 *gnu_high
5838 = convert (gnu_range_base_type, TYPE_MAX_VALUE (gnu_range_type));
5840 break;
5842 default:
5843 gcc_unreachable ();
5847 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Raise_xxx_Error,
5848 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to
5849 where we should place the result type. */
5851 static tree
5852 Raise_Error_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
5854 const Node_Kind kind = Nkind (gnat_node);
5855 const Node_Id gnat_cond = Condition (gnat_node);
5856 const int reason = UI_To_Int (Reason (gnat_node));
5857 const bool with_extra_info
5858 = Exception_Extra_Info
5859 && !No_Exception_Handlers_Set ()
5860 && No (get_exception_label (kind));
5861 tree gnu_result = NULL_TREE, gnu_cond = NULL_TREE;
5862 Node_Id gnat_rcond;
5864 /* The following processing is not required for correctness. Its purpose is
5865 to give more precise error messages and to record some information. */
5866 switch (reason)
5868 case CE_Access_Check_Failed:
5869 if (with_extra_info)
5870 gnu_result = build_call_raise_column (reason, gnat_node, kind);
5871 break;
5873 case CE_Index_Check_Failed:
5874 case CE_Range_Check_Failed:
5875 case CE_Invalid_Data:
5876 if (No (gnat_cond) || Nkind (gnat_cond) != N_Op_Not)
5877 break;
5878 gnat_rcond = Right_Opnd (gnat_cond);
5879 if (Nkind (gnat_rcond) == N_In
5880 || Nkind (gnat_rcond) == N_Op_Ge
5881 || Nkind (gnat_rcond) == N_Op_Le)
5883 const Node_Id gnat_index = Left_Opnd (gnat_rcond);
5884 const Node_Id gnat_type = Etype (gnat_index);
5885 tree gnu_index = gnat_to_gnu (gnat_index);
5886 tree gnu_type = get_unpadded_type (gnat_type);
5887 tree gnu_low_bound, gnu_high_bound, disp;
5888 struct loop_info_d *loop;
5889 bool neg_p;
5891 switch (Nkind (gnat_rcond))
5893 case N_In:
5894 Range_to_gnu (Right_Opnd (gnat_rcond),
5895 &gnu_low_bound, &gnu_high_bound);
5896 break;
5898 case N_Op_Ge:
5899 gnu_low_bound = gnat_to_gnu (Right_Opnd (gnat_rcond));
5900 gnu_high_bound = TYPE_MAX_VALUE (gnu_type);
5901 break;
5903 case N_Op_Le:
5904 gnu_low_bound = TYPE_MIN_VALUE (gnu_type);
5905 gnu_high_bound = gnat_to_gnu (Right_Opnd (gnat_rcond));
5906 break;
5908 default:
5909 gcc_unreachable ();
5912 gnu_type = maybe_character_type (gnu_type);
5913 if (TREE_TYPE (gnu_index) != gnu_type)
5915 gnu_low_bound = convert (gnu_type, gnu_low_bound);
5916 gnu_high_bound = convert (gnu_type, gnu_high_bound);
5917 gnu_index = convert (gnu_type, gnu_index);
5920 if (with_extra_info
5921 && Known_Esize (gnat_type)
5922 && UI_To_Int (Esize (gnat_type)) <= 32)
5923 gnu_result
5924 = build_call_raise_range (reason, gnat_node, kind, gnu_index,
5925 gnu_low_bound, gnu_high_bound);
5927 /* If optimization is enabled and we are inside a loop, we try to
5928 compute invariant conditions for checks applied to the iteration
5929 variable, i.e. conditions that are independent of the variable
5930 and necessary in order for the checks to fail in the course of
5931 some iteration. If we succeed, we consider an alternative:
5933 1. If loop unswitching is enabled, we prepend these conditions
5934 to the original conditions of the checks. This will make it
5935 possible for the loop unswitching pass to replace the loop
5936 with two loops, one of which has the checks eliminated and
5937 the other has the original checks reinstated, and a prologue
5938 implementing a run-time selection. The former loop will be
5939 for example suitable for vectorization.
5941 2. Otherwise, we instead append the conditions to the original
5942 conditions of the checks. At worse, if the conditions cannot
5943 be evaluated at compile time, they will be evaluated as true
5944 at run time only when the checks have already failed, thus
5945 contributing negatively only to the size of the executable.
5946 But the hope is that these invariant conditions be evaluated
5947 at compile time to false, thus taking away the entire checks
5948 with them. */
5949 if (optimize
5950 && inside_loop_p ()
5951 && (!gnu_low_bound
5952 || (gnu_low_bound = gnat_invariant_expr (gnu_low_bound)))
5953 && (!gnu_high_bound
5954 || (gnu_high_bound = gnat_invariant_expr (gnu_high_bound)))
5955 && (loop = find_loop_for (gnu_index, &disp, &neg_p)))
5957 struct range_check_info_d *rci = ggc_alloc<range_check_info_d> ();
5958 rci->low_bound = gnu_low_bound;
5959 rci->high_bound = gnu_high_bound;
5960 rci->disp = disp;
5961 rci->neg_p = neg_p;
5962 rci->type = gnu_type;
5963 rci->inserted_cond
5964 = build1 (SAVE_EXPR, boolean_type_node, boolean_true_node);
5965 vec_safe_push (loop->checks, rci);
5966 gnu_cond = build_noreturn_cond (gnat_to_gnu (gnat_cond));
5967 if (optimize >= 3)
5968 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5969 boolean_type_node,
5970 rci->inserted_cond,
5971 gnu_cond);
5972 else
5973 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5974 boolean_type_node,
5975 gnu_cond,
5976 rci->inserted_cond);
5979 break;
5981 default:
5982 break;
5985 /* The following processing does the real work, but we must nevertheless make
5986 sure not to override the result of the previous processing. */
5987 if (!gnu_result)
5988 gnu_result = build_call_raise (reason, gnat_node, kind);
5989 set_expr_location_from_node (gnu_result, gnat_node);
5991 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5993 /* If the type is VOID, this is a statement, so we need to generate the code
5994 for the call. Handle a condition, if there is one. */
5995 if (VOID_TYPE_P (*gnu_result_type_p))
5997 if (Present (gnat_cond))
5999 if (!gnu_cond)
6000 gnu_cond = gnat_to_gnu (gnat_cond);
6001 if (integer_zerop (gnu_cond))
6002 return alloc_stmt_list ();
6003 gnu_result = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
6004 alloc_stmt_list ());
6007 else
6009 /* The condition field must not be present when the node is used as an
6010 expression form. */
6011 gigi_checking_assert (No (gnat_cond));
6012 gnu_result = build1 (NULL_EXPR, *gnu_result_type_p, gnu_result);
6015 return gnu_result;
6018 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
6019 parameter of a call. */
6021 static bool
6022 lhs_or_actual_p (Node_Id gnat_node)
6024 const Node_Id gnat_parent = Parent (gnat_node);
6025 const Node_Kind kind = Nkind (gnat_parent);
6027 if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
6028 return true;
6030 if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
6031 && Name (gnat_parent) != gnat_node)
6032 return true;
6034 if (kind == N_Parameter_Association)
6035 return true;
6037 return false;
6040 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
6041 of an assignment or an actual parameter of a call. */
6043 static bool
6044 present_in_lhs_or_actual_p (Node_Id gnat_node)
6046 if (lhs_or_actual_p (gnat_node))
6047 return true;
6049 const Node_Kind kind = Nkind (Parent (gnat_node));
6051 if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
6052 && lhs_or_actual_p (Parent (gnat_node)))
6053 return true;
6055 return false;
6058 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
6059 as gigi is concerned. This is used to avoid conversions on the LHS. */
6061 static bool
6062 unchecked_conversion_nop (Node_Id gnat_node)
6064 Entity_Id from_type, to_type;
6066 /* The conversion must be on the LHS of an assignment or an actual parameter
6067 of a call. Otherwise, even if the conversion was essentially a no-op, it
6068 could de facto ensure type consistency and this should be preserved. */
6069 if (!lhs_or_actual_p (gnat_node))
6070 return false;
6072 from_type = Etype (Expression (gnat_node));
6074 /* We're interested in artificial conversions generated by the front-end
6075 to make private types explicit, e.g. in Expand_Assign_Array. */
6076 if (!Is_Private_Type (from_type))
6077 return false;
6079 from_type = Underlying_Type (from_type);
6080 to_type = Etype (gnat_node);
6082 /* The direct conversion to the underlying type is a no-op. */
6083 if (to_type == from_type)
6084 return true;
6086 /* For an array subtype, the conversion to the PAIT is a no-op. */
6087 if (Ekind (from_type) == E_Array_Subtype
6088 && to_type == Packed_Array_Impl_Type (from_type))
6089 return true;
6091 /* For a record subtype, the conversion to the type is a no-op. */
6092 if (Ekind (from_type) == E_Record_Subtype
6093 && to_type == Etype (from_type))
6094 return true;
6096 return false;
6099 /* Return true if GNAT_NODE represents a statement. */
6101 static bool
6102 statement_node_p (Node_Id gnat_node)
6104 const Node_Kind kind = Nkind (gnat_node);
6106 if (kind == N_Label)
6107 return true;
6109 if (IN (kind, N_Statement_Other_Than_Procedure_Call))
6110 return true;
6112 if (kind == N_Procedure_Call_Statement)
6113 return true;
6115 if (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void)
6116 return true;
6118 return false;
6121 /* This function is the driver of the GNAT to GCC tree transformation process.
6122 It is the entry point of the tree transformer. GNAT_NODE is the root of
6123 some GNAT tree. Return the root of the corresponding GCC tree. If this
6124 is an expression, return the GCC equivalent of the expression. If this
6125 is a statement, return the statement or add it to the current statement
6126 group, in which case anything returned is to be interpreted as occurring
6127 after anything added. */
6129 tree
6130 gnat_to_gnu (Node_Id gnat_node)
6132 const Node_Kind kind = Nkind (gnat_node);
6133 tree gnu_result = error_mark_node; /* Default to no value. */
6134 tree gnu_result_type = void_type_node;
6135 tree gnu_expr, gnu_lhs, gnu_rhs;
6136 Node_Id gnat_temp;
6137 atomic_acces_t aa_type;
6138 bool went_into_elab_proc;
6139 bool aa_sync;
6141 /* Save node number for error message and set location information. */
6142 Current_Error_Node = gnat_node;
6143 Sloc_to_locus (Sloc (gnat_node), &input_location);
6145 /* If we are only annotating types and this node is a statement, return
6146 an empty statement list. */
6147 if (type_annotate_only && statement_node_p (gnat_node))
6148 return alloc_stmt_list ();
6150 /* If we are only annotating types and this node is a subexpression, return
6151 a NULL_EXPR, but filter out nodes appearing in the expressions attached
6152 to packed array implementation types. */
6153 if (type_annotate_only
6154 && IN (kind, N_Subexpr)
6155 && !(((IN (kind, N_Op) && kind != N_Op_Expon)
6156 || kind == N_Type_Conversion)
6157 && Is_Integer_Type (Etype (gnat_node)))
6158 && !(kind == N_Attribute_Reference
6159 && (Get_Attribute_Id (Attribute_Name (gnat_node)) == Attr_Length
6160 || Get_Attribute_Id (Attribute_Name (gnat_node)) == Attr_Size)
6161 && Is_Constrained (Etype (Prefix (gnat_node)))
6162 && !Is_Constr_Subt_For_U_Nominal (Etype (Prefix (gnat_node))))
6163 && kind != N_Expanded_Name
6164 && kind != N_Identifier
6165 && !Compile_Time_Known_Value (gnat_node))
6166 return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
6167 build_call_raise (CE_Range_Check_Failed, gnat_node,
6168 N_Raise_Constraint_Error));
6170 /* If this is a statement and we are at top level, it must be part of the
6171 elaboration procedure, so mark us as being in that procedure. */
6172 if ((statement_node_p (gnat_node)
6173 || kind == N_Handled_Sequence_Of_Statements
6174 || kind == N_Implicit_Label_Declaration)
6175 && !current_function_decl)
6177 current_function_decl = get_elaboration_procedure ();
6178 went_into_elab_proc = true;
6180 else
6181 went_into_elab_proc = false;
6183 switch (kind)
6185 /********************************/
6186 /* Chapter 2: Lexical Elements */
6187 /********************************/
6189 case N_Identifier:
6190 case N_Expanded_Name:
6191 case N_Operator_Symbol:
6192 case N_Defining_Identifier:
6193 case N_Defining_Operator_Symbol:
6194 gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
6196 /* If atomic access is required on the RHS, build the atomic load. */
6197 if (simple_atomic_access_required_p (gnat_node, &aa_sync)
6198 && !present_in_lhs_or_actual_p (gnat_node))
6199 gnu_result = build_atomic_load (gnu_result, aa_sync);
6200 break;
6202 case N_Integer_Literal:
6204 tree gnu_type;
6206 /* Get the type of the result, looking inside any padding and
6207 justified modular types. Then get the value in that type. */
6208 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6210 if (TREE_CODE (gnu_type) == RECORD_TYPE
6211 && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
6212 gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
6214 gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
6216 /* If the result overflows (meaning it doesn't fit in its base type),
6217 abort, unless this is for a named number because that's not fatal.
6218 We would like to check that the value is within the range of the
6219 subtype, but that causes problems with subtypes whose usage will
6220 raise Constraint_Error and also with biased representation. */
6221 if (TREE_OVERFLOW (gnu_result))
6223 if (Nkind (Parent (gnat_node)) == N_Number_Declaration)
6224 gnu_result = error_mark_node;
6225 else
6226 gcc_unreachable ();
6229 break;
6231 case N_Character_Literal:
6232 /* If a Entity is present, it means that this was one of the
6233 literals in a user-defined character type. In that case,
6234 just return the value in the CONST_DECL. Otherwise, use the
6235 character code. In that case, the base type should be an
6236 INTEGER_TYPE, but we won't bother checking for that. */
6237 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6238 if (Present (Entity (gnat_node)))
6239 gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
6240 else
6241 gnu_result
6242 = build_int_cst (gnu_result_type,
6243 UI_To_CC (Char_Literal_Value (gnat_node)));
6244 break;
6246 case N_Real_Literal:
6247 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6249 /* If this is of a fixed-point type, the value we want is the value of
6250 the corresponding integer. */
6251 if (Is_Fixed_Point_Type (Underlying_Type (Etype (gnat_node))))
6253 gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
6254 gnu_result_type);
6255 gcc_assert (!TREE_OVERFLOW (gnu_result));
6258 else
6260 Ureal ur_realval = Realval (gnat_node);
6262 /* First convert the value to a machine number if it isn't already.
6263 That will force the base to 2 for non-zero values and simplify
6264 the rest of the logic. */
6265 if (!Is_Machine_Number (gnat_node))
6266 ur_realval
6267 = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
6268 ur_realval, Round_Even, gnat_node);
6270 if (UR_Is_Zero (ur_realval))
6271 gnu_result = build_real (gnu_result_type, dconst0);
6272 else
6274 REAL_VALUE_TYPE tmp;
6276 gnu_result = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
6278 /* The base must be 2 as Machine guarantees this, so we scale
6279 the value, which we know can fit in the mantissa of the type
6280 (hence the use of that type above). */
6281 gcc_assert (Rbase (ur_realval) == 2);
6282 real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
6283 - UI_To_Int (Denominator (ur_realval)));
6284 gnu_result = build_real (gnu_result_type, tmp);
6287 /* Now see if we need to negate the result. Do it this way to
6288 properly handle -0. */
6289 if (UR_Is_Negative (Realval (gnat_node)))
6290 gnu_result
6291 = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
6292 gnu_result);
6295 break;
6297 case N_String_Literal:
6298 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6299 if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
6301 String_Id gnat_string = Strval (gnat_node);
6302 int length = String_Length (gnat_string);
6303 int i;
6304 char *string;
6305 if (length >= ALLOCA_THRESHOLD)
6306 string = XNEWVEC (char, length);
6307 else
6308 string = (char *) alloca (length);
6310 /* Build the string with the characters in the literal. Note
6311 that Ada strings are 1-origin. */
6312 for (i = 0; i < length; i++)
6313 string[i] = Get_String_Char (gnat_string, i + 1);
6315 gnu_result = build_string (length, string);
6317 /* Strings in GCC don't normally have types, but we want
6318 this to not be converted to the array type. */
6319 TREE_TYPE (gnu_result) = gnu_result_type;
6321 if (length >= ALLOCA_THRESHOLD)
6322 free (string);
6324 else
6326 /* Build a list consisting of each character, then make
6327 the aggregate. */
6328 String_Id gnat_string = Strval (gnat_node);
6329 int length = String_Length (gnat_string);
6330 int i;
6331 tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
6332 tree gnu_one_node = convert (TREE_TYPE (gnu_idx), integer_one_node);
6333 vec<constructor_elt, va_gc> *gnu_vec;
6334 vec_alloc (gnu_vec, length);
6336 for (i = 0; i < length; i++)
6338 tree t = build_int_cst (TREE_TYPE (gnu_result_type),
6339 Get_String_Char (gnat_string, i + 1));
6341 CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
6342 gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, gnu_one_node);
6345 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
6347 break;
6349 case N_Pragma:
6350 gnu_result = Pragma_to_gnu (gnat_node);
6351 break;
6353 /**************************************/
6354 /* Chapter 3: Declarations and Types */
6355 /**************************************/
6357 case N_Subtype_Declaration:
6358 case N_Full_Type_Declaration:
6359 case N_Incomplete_Type_Declaration:
6360 case N_Private_Type_Declaration:
6361 case N_Private_Extension_Declaration:
6362 case N_Task_Type_Declaration:
6363 process_type (Defining_Entity (gnat_node));
6364 gnu_result = alloc_stmt_list ();
6365 break;
6367 case N_Object_Declaration:
6368 case N_Number_Declaration:
6369 case N_Exception_Declaration:
6370 gnat_temp = Defining_Entity (gnat_node);
6371 gnu_result = alloc_stmt_list ();
6373 /* If we are just annotating types and this object has an unconstrained
6374 or task type, don't elaborate it. */
6375 if (type_annotate_only
6376 && (((Is_Array_Type (Etype (gnat_temp))
6377 || Is_Record_Type (Etype (gnat_temp)))
6378 && !Is_Constrained (Etype (gnat_temp)))
6379 || Is_Concurrent_Type (Etype (gnat_temp))))
6380 break;
6382 if (Present (Expression (gnat_node))
6383 && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
6384 && (!type_annotate_only
6385 || Compile_Time_Known_Value (Expression (gnat_node))))
6387 gigi_checking_assert (!Do_Range_Check (Expression (gnat_node)));
6389 gnu_expr = gnat_to_gnu (Expression (gnat_node));
6391 /* First deal with erroneous expressions. */
6392 if (TREE_CODE (gnu_expr) == ERROR_MARK)
6394 /* If this is a named number for which we cannot manipulate
6395 the value, just skip the declaration altogether. */
6396 if (kind == N_Number_Declaration)
6397 break;
6398 else if (type_annotate_only)
6399 gnu_expr = NULL_TREE;
6402 /* Then a special case: we do not want the SLOC of the expression
6403 of the tag to pop up every time it is referenced somewhere. */
6404 else if (EXPR_P (gnu_expr) && Is_Tag (gnat_temp))
6405 SET_EXPR_LOCATION (gnu_expr, UNKNOWN_LOCATION);
6407 else
6408 gnu_expr = NULL_TREE;
6410 /* If this is a deferred constant with an address clause, we ignore the
6411 full view since the clause is on the partial view and we cannot have
6412 2 different GCC trees for the object. The only bits of the full view
6413 we will use is the initializer, but it will be directly fetched. */
6414 if (Ekind (gnat_temp) == E_Constant
6415 && Present (Address_Clause (gnat_temp))
6416 && Present (Full_View (gnat_temp)))
6417 save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
6419 /* If this object has its elaboration delayed, we must force evaluation
6420 of GNU_EXPR now and save it for the freeze point. Note that we need
6421 not do anything special at the global level since the lifetime of the
6422 temporary is fully contained within the elaboration routine. */
6423 if (Present (Freeze_Node (gnat_temp)))
6425 if (gnu_expr)
6427 gnu_result = gnat_save_expr (gnu_expr);
6428 save_gnu_tree (gnat_node, gnu_result, true);
6431 else
6432 gnat_to_gnu_entity (gnat_temp, gnu_expr, true);
6433 break;
6435 case N_Object_Renaming_Declaration:
6436 gnat_temp = Defining_Entity (gnat_node);
6437 gnu_result = alloc_stmt_list ();
6439 /* Don't do anything if this renaming is handled by the front end and it
6440 does not need debug info. Note that we consider renamings don't need
6441 debug info when optimizing: our way to describe them has a
6442 memory/elaboration footprint.
6444 Don't do anything neither if we are just annotating types and this
6445 object has a composite or task type, don't elaborate it. */
6446 if ((!Is_Renaming_Of_Object (gnat_temp)
6447 || (Needs_Debug_Info (gnat_temp)
6448 && !optimize
6449 && can_materialize_object_renaming_p
6450 (Renamed_Object (gnat_temp))))
6451 && ! (type_annotate_only
6452 && (Is_Array_Type (Etype (gnat_temp))
6453 || Is_Record_Type (Etype (gnat_temp))
6454 || Is_Concurrent_Type (Etype (gnat_temp)))))
6455 gnat_to_gnu_entity (gnat_temp,
6456 gnat_to_gnu (Renamed_Object (gnat_temp)),
6457 true);
6458 break;
6460 case N_Exception_Renaming_Declaration:
6461 gnat_temp = Defining_Entity (gnat_node);
6462 gnu_result = alloc_stmt_list ();
6464 if (Present (Renamed_Entity (gnat_temp)))
6465 gnat_to_gnu_entity (gnat_temp,
6466 gnat_to_gnu (Renamed_Entity (gnat_temp)),
6467 true);
6468 break;
6470 case N_Subprogram_Renaming_Declaration:
6472 const Node_Id gnat_renaming = Defining_Entity (gnat_node);
6473 const Node_Id gnat_renamed = Renamed_Entity (gnat_renaming);
6475 gnu_result = alloc_stmt_list ();
6477 /* Materializing renamed subprograms will only benefit the debugging
6478 information as they aren't referenced in the generated code. So
6479 skip them when they aren't needed. Avoid doing this if:
6481 - there is a freeze node: in this case the renamed entity is not
6482 elaborated yet,
6483 - the renamed subprogram is intrinsic: it will not be available in
6484 the debugging information (note that both or only one of the
6485 renaming and the renamed subprograms can be intrinsic). */
6486 if (!type_annotate_only
6487 && Needs_Debug_Info (gnat_renaming)
6488 && No (Freeze_Node (gnat_renaming))
6489 && Present (gnat_renamed)
6490 && (Ekind (gnat_renamed) == E_Function
6491 || Ekind (gnat_renamed) == E_Procedure)
6492 && !Is_Intrinsic_Subprogram (gnat_renaming)
6493 && !Is_Intrinsic_Subprogram (gnat_renamed))
6494 gnat_to_gnu_entity (gnat_renaming, gnat_to_gnu (gnat_renamed), true);
6495 break;
6498 case N_Implicit_Label_Declaration:
6499 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, true);
6500 gnu_result = alloc_stmt_list ();
6501 break;
6503 case N_Package_Renaming_Declaration:
6504 /* These are fully handled in the front end. */
6505 /* ??? For package renamings, find a way to use GENERIC namespaces so
6506 that we get proper debug information for them. */
6507 gnu_result = alloc_stmt_list ();
6508 break;
6510 /*************************************/
6511 /* Chapter 4: Names and Expressions */
6512 /*************************************/
6514 case N_Explicit_Dereference:
6515 /* Make sure the designated type is complete before dereferencing. */
6516 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6517 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6518 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
6520 /* If atomic access is required on the RHS, build the atomic load. */
6521 if (simple_atomic_access_required_p (gnat_node, &aa_sync)
6522 && !present_in_lhs_or_actual_p (gnat_node))
6523 gnu_result = build_atomic_load (gnu_result, aa_sync);
6524 break;
6526 case N_Indexed_Component:
6528 tree gnu_array_object = gnat_to_gnu ((Prefix (gnat_node)));
6529 tree gnu_type;
6530 int ndim, i;
6531 Node_Id *gnat_expr_array;
6533 gnu_array_object = maybe_padded_object (gnu_array_object);
6534 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
6536 /* Convert vector inputs to their representative array type, to fit
6537 what the code below expects. */
6538 if (VECTOR_TYPE_P (TREE_TYPE (gnu_array_object)))
6540 if (present_in_lhs_or_actual_p (gnat_node))
6541 gnat_mark_addressable (gnu_array_object);
6542 gnu_array_object = maybe_vector_array (gnu_array_object);
6545 /* The failure of this assertion will very likely come from a missing
6546 expansion for a packed array access. */
6547 gcc_assert (TREE_CODE (TREE_TYPE (gnu_array_object)) == ARRAY_TYPE);
6549 /* First compute the number of dimensions of the array, then
6550 fill the expression array, the order depending on whether
6551 this is a Convention_Fortran array or not. */
6552 for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
6553 TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
6554 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
6555 ndim++, gnu_type = TREE_TYPE (gnu_type))
6558 gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
6560 if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
6561 for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
6562 i >= 0;
6563 i--, gnat_temp = Next (gnat_temp))
6564 gnat_expr_array[i] = gnat_temp;
6565 else
6566 for (i = 0, gnat_temp = First (Expressions (gnat_node));
6567 i < ndim;
6568 i++, gnat_temp = Next (gnat_temp))
6569 gnat_expr_array[i] = gnat_temp;
6571 /* Start with the prefix and build the successive references. */
6572 gnu_result = gnu_array_object;
6574 for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
6575 i < ndim;
6576 i++, gnu_type = TREE_TYPE (gnu_type))
6578 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
6579 gnat_temp = gnat_expr_array[i];
6580 gnu_expr = maybe_character_value (gnat_to_gnu (gnat_temp));
6582 gnu_result
6583 = build_binary_op (ARRAY_REF, NULL_TREE, gnu_result, gnu_expr);
6586 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6588 /* If atomic access is required on the RHS, build the atomic load. */
6589 if (simple_atomic_access_required_p (gnat_node, &aa_sync)
6590 && !present_in_lhs_or_actual_p (gnat_node))
6591 gnu_result = build_atomic_load (gnu_result, aa_sync);
6593 break;
6595 case N_Slice:
6597 tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
6599 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6601 gnu_array_object = maybe_padded_object (gnu_array_object);
6602 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
6604 gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
6605 gnu_expr = maybe_character_value (gnu_expr);
6607 /* If this is a slice with non-constant size of an array with constant
6608 size, set the maximum size for the allocation of temporaries. */
6609 if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
6610 && TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (gnu_array_object))))
6611 TYPE_ARRAY_MAX_SIZE (gnu_result_type)
6612 = TYPE_SIZE_UNIT (TREE_TYPE (gnu_array_object));
6614 gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
6615 gnu_array_object, gnu_expr);
6617 break;
6619 case N_Selected_Component:
6621 const Entity_Id gnat_prefix = Prefix (gnat_node);
6622 Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
6623 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
6625 gnu_prefix = maybe_padded_object (gnu_prefix);
6627 /* gnat_to_gnu_entity does not save the GNU tree made for renamed
6628 discriminants so avoid making recursive calls on each reference
6629 to them by following the appropriate link directly here. */
6630 if (Ekind (gnat_field) == E_Discriminant)
6632 /* For discriminant references in tagged types always substitute
6633 the corresponding discriminant as the actual component. */
6634 if (Is_Tagged_Type (Underlying_Type (Etype (gnat_prefix))))
6635 while (Present (Corresponding_Discriminant (gnat_field)))
6636 gnat_field = Corresponding_Discriminant (gnat_field);
6638 /* For discriminant references in untagged types always substitute
6639 the corresponding stored discriminant. */
6640 else if (Present (Corresponding_Discriminant (gnat_field)))
6641 gnat_field = Original_Record_Component (gnat_field);
6644 /* Handle extracting the real or imaginary part of a complex.
6645 The real part is the first field and the imaginary the last. */
6646 if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
6647 gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
6648 ? REALPART_EXPR : IMAGPART_EXPR,
6649 NULL_TREE, gnu_prefix);
6650 else
6652 tree gnu_field = gnat_to_gnu_field_decl (gnat_field);
6653 tree gnu_offset;
6654 struct loop_info_d *loop;
6656 gnu_result
6657 = build_component_ref (gnu_prefix, gnu_field,
6658 (Nkind (Parent (gnat_node))
6659 == N_Attribute_Reference)
6660 && lvalue_required_for_attribute_p
6661 (Parent (gnat_node)));
6663 /* If optimization is enabled and we are inside a loop, we try to
6664 hoist nonconstant but invariant offset computations outside of
6665 the loop, since they very likely contain loads that could turn
6666 out to be hard to move if they end up in active EH regions. */
6667 if (optimize
6668 && inside_loop_p ()
6669 && TREE_CODE (gnu_result) == COMPONENT_REF
6670 && (gnu_offset = component_ref_field_offset (gnu_result))
6671 && !TREE_CONSTANT (gnu_offset)
6672 && (gnu_offset = gnat_invariant_expr (gnu_offset))
6673 && (loop = find_loop ()))
6675 tree invariant
6676 = build1 (SAVE_EXPR, TREE_TYPE (gnu_offset), gnu_offset);
6677 vec_safe_push (loop->invariants, invariant);
6678 tree field = TREE_OPERAND (gnu_result, 1);
6679 tree factor
6680 = size_int (DECL_OFFSET_ALIGN (field) / BITS_PER_UNIT);
6681 /* Divide the offset by its alignment. */
6682 TREE_OPERAND (gnu_result, 2)
6683 = size_binop (EXACT_DIV_EXPR, invariant, factor);
6687 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6689 /* If atomic access is required on the RHS, build the atomic load. */
6690 if (simple_atomic_access_required_p (gnat_node, &aa_sync)
6691 && !present_in_lhs_or_actual_p (gnat_node))
6692 gnu_result = build_atomic_load (gnu_result, aa_sync);
6694 break;
6696 case N_Attribute_Reference:
6698 /* The attribute designator. */
6699 const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
6701 /* The Elab_Spec and Elab_Body attributes are special in that Prefix
6702 is a unit, not an object with a GCC equivalent. */
6703 if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
6704 return
6705 create_subprog_decl (create_concat_name
6706 (Entity (Prefix (gnat_node)),
6707 attr == Attr_Elab_Body ? "elabb" : "elabs"),
6708 NULL_TREE, void_ftype, NULL_TREE, is_default,
6709 true, true, true, true, false, NULL,
6710 gnat_node);
6712 gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
6714 break;
6716 case N_Reference:
6717 /* Like 'Access as far as we are concerned. */
6718 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6719 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
6720 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6721 break;
6723 case N_Aggregate:
6724 case N_Extension_Aggregate:
6726 tree gnu_aggr_type;
6728 /* Check that this aggregate has not slipped through the cracks. */
6729 gcc_assert (!Expansion_Delayed (gnat_node));
6731 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6733 if (TREE_CODE (gnu_result_type) == RECORD_TYPE
6734 && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
6735 gnu_aggr_type
6736 = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
6737 else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
6738 gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
6739 else
6740 gnu_aggr_type = gnu_result_type;
6742 if (Null_Record_Present (gnat_node))
6743 gnu_result = gnat_build_constructor (gnu_aggr_type, NULL);
6745 else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
6746 || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
6747 gnu_result
6748 = assoc_to_constructor (Etype (gnat_node),
6749 First (Component_Associations (gnat_node)),
6750 gnu_aggr_type);
6751 else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
6752 gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
6753 gnu_aggr_type);
6754 else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
6755 gnu_result
6756 = build_binary_op
6757 (COMPLEX_EXPR, gnu_aggr_type,
6758 gnat_to_gnu (Expression (First
6759 (Component_Associations (gnat_node)))),
6760 gnat_to_gnu (Expression
6761 (Next
6762 (First (Component_Associations (gnat_node))))));
6763 else
6764 gcc_unreachable ();
6766 gnu_result = convert (gnu_result_type, gnu_result);
6768 break;
6770 case N_Null:
6771 if (TARGET_VTABLE_USES_DESCRIPTORS
6772 && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
6773 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
6774 gnu_result = null_fdesc_node;
6775 else
6776 gnu_result = null_pointer_node;
6777 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6778 break;
6780 case N_Type_Conversion:
6781 case N_Qualified_Expression:
6782 gnu_expr = maybe_character_value (gnat_to_gnu (Expression (gnat_node)));
6783 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6785 /* If this is a qualified expression for a tagged type, we mark the type
6786 as used. Because of polymorphism, this might be the only reference to
6787 the tagged type in the program while objects have it as dynamic type.
6788 The debugger needs to see it to display these objects properly. */
6789 if (kind == N_Qualified_Expression && Is_Tagged_Type (Etype (gnat_node)))
6790 used_types_insert (gnu_result_type);
6792 gigi_checking_assert (!Do_Range_Check (Expression (gnat_node)));
6794 gnu_result
6795 = convert_with_check (Etype (gnat_node), gnu_expr,
6796 Do_Overflow_Check (gnat_node),
6797 kind == N_Type_Conversion
6798 && Float_Truncate (gnat_node), gnat_node);
6799 break;
6801 case N_Unchecked_Type_Conversion:
6802 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6803 gnu_expr = maybe_character_value (gnat_to_gnu (Expression (gnat_node)));
6805 /* Skip further processing if the conversion is deemed a no-op. */
6806 if (unchecked_conversion_nop (gnat_node))
6808 gnu_result = gnu_expr;
6809 gnu_result_type = TREE_TYPE (gnu_result);
6810 break;
6813 /* If the result is a pointer type, see if we are improperly
6814 converting to a stricter alignment. */
6815 if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
6816 && Is_Access_Type (Etype (gnat_node)))
6818 unsigned int align = known_alignment (gnu_expr);
6819 tree gnu_obj_type = TREE_TYPE (gnu_result_type);
6820 unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
6822 if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
6823 post_error_ne_tree_2
6824 ("??source alignment (^) '< alignment of & (^)",
6825 gnat_node, Designated_Type (Etype (gnat_node)),
6826 size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
6829 /* If we are converting a descriptor to a function pointer, first
6830 build the pointer. */
6831 if (TARGET_VTABLE_USES_DESCRIPTORS
6832 && TREE_TYPE (gnu_expr) == fdesc_type_node
6833 && POINTER_TYPE_P (gnu_result_type))
6834 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
6836 gnu_result = unchecked_convert (gnu_result_type, gnu_expr,
6837 No_Truncation (gnat_node));
6838 break;
6840 case N_In:
6841 case N_Not_In:
6843 tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
6844 tree gnu_low, gnu_high;
6846 Range_to_gnu (Right_Opnd (gnat_node), &gnu_low, &gnu_high);
6847 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6849 tree gnu_op_type = maybe_character_type (TREE_TYPE (gnu_obj));
6850 if (TREE_TYPE (gnu_obj) != gnu_op_type)
6852 gnu_obj = convert (gnu_op_type, gnu_obj);
6853 gnu_low = convert (gnu_op_type, gnu_low);
6854 gnu_high = convert (gnu_op_type, gnu_high);
6857 /* If LOW and HIGH are identical, perform an equality test. Otherwise,
6858 ensure that GNU_OBJ is evaluated only once and perform a full range
6859 test. */
6860 if (operand_equal_p (gnu_low, gnu_high, 0))
6861 gnu_result
6862 = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
6863 else
6865 tree t1, t2;
6866 gnu_obj = gnat_protect_expr (gnu_obj);
6867 t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
6868 if (EXPR_P (t1))
6869 set_expr_location_from_node (t1, gnat_node);
6870 t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
6871 if (EXPR_P (t2))
6872 set_expr_location_from_node (t2, gnat_node);
6873 gnu_result
6874 = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
6877 if (kind == N_Not_In)
6878 gnu_result
6879 = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
6881 break;
6883 case N_Op_Divide:
6884 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6885 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6886 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6887 gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
6888 ? RDIV_EXPR
6889 : (Rounded_Result (gnat_node)
6890 ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
6891 gnu_result_type, gnu_lhs, gnu_rhs);
6892 break;
6894 case N_Op_Eq:
6895 case N_Op_Ne:
6896 case N_Op_Lt:
6897 case N_Op_Le:
6898 case N_Op_Gt:
6899 case N_Op_Ge:
6900 case N_Op_Add:
6901 case N_Op_Subtract:
6902 case N_Op_Multiply:
6903 case N_Op_Mod:
6904 case N_Op_Rem:
6905 case N_Op_Rotate_Left:
6906 case N_Op_Rotate_Right:
6907 case N_Op_Shift_Left:
6908 case N_Op_Shift_Right:
6909 case N_Op_Shift_Right_Arithmetic:
6910 case N_Op_And:
6911 case N_Op_Or:
6912 case N_Op_Xor:
6913 case N_And_Then:
6914 case N_Or_Else:
6916 enum tree_code code = gnu_codes[kind];
6917 bool ignore_lhs_overflow = false;
6918 location_t saved_location = input_location;
6919 tree gnu_type, gnu_max_shift = NULL_TREE;
6921 /* Fix operations set up for boolean types in GNU_CODES above. */
6922 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6923 switch (kind)
6925 case N_Op_And:
6926 code = BIT_AND_EXPR;
6927 break;
6928 case N_Op_Or:
6929 code = BIT_IOR_EXPR;
6930 break;
6931 case N_Op_Xor:
6932 code = BIT_XOR_EXPR;
6933 break;
6934 default:
6935 break;
6938 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6939 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6940 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6942 /* If this is a shift, take the count as unsigned since that is what
6943 most machines do and will generate simpler adjustments below. */
6944 if (IN (kind, N_Op_Shift))
6946 tree gnu_count_type
6947 = gnat_unsigned_type_for (get_base_type (TREE_TYPE (gnu_rhs)));
6948 gnu_rhs = convert (gnu_count_type, gnu_rhs);
6949 gnu_max_shift
6950 = convert (TREE_TYPE (gnu_rhs), TYPE_SIZE (gnu_type));
6953 /* Pending generic support for efficient vector logical operations in
6954 GCC, convert vectors to their representative array type view and
6955 fallthrough. */
6956 gnu_lhs = maybe_vector_array (gnu_lhs);
6957 gnu_rhs = maybe_vector_array (gnu_rhs);
6959 /* If this is a comparison operator, convert any references to an
6960 unconstrained array value into a reference to the actual array. */
6961 if (TREE_CODE_CLASS (code) == tcc_comparison)
6963 gnu_lhs = maybe_unconstrained_array (gnu_lhs);
6964 gnu_rhs = maybe_unconstrained_array (gnu_rhs);
6966 tree gnu_op_type = maybe_character_type (TREE_TYPE (gnu_lhs));
6967 if (TREE_TYPE (gnu_lhs) != gnu_op_type)
6969 gnu_lhs = convert (gnu_op_type, gnu_lhs);
6970 gnu_rhs = convert (gnu_op_type, gnu_rhs);
6974 /* If this is a shift whose count is not guaranteed to be correct,
6975 we need to adjust the shift count. */
6976 if ((kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
6977 && !Shift_Count_OK (gnat_node))
6978 gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, TREE_TYPE (gnu_rhs),
6979 gnu_rhs, gnu_max_shift);
6980 else if (kind == N_Op_Shift_Right_Arithmetic
6981 && !Shift_Count_OK (gnat_node))
6982 gnu_rhs
6983 = build_binary_op (MIN_EXPR, TREE_TYPE (gnu_rhs),
6984 build_binary_op (MINUS_EXPR,
6985 TREE_TYPE (gnu_rhs),
6986 gnu_max_shift,
6987 build_int_cst
6988 (TREE_TYPE (gnu_rhs), 1)),
6989 gnu_rhs);
6991 /* For right shifts, the type says what kind of shift to do,
6992 so we may need to choose a different type. In this case,
6993 we have to ignore integer overflow lest it propagates all
6994 the way down and causes a CE to be explicitly raised. */
6995 if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
6997 gnu_type = gnat_unsigned_type_for (gnu_type);
6998 ignore_lhs_overflow = true;
7000 else if (kind == N_Op_Shift_Right_Arithmetic
7001 && TYPE_UNSIGNED (gnu_type))
7003 gnu_type = gnat_signed_type_for (gnu_type);
7004 ignore_lhs_overflow = true;
7007 if (gnu_type != gnu_result_type)
7009 tree gnu_old_lhs = gnu_lhs;
7010 gnu_lhs = convert (gnu_type, gnu_lhs);
7011 if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
7012 TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
7013 gnu_rhs = convert (gnu_type, gnu_rhs);
7014 if (gnu_max_shift)
7015 gnu_max_shift = convert (gnu_type, gnu_max_shift);
7018 /* For signed integer addition, subtraction and multiplication, do an
7019 overflow check if required. */
7020 if (Do_Overflow_Check (gnat_node)
7021 && (code == PLUS_EXPR || code == MINUS_EXPR || code == MULT_EXPR)
7022 && !TYPE_UNSIGNED (gnu_type)
7023 && !FLOAT_TYPE_P (gnu_type))
7024 gnu_result
7025 = build_binary_op_trapv (code, gnu_type, gnu_lhs, gnu_rhs,
7026 gnat_node);
7027 else
7029 /* Some operations, e.g. comparisons of arrays, generate complex
7030 trees that need to be annotated while they are being built. */
7031 input_location = saved_location;
7032 gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
7035 /* If this is a logical shift with the shift count not verified,
7036 we must return zero if it is too large. We cannot compensate
7037 beforehand in this case. */
7038 if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
7039 && !Shift_Count_OK (gnat_node))
7040 gnu_result
7041 = build_cond_expr (gnu_type,
7042 build_binary_op (GE_EXPR, boolean_type_node,
7043 gnu_rhs, gnu_max_shift),
7044 build_int_cst (gnu_type, 0),
7045 gnu_result);
7047 break;
7049 case N_If_Expression:
7051 tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
7052 tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
7053 tree gnu_false
7054 = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
7056 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7057 gnu_result
7058 = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
7060 break;
7062 case N_Op_Plus:
7063 gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
7064 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7065 break;
7067 case N_Op_Not:
7068 /* This case can apply to a boolean or a modular type.
7069 Fall through for a boolean operand since GNU_CODES is set
7070 up to handle this. */
7071 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
7073 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
7074 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7075 gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
7076 gnu_expr);
7077 break;
7080 /* ... fall through ... */
7082 case N_Op_Minus:
7083 case N_Op_Abs:
7084 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
7085 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7087 /* For signed integer negation and absolute value, do an overflow check
7088 if required. */
7089 if (Do_Overflow_Check (gnat_node)
7090 && !TYPE_UNSIGNED (gnu_result_type)
7091 && !FLOAT_TYPE_P (gnu_result_type))
7092 gnu_result
7093 = build_unary_op_trapv (gnu_codes[kind], gnu_result_type, gnu_expr,
7094 gnat_node);
7095 else
7096 gnu_result
7097 = build_unary_op (gnu_codes[kind], gnu_result_type, gnu_expr);
7098 break;
7100 case N_Allocator:
7102 tree gnu_type, gnu_init;
7103 bool ignore_init_type;
7105 gnat_temp = Expression (gnat_node);
7107 /* The expression can be either an N_Identifier or an Expanded_Name,
7108 which must represent a type, or a N_Qualified_Expression, which
7109 contains both the type and an initial value for the object. */
7110 if (Nkind (gnat_temp) == N_Identifier
7111 || Nkind (gnat_temp) == N_Expanded_Name)
7113 ignore_init_type = false;
7114 gnu_init = NULL_TREE;
7115 gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
7118 else if (Nkind (gnat_temp) == N_Qualified_Expression)
7120 const Entity_Id gnat_desig_type
7121 = Designated_Type (Underlying_Type (Etype (gnat_node)));
7123 ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
7125 gnu_init = gnat_to_gnu (Expression (gnat_temp));
7126 gnu_init = maybe_unconstrained_array (gnu_init);
7128 gigi_checking_assert (!Do_Range_Check (Expression (gnat_temp)));
7130 if (Is_Elementary_Type (gnat_desig_type)
7131 || Is_Constrained (gnat_desig_type))
7132 gnu_type = gnat_to_gnu_type (gnat_desig_type);
7133 else
7135 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
7136 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
7137 gnu_type = TREE_TYPE (gnu_init);
7140 /* See the N_Qualified_Expression case for the rationale. */
7141 if (Is_Tagged_Type (gnat_desig_type))
7142 used_types_insert (gnu_type);
7144 gnu_init = convert (gnu_type, gnu_init);
7146 else
7147 gcc_unreachable ();
7149 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7150 return build_allocator (gnu_type, gnu_init, gnu_result_type,
7151 Procedure_To_Call (gnat_node),
7152 Storage_Pool (gnat_node), gnat_node,
7153 ignore_init_type);
7155 break;
7157 /**************************/
7158 /* Chapter 5: Statements */
7159 /**************************/
7161 case N_Label:
7162 gnu_result = build1 (LABEL_EXPR, void_type_node,
7163 gnat_to_gnu (Identifier (gnat_node)));
7164 break;
7166 case N_Null_Statement:
7167 /* When not optimizing, turn null statements from source into gotos to
7168 the next statement that the middle-end knows how to preserve. */
7169 if (!optimize && Comes_From_Source (gnat_node))
7171 tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
7172 DECL_IGNORED_P (label) = 1;
7173 start_stmt_group ();
7174 stmt = build1 (GOTO_EXPR, void_type_node, label);
7175 set_expr_location_from_node (stmt, gnat_node);
7176 add_stmt (stmt);
7177 stmt = build1 (LABEL_EXPR, void_type_node, label);
7178 set_expr_location_from_node (stmt, gnat_node);
7179 add_stmt (stmt);
7180 gnu_result = end_stmt_group ();
7182 else
7183 gnu_result = alloc_stmt_list ();
7184 break;
7186 case N_Assignment_Statement:
7187 /* Get the LHS and RHS of the statement and convert any reference to an
7188 unconstrained array into a reference to the underlying array. */
7189 gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
7191 /* If the type has a size that overflows, convert this into raise of
7192 Storage_Error: execution shouldn't have gotten here anyway. */
7193 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
7194 && !valid_constant_size_p (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
7195 gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
7196 N_Raise_Storage_Error);
7197 else if (Nkind (Expression (gnat_node)) == N_Function_Call)
7199 get_atomic_access (Name (gnat_node), &aa_type, &aa_sync);
7200 gnu_result
7201 = Call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
7202 aa_type, aa_sync);
7204 else
7206 const Node_Id gnat_expr = Expression (gnat_node);
7207 const Node_Id gnat_inner
7208 = Nkind (gnat_expr) == N_Qualified_Expression
7209 ? Expression (gnat_expr)
7210 : gnat_expr;
7211 const Entity_Id gnat_type
7212 = Underlying_Type (Etype (Name (gnat_node)));
7213 const bool use_memset_p
7214 = Is_Array_Type (gnat_type)
7215 && Nkind (gnat_inner) == N_Aggregate
7216 && Is_Single_Aggregate (gnat_inner);
7218 /* If we use memset, we need to find the innermost expression. */
7219 if (use_memset_p)
7221 gnat_temp = gnat_inner;
7222 do {
7223 gnat_temp
7224 = Expression (First (Component_Associations (gnat_temp)));
7225 } while (Nkind (gnat_temp) == N_Aggregate
7226 && Is_Single_Aggregate (gnat_temp));
7227 gnu_rhs = gnat_to_gnu (gnat_temp);
7229 else
7230 gnu_rhs = maybe_unconstrained_array (gnat_to_gnu (gnat_expr));
7232 gigi_checking_assert (!Do_Range_Check (gnat_expr));
7234 get_atomic_access (Name (gnat_node), &aa_type, &aa_sync);
7236 /* If an outer atomic access is required on the LHS, build the load-
7237 modify-store sequence. */
7238 if (aa_type == OUTER_ATOMIC)
7239 gnu_result = build_load_modify_store (gnu_lhs, gnu_rhs, gnat_node);
7241 /* Or else, if a simple atomic access is required, build the atomic
7242 store. */
7243 else if (aa_type == SIMPLE_ATOMIC)
7244 gnu_result = build_atomic_store (gnu_lhs, gnu_rhs, aa_sync);
7246 /* Or else, use memset when the conditions are met. This has already
7247 been validated by Aggr_Assignment_OK_For_Backend in the front-end
7248 and the RHS is thus guaranteed to be of the appropriate form. */
7249 else if (use_memset_p)
7251 tree value
7252 = real_zerop (gnu_rhs)
7253 ? integer_zero_node
7254 : fold_convert (integer_type_node, gnu_rhs);
7255 tree dest = build_fold_addr_expr (gnu_lhs);
7256 tree t = builtin_decl_explicit (BUILT_IN_MEMSET);
7257 /* Be extra careful not to write too much data. */
7258 tree size;
7259 if (TREE_CODE (gnu_lhs) == COMPONENT_REF)
7260 size = DECL_SIZE_UNIT (TREE_OPERAND (gnu_lhs, 1));
7261 else if (DECL_P (gnu_lhs))
7262 size = DECL_SIZE_UNIT (gnu_lhs);
7263 else
7264 size = TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs));
7265 size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, gnu_lhs);
7266 if (TREE_CODE (value) == INTEGER_CST && !integer_zerop (value))
7268 tree mask
7269 = build_int_cst (integer_type_node,
7270 ((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
7271 value = int_const_binop (BIT_AND_EXPR, value, mask);
7273 gnu_result = build_call_expr (t, 3, dest, value, size);
7276 /* Otherwise build a regular assignment. */
7277 else
7278 gnu_result
7279 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
7281 /* If the assignment type is a regular array and the two sides are
7282 not completely disjoint, play safe and use memmove. But don't do
7283 it for a bit-packed array as it might not be byte-aligned. */
7284 if (TREE_CODE (gnu_result) == MODIFY_EXPR
7285 && Is_Array_Type (gnat_type)
7286 && !Is_Bit_Packed_Array (gnat_type)
7287 && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
7289 tree to = TREE_OPERAND (gnu_result, 0);
7290 tree from = TREE_OPERAND (gnu_result, 1);
7291 tree type = TREE_TYPE (from);
7292 tree size
7293 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), from);
7294 tree to_ptr = build_fold_addr_expr (to);
7295 tree from_ptr = build_fold_addr_expr (from);
7296 tree t = builtin_decl_explicit (BUILT_IN_MEMMOVE);
7297 gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
7300 break;
7302 case N_If_Statement:
7304 tree *gnu_else_ptr; /* Point to put next "else if" or "else". */
7306 /* Make the outer COND_EXPR. Avoid non-determinism. */
7307 gnu_result = build3 (COND_EXPR, void_type_node,
7308 gnat_to_gnu (Condition (gnat_node)),
7309 NULL_TREE, NULL_TREE);
7310 COND_EXPR_THEN (gnu_result)
7311 = build_stmt_group (Then_Statements (gnat_node), false);
7312 TREE_SIDE_EFFECTS (gnu_result) = 1;
7313 gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
7315 /* Now make a COND_EXPR for each of the "else if" parts. Put each
7316 into the previous "else" part and point to where to put any
7317 outer "else". Also avoid non-determinism. */
7318 if (Present (Elsif_Parts (gnat_node)))
7319 for (gnat_temp = First (Elsif_Parts (gnat_node));
7320 Present (gnat_temp); gnat_temp = Next (gnat_temp))
7322 gnu_expr = build3 (COND_EXPR, void_type_node,
7323 gnat_to_gnu (Condition (gnat_temp)),
7324 NULL_TREE, NULL_TREE);
7325 COND_EXPR_THEN (gnu_expr)
7326 = build_stmt_group (Then_Statements (gnat_temp), false);
7327 TREE_SIDE_EFFECTS (gnu_expr) = 1;
7328 set_expr_location_from_node (gnu_expr, gnat_temp);
7329 *gnu_else_ptr = gnu_expr;
7330 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
7333 *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
7335 break;
7337 case N_Case_Statement:
7338 gnu_result = Case_Statement_to_gnu (gnat_node);
7339 break;
7341 case N_Loop_Statement:
7342 gnu_result = Loop_Statement_to_gnu (gnat_node);
7343 break;
7345 case N_Block_Statement:
7346 /* The only way to enter the block is to fall through to it. */
7347 if (stmt_group_may_fallthru ())
7349 start_stmt_group ();
7350 gnat_pushlevel ();
7351 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7352 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
7353 gnat_poplevel ();
7354 gnu_result = end_stmt_group ();
7356 else
7357 gnu_result = alloc_stmt_list ();
7358 break;
7360 case N_Exit_Statement:
7361 gnu_result
7362 = build2 (EXIT_STMT, void_type_node,
7363 (Present (Condition (gnat_node))
7364 ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
7365 (Present (Name (gnat_node))
7366 ? get_gnu_tree (Entity (Name (gnat_node)))
7367 : LOOP_STMT_LABEL (gnu_loop_stack->last ()->stmt)));
7368 break;
7370 case N_Simple_Return_Statement:
7372 tree gnu_ret_obj, gnu_ret_val;
7374 /* If the subprogram is a function, we must return the expression. */
7375 if (Present (Expression (gnat_node)))
7377 tree gnu_subprog_type = TREE_TYPE (current_function_decl);
7379 /* If this function has copy-in/copy-out parameters parameters and
7380 doesn't return by invisible reference, get the real object for
7381 the return. See Subprogram_Body_to_gnu. */
7382 if (TYPE_CI_CO_LIST (gnu_subprog_type)
7383 && !TREE_ADDRESSABLE (gnu_subprog_type))
7384 gnu_ret_obj = gnu_return_var_stack->last ();
7385 else
7386 gnu_ret_obj = DECL_RESULT (current_function_decl);
7388 /* Get the GCC tree for the expression to be returned. */
7389 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
7391 /* Do not remove the padding from GNU_RET_VAL if the inner type is
7392 self-referential since we want to allocate the fixed size. */
7393 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
7394 && type_is_padding_self_referential
7395 (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0))))
7396 gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
7398 /* If the function returns by direct reference, return a pointer
7399 to the return value. */
7400 if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
7401 || By_Ref (gnat_node))
7402 gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
7404 /* Otherwise, if it returns an unconstrained array, we have to
7405 allocate a new version of the result and return it. */
7406 else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
7408 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
7410 /* And find out whether this is a candidate for Named Return
7411 Value. If so, record it. */
7412 if (optimize
7413 && !optimize_debug
7414 && !TYPE_CI_CO_LIST (gnu_subprog_type))
7416 tree ret_val = gnu_ret_val;
7418 /* Strip useless conversions around the return value. */
7419 if (gnat_useless_type_conversion (ret_val))
7420 ret_val = TREE_OPERAND (ret_val, 0);
7422 /* Strip unpadding around the return value. */
7423 if (TREE_CODE (ret_val) == COMPONENT_REF
7424 && TYPE_IS_PADDING_P
7425 (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
7426 ret_val = TREE_OPERAND (ret_val, 0);
7428 /* Now apply the test to the return value. */
7429 if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
7431 if (!f_named_ret_val)
7432 f_named_ret_val = BITMAP_GGC_ALLOC ();
7433 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
7434 if (!f_gnat_ret)
7435 f_gnat_ret = gnat_node;
7439 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
7440 gnu_ret_val,
7441 TREE_TYPE (gnu_ret_obj),
7442 Procedure_To_Call (gnat_node),
7443 Storage_Pool (gnat_node),
7444 gnat_node, false);
7447 /* Otherwise, if it returns by invisible reference, dereference
7448 the pointer it is passed using the type of the return value
7449 and build the copy operation manually. This ensures that we
7450 don't copy too much data, for example if the return type is
7451 unconstrained with a maximum size. */
7452 else if (TREE_ADDRESSABLE (gnu_subprog_type))
7454 tree gnu_ret_deref
7455 = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
7456 gnu_ret_obj);
7457 gnu_result = build2 (INIT_EXPR, void_type_node,
7458 gnu_ret_deref, gnu_ret_val);
7459 /* Avoid a useless copy with __builtin_return_slot. */
7460 if (TREE_CODE (gnu_ret_val) == INDIRECT_REF)
7461 gnu_result
7462 = build3 (COND_EXPR, void_type_node,
7463 fold_build2 (NE_EXPR, boolean_type_node,
7464 TREE_OPERAND (gnu_ret_val, 0),
7465 gnu_ret_obj),
7466 gnu_result, NULL_TREE);
7467 add_stmt_with_node (gnu_result, gnat_node);
7468 gnu_ret_val = NULL_TREE;
7472 else
7473 gnu_ret_obj = gnu_ret_val = NULL_TREE;
7475 /* If we have a return label defined, convert this into a branch to
7476 that label. The return proper will be handled elsewhere. */
7477 if (gnu_return_label_stack->last ())
7479 if (gnu_ret_val)
7480 add_stmt_with_node (build_binary_op (MODIFY_EXPR,
7481 NULL_TREE, gnu_ret_obj,
7482 gnu_ret_val),
7483 gnat_node);
7485 gnu_result = build1 (GOTO_EXPR, void_type_node,
7486 gnu_return_label_stack->last ());
7488 /* When not optimizing, make sure the return is preserved. */
7489 if (!optimize && Comes_From_Source (gnat_node))
7490 DECL_ARTIFICIAL (gnu_return_label_stack->last ()) = 0;
7493 /* Otherwise, build a regular return. */
7494 else
7495 gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
7497 break;
7499 case N_Goto_Statement:
7500 gnu_expr = gnat_to_gnu (Name (gnat_node));
7501 gnu_result = build1 (GOTO_EXPR, void_type_node, gnu_expr);
7502 TREE_USED (gnu_expr) = 1;
7503 break;
7505 /***************************/
7506 /* Chapter 6: Subprograms */
7507 /***************************/
7509 case N_Subprogram_Declaration:
7510 /* Unless there is a freeze node, declare the entity. We consider
7511 this a definition even though we're not generating code for the
7512 subprogram because we will be making the corresponding GCC node.
7513 When there is a freeze node, it is considered the definition of
7514 the subprogram and we do nothing until after it is encountered.
7515 That's an efficiency issue: the types involved in the profile
7516 are far more likely to be frozen between the declaration and
7517 the freeze node than before the declaration, so we save some
7518 updates of the GCC node by waiting until the freeze node.
7519 The counterpart is that we assume that there is no reference
7520 to the subprogram between the declaration and the freeze node
7521 in the expanded code; otherwise, it will be interpreted as an
7522 external reference and very likely give rise to a link failure. */
7523 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
7524 gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
7525 NULL_TREE, true);
7526 gnu_result = alloc_stmt_list ();
7527 break;
7529 case N_Abstract_Subprogram_Declaration:
7530 /* This subprogram doesn't exist for code generation purposes, but we
7531 have to elaborate the types of any parameters and result, unless
7532 they are imported types (nothing to generate in this case).
7534 The parameter list may contain types with freeze nodes, e.g. not null
7535 subtypes, so the subprogram itself may carry a freeze node, in which
7536 case its elaboration must be deferred. */
7538 /* Process the parameter types first. */
7539 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
7540 for (gnat_temp
7541 = First_Formal_With_Extras
7542 (Defining_Entity (Specification (gnat_node)));
7543 Present (gnat_temp);
7544 gnat_temp = Next_Formal_With_Extras (gnat_temp))
7545 if (Is_Itype (Etype (gnat_temp))
7546 && !From_Limited_With (Etype (gnat_temp)))
7547 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, false);
7549 /* Then the result type, set to Standard_Void_Type for procedures. */
7551 Entity_Id gnat_temp_type
7552 = Etype (Defining_Entity (Specification (gnat_node)));
7554 if (Is_Itype (gnat_temp_type) && !From_Limited_With (gnat_temp_type))
7555 gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, false);
7558 gnu_result = alloc_stmt_list ();
7559 break;
7561 case N_Defining_Program_Unit_Name:
7562 /* For a child unit identifier go up a level to get the specification.
7563 We get this when we try to find the spec of a child unit package
7564 that is the compilation unit being compiled. */
7565 gnu_result = gnat_to_gnu (Parent (gnat_node));
7566 break;
7568 case N_Subprogram_Body:
7569 Subprogram_Body_to_gnu (gnat_node);
7570 gnu_result = alloc_stmt_list ();
7571 break;
7573 case N_Function_Call:
7574 case N_Procedure_Call_Statement:
7575 gnu_result = Call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE,
7576 NOT_ATOMIC, false);
7577 break;
7579 /************************/
7580 /* Chapter 7: Packages */
7581 /************************/
7583 case N_Package_Declaration:
7584 gnu_result = gnat_to_gnu (Specification (gnat_node));
7585 break;
7587 case N_Package_Specification:
7589 start_stmt_group ();
7590 process_decls (Visible_Declarations (gnat_node),
7591 Private_Declarations (gnat_node), Empty, true, true);
7592 gnu_result = end_stmt_group ();
7593 break;
7595 case N_Package_Body:
7597 /* If this is the body of a generic package - do nothing. */
7598 if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
7600 gnu_result = alloc_stmt_list ();
7601 break;
7604 start_stmt_group ();
7605 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7607 if (Present (Handled_Statement_Sequence (gnat_node)))
7608 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
7610 gnu_result = end_stmt_group ();
7611 break;
7613 /********************************/
7614 /* Chapter 8: Visibility Rules */
7615 /********************************/
7617 case N_Use_Package_Clause:
7618 case N_Use_Type_Clause:
7619 /* Nothing to do here - but these may appear in list of declarations. */
7620 gnu_result = alloc_stmt_list ();
7621 break;
7623 /*********************/
7624 /* Chapter 9: Tasks */
7625 /*********************/
7627 case N_Protected_Type_Declaration:
7628 gnu_result = alloc_stmt_list ();
7629 break;
7631 case N_Single_Task_Declaration:
7632 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, true);
7633 gnu_result = alloc_stmt_list ();
7634 break;
7636 /*********************************************************/
7637 /* Chapter 10: Program Structure and Compilation Issues */
7638 /*********************************************************/
7640 case N_Compilation_Unit:
7641 /* This is not called for the main unit on which gigi is invoked. */
7642 Compilation_Unit_to_gnu (gnat_node);
7643 gnu_result = alloc_stmt_list ();
7644 break;
7646 case N_Subunit:
7647 gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
7648 break;
7650 case N_Entry_Body:
7651 case N_Protected_Body:
7652 case N_Task_Body:
7653 /* These nodes should only be present when annotating types. */
7654 gcc_assert (type_annotate_only);
7655 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7656 gnu_result = alloc_stmt_list ();
7657 break;
7659 case N_Subprogram_Body_Stub:
7660 case N_Package_Body_Stub:
7661 case N_Protected_Body_Stub:
7662 case N_Task_Body_Stub:
7663 /* Simply process whatever unit is being inserted. */
7664 if (Present (Library_Unit (gnat_node)))
7665 gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
7666 else
7668 gcc_assert (type_annotate_only);
7669 gnu_result = alloc_stmt_list ();
7671 break;
7673 /***************************/
7674 /* Chapter 11: Exceptions */
7675 /***************************/
7677 case N_Handled_Sequence_Of_Statements:
7678 gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
7679 break;
7681 case N_Exception_Handler:
7682 gnu_result = Exception_Handler_to_gnu (gnat_node);
7683 break;
7685 case N_Raise_Statement:
7686 /* Only for reraise in back-end exceptions mode. */
7687 gcc_assert (No (Name (gnat_node)));
7689 start_stmt_group ();
7691 add_stmt_with_node (build_call_n_expr (reraise_zcx_decl, 1,
7692 gnu_incoming_exc_ptr),
7693 gnat_node);
7695 gnu_result = end_stmt_group ();
7696 break;
7698 case N_Push_Constraint_Error_Label:
7699 gnu_constraint_error_label_stack.safe_push (Exception_Label (gnat_node));
7700 break;
7702 case N_Push_Storage_Error_Label:
7703 gnu_storage_error_label_stack.safe_push (Exception_Label (gnat_node));
7704 break;
7706 case N_Push_Program_Error_Label:
7707 gnu_program_error_label_stack.safe_push (Exception_Label (gnat_node));
7708 break;
7710 case N_Pop_Constraint_Error_Label:
7711 gnat_temp = gnu_constraint_error_label_stack.pop ();
7712 if (Present (gnat_temp)
7713 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false))
7714 && No_Exception_Propagation_Active ())
7715 Warn_If_No_Local_Raise (gnat_temp);
7716 break;
7718 case N_Pop_Storage_Error_Label:
7719 gnat_temp = gnu_storage_error_label_stack.pop ();
7720 if (Present (gnat_temp)
7721 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false))
7722 && No_Exception_Propagation_Active ())
7723 Warn_If_No_Local_Raise (gnat_temp);
7724 break;
7726 case N_Pop_Program_Error_Label:
7727 gnat_temp = gnu_program_error_label_stack.pop ();
7728 if (Present (gnat_temp)
7729 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false))
7730 && No_Exception_Propagation_Active ())
7731 Warn_If_No_Local_Raise (gnat_temp);
7732 break;
7734 /******************************/
7735 /* Chapter 12: Generic Units */
7736 /******************************/
7738 case N_Generic_Function_Renaming_Declaration:
7739 case N_Generic_Package_Renaming_Declaration:
7740 case N_Generic_Procedure_Renaming_Declaration:
7741 case N_Generic_Package_Declaration:
7742 case N_Generic_Subprogram_Declaration:
7743 case N_Package_Instantiation:
7744 case N_Procedure_Instantiation:
7745 case N_Function_Instantiation:
7746 /* These nodes can appear on a declaration list but there is nothing to
7747 to be done with them. */
7748 gnu_result = alloc_stmt_list ();
7749 break;
7751 /**************************************************/
7752 /* Chapter 13: Representation Clauses and */
7753 /* Implementation-Dependent Features */
7754 /**************************************************/
7756 case N_Attribute_Definition_Clause:
7757 gnu_result = alloc_stmt_list ();
7759 /* The only one we need to deal with is 'Address since, for the others,
7760 the front-end puts the information elsewhere. */
7761 if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
7762 break;
7764 /* And we only deal with 'Address if the object has a Freeze node. */
7765 gnat_temp = Entity (Name (gnat_node));
7766 if (Freeze_Node (gnat_temp))
7768 tree gnu_address = gnat_to_gnu (Expression (gnat_node)), gnu_temp;
7770 /* Get the value to use as the address and save it as the equivalent
7771 for the object; when it is frozen, gnat_to_gnu_entity will do the
7772 right thing. For a subprogram, put the naked address but build a
7773 meaningfull expression for an object in case its address is taken
7774 before the Freeze node is encountered; this can happen if the type
7775 of the object is limited and it is initialized with the result of
7776 a function call. */
7777 if (Is_Subprogram (gnat_temp))
7778 gnu_temp = gnu_address;
7779 else
7781 tree gnu_type = gnat_to_gnu_type (Etype (gnat_temp));
7782 /* Drop atomic and volatile qualifiers for the expression. */
7783 gnu_type = TYPE_MAIN_VARIANT (gnu_type);
7784 gnu_type
7785 = build_reference_type_for_mode (gnu_type, ptr_mode, true);
7786 gnu_address = convert (gnu_type, gnu_address);
7787 gnu_temp
7788 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_address);
7791 save_gnu_tree (gnat_temp, gnu_temp, true);
7793 break;
7795 case N_Enumeration_Representation_Clause:
7796 case N_Record_Representation_Clause:
7797 case N_At_Clause:
7798 /* We do nothing with these. SEM puts the information elsewhere. */
7799 gnu_result = alloc_stmt_list ();
7800 break;
7802 case N_Code_Statement:
7803 if (!type_annotate_only)
7805 tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
7806 tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
7807 tree gnu_clobbers = NULL_TREE, tail;
7808 bool allows_mem, allows_reg, fake;
7809 int ninputs, noutputs, i;
7810 const char **oconstraints;
7811 const char *constraint;
7812 char *clobber;
7814 /* First retrieve the 3 operand lists built by the front-end. */
7815 Setup_Asm_Outputs (gnat_node);
7816 while (Present (gnat_temp = Asm_Output_Variable ()))
7818 tree gnu_value = gnat_to_gnu (gnat_temp);
7819 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7820 (Asm_Output_Constraint ()));
7822 gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
7823 Next_Asm_Output ();
7826 Setup_Asm_Inputs (gnat_node);
7827 while (Present (gnat_temp = Asm_Input_Value ()))
7829 tree gnu_value = gnat_to_gnu (gnat_temp);
7830 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7831 (Asm_Input_Constraint ()));
7833 gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
7834 Next_Asm_Input ();
7837 Clobber_Setup (gnat_node);
7838 while ((clobber = (char *) Clobber_Get_Next ()))
7839 gnu_clobbers
7840 = tree_cons (NULL_TREE,
7841 build_string (strlen (clobber) + 1, clobber),
7842 gnu_clobbers);
7844 /* Then perform some standard checking and processing on the
7845 operands. In particular, mark them addressable if needed. */
7846 gnu_outputs = nreverse (gnu_outputs);
7847 noutputs = list_length (gnu_outputs);
7848 gnu_inputs = nreverse (gnu_inputs);
7849 ninputs = list_length (gnu_inputs);
7850 oconstraints = XALLOCAVEC (const char *, noutputs);
7852 for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
7854 tree output = TREE_VALUE (tail);
7855 constraint
7856 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7857 oconstraints[i] = constraint;
7859 if (parse_output_constraint (&constraint, i, ninputs, noutputs,
7860 &allows_mem, &allows_reg, &fake))
7862 /* If the operand is going to end up in memory,
7863 mark it addressable. Note that we don't test
7864 allows_mem like in the input case below; this
7865 is modeled on the C front-end. */
7866 if (!allows_reg)
7868 output = remove_conversions (output, false);
7869 if (TREE_CODE (output) == CONST_DECL
7870 && DECL_CONST_CORRESPONDING_VAR (output))
7871 output = DECL_CONST_CORRESPONDING_VAR (output);
7872 if (!gnat_mark_addressable (output))
7873 output = error_mark_node;
7876 else
7877 output = error_mark_node;
7879 TREE_VALUE (tail) = output;
7882 for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
7884 tree input = TREE_VALUE (tail);
7885 constraint
7886 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7888 if (parse_input_constraint (&constraint, i, ninputs, noutputs,
7889 0, oconstraints,
7890 &allows_mem, &allows_reg))
7892 /* If the operand is going to end up in memory,
7893 mark it addressable. */
7894 if (!allows_reg && allows_mem)
7896 input = remove_conversions (input, false);
7897 if (TREE_CODE (input) == CONST_DECL
7898 && DECL_CONST_CORRESPONDING_VAR (input))
7899 input = DECL_CONST_CORRESPONDING_VAR (input);
7900 if (!gnat_mark_addressable (input))
7901 input = error_mark_node;
7904 else
7905 input = error_mark_node;
7907 TREE_VALUE (tail) = input;
7910 gnu_result = build5 (ASM_EXPR, void_type_node,
7911 gnu_template, gnu_outputs,
7912 gnu_inputs, gnu_clobbers, NULL_TREE);
7913 ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
7915 else
7916 gnu_result = alloc_stmt_list ();
7918 break;
7920 /****************/
7921 /* Added Nodes */
7922 /****************/
7924 /* Markers are created by the ABE mechanism to capture information which
7925 is either unavailable of expensive to recompute. Markers do not have
7926 and runtime semantics, and should be ignored. */
7928 case N_Call_Marker:
7929 case N_Variable_Reference_Marker:
7930 gnu_result = alloc_stmt_list ();
7931 break;
7933 case N_Expression_With_Actions:
7934 /* This construct doesn't define a scope so we don't push a binding
7935 level around the statement list, but we wrap it in a SAVE_EXPR to
7936 protect it from unsharing. Elaborate the expression as part of the
7937 same statement group as the actions so that the type declaration
7938 gets inserted there as well. This ensures that the type elaboration
7939 code is issued past the actions computing values on which it might
7940 depend. */
7941 start_stmt_group ();
7942 add_stmt_list (Actions (gnat_node));
7943 gnu_expr = gnat_to_gnu (Expression (gnat_node));
7944 gnu_result = end_stmt_group ();
7946 gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
7947 TREE_SIDE_EFFECTS (gnu_result) = 1;
7949 gnu_result
7950 = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
7951 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7952 break;
7954 case N_Freeze_Entity:
7955 start_stmt_group ();
7956 process_freeze_entity (gnat_node);
7957 process_decls (Actions (gnat_node), Empty, Empty, true, true);
7958 gnu_result = end_stmt_group ();
7959 break;
7961 case N_Freeze_Generic_Entity:
7962 gnu_result = alloc_stmt_list ();
7963 break;
7965 case N_Itype_Reference:
7966 if (!present_gnu_tree (Itype (gnat_node)))
7967 process_type (Itype (gnat_node));
7968 gnu_result = alloc_stmt_list ();
7969 break;
7971 case N_Free_Statement:
7972 gnat_temp = Expression (gnat_node);
7974 if (!type_annotate_only)
7976 tree gnu_ptr, gnu_ptr_type, gnu_obj_type, gnu_actual_obj_type;
7978 const Entity_Id gnat_desig_type
7979 = Designated_Type (Underlying_Type (Etype (gnat_temp)));
7981 /* Make sure the designated type is complete before dereferencing,
7982 in case it is a Taft Amendment type. */
7983 (void) gnat_to_gnu_entity (gnat_desig_type, NULL_TREE, false);
7985 gnu_ptr = gnat_to_gnu (gnat_temp);
7986 gnu_ptr_type = TREE_TYPE (gnu_ptr);
7988 /* If this is a thin pointer, we must first dereference it to create
7989 a fat pointer, then go back below to a thin pointer. The reason
7990 for this is that we need to have a fat pointer someplace in order
7991 to properly compute the size. */
7992 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7993 gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
7994 build_unary_op (INDIRECT_REF, NULL_TREE,
7995 gnu_ptr));
7997 /* If this is a fat pointer, the object must have been allocated with
7998 the template in front of the array. So pass the template address,
7999 and get the total size; do it by converting to a thin pointer. */
8000 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
8001 gnu_ptr
8002 = convert (build_pointer_type
8003 (TYPE_OBJECT_RECORD_TYPE
8004 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
8005 gnu_ptr);
8007 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
8009 /* If this is a thin pointer, the object must have been allocated with
8010 the template in front of the array. So pass the template address,
8011 and get the total size. */
8012 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
8013 gnu_ptr
8014 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
8015 gnu_ptr,
8016 fold_build1 (NEGATE_EXPR, sizetype,
8017 byte_position
8018 (DECL_CHAIN
8019 TYPE_FIELDS ((gnu_obj_type)))));
8021 /* If we have a special dynamic constrained subtype on the node, use
8022 it to compute the size; otherwise, use the designated subtype. */
8023 if (Present (Actual_Designated_Subtype (gnat_node)))
8025 gnu_actual_obj_type
8026 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
8028 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
8029 gnu_actual_obj_type
8030 = build_unc_object_type_from_ptr (gnu_ptr_type,
8031 gnu_actual_obj_type,
8032 get_identifier ("DEALLOC"),
8033 false);
8035 else
8036 gnu_actual_obj_type = gnu_obj_type;
8038 tree gnu_size = TYPE_SIZE_UNIT (gnu_actual_obj_type);
8039 gnu_size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_size, gnu_ptr);
8041 gnu_result
8042 = build_call_alloc_dealloc (gnu_ptr, gnu_size, gnu_obj_type,
8043 Procedure_To_Call (gnat_node),
8044 Storage_Pool (gnat_node),
8045 gnat_node);
8047 break;
8049 case N_Raise_Constraint_Error:
8050 case N_Raise_Program_Error:
8051 case N_Raise_Storage_Error:
8052 if (type_annotate_only)
8053 gnu_result = alloc_stmt_list ();
8054 else
8055 gnu_result = Raise_Error_to_gnu (gnat_node, &gnu_result_type);
8056 break;
8058 case N_Validate_Unchecked_Conversion:
8059 /* The only validation we currently do on an unchecked conversion is
8060 that of aliasing assumptions. */
8061 if (flag_strict_aliasing)
8062 gnat_validate_uc_list.safe_push (gnat_node);
8063 gnu_result = alloc_stmt_list ();
8064 break;
8066 case N_Function_Specification:
8067 case N_Procedure_Specification:
8068 case N_Op_Concat:
8069 case N_Component_Association:
8070 /* These nodes should only be present when annotating types. */
8071 gcc_assert (type_annotate_only);
8072 gnu_result = alloc_stmt_list ();
8073 break;
8075 default:
8076 /* Other nodes are not supposed to reach here. */
8077 gcc_unreachable ();
8080 /* If we are in the elaboration procedure, check if we are violating the
8081 No_Elaboration_Code restriction by having a non-empty statement. */
8082 if (statement_node_p (gnat_node)
8083 && !(TREE_CODE (gnu_result) == STATEMENT_LIST
8084 && empty_stmt_list_p (gnu_result))
8085 && current_function_decl == get_elaboration_procedure ())
8086 Check_Elaboration_Code_Allowed (gnat_node);
8088 /* If we pushed the processing of the elaboration routine, pop it back. */
8089 if (went_into_elab_proc)
8090 current_function_decl = NULL_TREE;
8092 /* When not optimizing, turn boolean rvalues B into B != false tests
8093 so that we can put the location information of the reference to B on
8094 the inequality operator for better debug info. */
8095 if (!optimize
8096 && TREE_CODE (gnu_result) != INTEGER_CST
8097 && TREE_CODE (gnu_result) != TYPE_DECL
8098 && (kind == N_Identifier
8099 || kind == N_Expanded_Name
8100 || kind == N_Explicit_Dereference
8101 || kind == N_Indexed_Component
8102 || kind == N_Selected_Component)
8103 && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
8104 && Nkind (Parent (gnat_node)) != N_Attribute_Reference
8105 && Nkind (Parent (gnat_node)) != N_Pragma_Argument_Association
8106 && Nkind (Parent (gnat_node)) != N_Variant_Part
8107 && !lvalue_required_p (gnat_node, gnu_result_type, false, false))
8109 gnu_result
8110 = build_binary_op (NE_EXPR, gnu_result_type,
8111 convert (gnu_result_type, gnu_result),
8112 convert (gnu_result_type, boolean_false_node));
8113 if (TREE_CODE (gnu_result) != INTEGER_CST)
8114 set_gnu_expr_location_from_node (gnu_result, gnat_node);
8117 /* Set the location information on the result if it's not a simple name
8118 or something that contains a simple name, for example a tag, because
8119 we don"t want all the references to get the location of the first use.
8120 Note that we may have no result if we tried to build a CALL_EXPR node
8121 to a procedure with no side-effects and optimization is enabled. */
8122 else if (kind != N_Identifier
8123 && !(kind == N_Selected_Component
8124 && Chars (Selector_Name (gnat_node)) == Name_uTag)
8125 && gnu_result
8126 && EXPR_P (gnu_result))
8127 set_gnu_expr_location_from_node (gnu_result, gnat_node);
8129 /* If we're supposed to return something of void_type, it means we have
8130 something we're elaborating for effect, so just return. */
8131 if (TREE_CODE (gnu_result_type) == VOID_TYPE)
8132 return gnu_result;
8134 /* If the result is a constant that overflowed, raise Constraint_Error. */
8135 if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
8137 post_error ("??Constraint_Error will be raised at run time", gnat_node);
8138 gnu_result
8139 = build1 (NULL_EXPR, gnu_result_type,
8140 build_call_raise (CE_Overflow_Check_Failed, gnat_node,
8141 N_Raise_Constraint_Error));
8144 /* If the result has side-effects and is of an unconstrained type, protect
8145 the expression in case it will be referenced multiple times, i.e. for
8146 its value and to compute the size of an object. But do it neither for
8147 an object nor a renaming declaration, nor a return statement of a call
8148 to a function that returns an unconstrained record type with default
8149 discriminant, because there is no size to be computed in these cases
8150 and this will create a useless temporary. We must do this before any
8151 conversions. */
8152 if (TREE_SIDE_EFFECTS (gnu_result)
8153 && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
8154 || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type)))
8155 && !(TREE_CODE (gnu_result) == CALL_EXPR
8156 && type_is_padding_self_referential (TREE_TYPE (gnu_result))
8157 && (Nkind (Parent (gnat_node)) == N_Object_Declaration
8158 || Nkind (Parent (gnat_node)) == N_Object_Renaming_Declaration
8159 || Nkind (Parent (gnat_node)) == N_Simple_Return_Statement)))
8160 gnu_result = gnat_protect_expr (gnu_result);
8162 /* Now convert the result to the result type, unless we are in one of the
8163 following cases:
8165 1. If this is the LHS of an assignment or an actual parameter of a
8166 call, return the result almost unmodified since the RHS will have
8167 to be converted to our type in that case, unless the result type
8168 has a simpler size or for array types because this size might be
8169 changed in-between. Likewise if there is just a no-op unchecked
8170 conversion in-between. Similarly, don't convert integral types
8171 that are the operands of an unchecked conversion since we need
8172 to ignore those conversions (for 'Valid).
8174 2. If we have a label (which doesn't have any well-defined type), a
8175 field or an error, return the result almost unmodified. Similarly,
8176 if the two types are record types with the same name, don't convert.
8177 This will be the case when we are converting from a packable version
8178 of a type to its original type and we need those conversions to be
8179 NOPs in order for assignments into these types to work properly.
8181 3. If the type is void or if we have no result, return error_mark_node
8182 to show we have no result.
8184 4. If this is a call to a function that returns with variable size and
8185 the call is used as the expression in either an object or a renaming
8186 declaration, return the result unmodified because we want to use the
8187 return slot optimization in this case.
8189 5. If this is a reference to an unconstrained array which is used as the
8190 prefix of an attribute reference that requires an lvalue, return the
8191 result unmodified because we want to return the original bounds.
8193 6. Finally, if the type of the result is already correct. */
8195 if (Present (Parent (gnat_node))
8196 && (lhs_or_actual_p (gnat_node)
8197 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
8198 && unchecked_conversion_nop (Parent (gnat_node)))
8199 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
8200 && !AGGREGATE_TYPE_P (gnu_result_type)
8201 && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
8202 && !(TYPE_SIZE (gnu_result_type)
8203 && TYPE_SIZE (TREE_TYPE (gnu_result))
8204 && AGGREGATE_TYPE_P (gnu_result_type)
8205 == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))
8206 && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
8207 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
8208 != INTEGER_CST))
8209 || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
8210 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
8211 && (CONTAINS_PLACEHOLDER_P
8212 (TYPE_SIZE (TREE_TYPE (gnu_result)))))
8213 || (TREE_CODE (gnu_result_type) == ARRAY_TYPE
8214 && TREE_CODE (TREE_TYPE (gnu_result)) == ARRAY_TYPE))
8215 && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
8216 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
8218 /* Remove padding only if the inner object is of self-referential
8219 size: in that case it must be an object of unconstrained type
8220 with a default discriminant and we want to avoid copying too
8221 much data. But do not remove it if it is already too small. */
8222 if (type_is_padding_self_referential (TREE_TYPE (gnu_result))
8223 && !(TREE_CODE (gnu_result) == COMPONENT_REF
8224 && DECL_BIT_FIELD (TREE_OPERAND (gnu_result, 1))
8225 && DECL_SIZE (TREE_OPERAND (gnu_result, 1))
8226 != TYPE_SIZE (TREE_TYPE (gnu_result))))
8227 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
8228 gnu_result);
8231 else if (TREE_CODE (gnu_result) == LABEL_DECL
8232 || TREE_CODE (gnu_result) == FIELD_DECL
8233 || TREE_CODE (gnu_result) == ERROR_MARK
8234 || (TYPE_NAME (gnu_result_type)
8235 == TYPE_NAME (TREE_TYPE (gnu_result))
8236 && TREE_CODE (gnu_result_type) == RECORD_TYPE
8237 && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
8239 /* Remove any padding. */
8240 gnu_result = maybe_padded_object (gnu_result);
8243 else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
8244 gnu_result = error_mark_node;
8246 else if (TREE_CODE (gnu_result) == CALL_EXPR
8247 && Present (Parent (gnat_node))
8248 && (Nkind (Parent (gnat_node)) == N_Object_Declaration
8249 || Nkind (Parent (gnat_node)) == N_Object_Renaming_Declaration)
8250 && return_type_with_variable_size_p (TREE_TYPE (gnu_result)))
8253 else if (TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF
8254 && Present (Parent (gnat_node))
8255 && Nkind (Parent (gnat_node)) == N_Attribute_Reference
8256 && lvalue_required_for_attribute_p (Parent (gnat_node)))
8259 else if (TREE_TYPE (gnu_result) != gnu_result_type)
8260 gnu_result = convert (gnu_result_type, gnu_result);
8262 /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result. */
8263 while ((TREE_CODE (gnu_result) == NOP_EXPR
8264 || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
8265 && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
8266 gnu_result = TREE_OPERAND (gnu_result, 0);
8268 return gnu_result;
8271 /* Similar to gnat_to_gnu, but discard any object that might be created in
8272 the course of the translation of GNAT_NODE, which must be an "external"
8273 expression in the sense that it will be elaborated elsewhere. */
8275 tree
8276 gnat_to_gnu_external (Node_Id gnat_node)
8278 const int save_force_global = force_global;
8279 bool went_into_elab_proc;
8281 /* Force the local context and create a fake scope that we zap
8282 at the end so declarations will not be stuck either in the
8283 global varpool or in the current scope. */
8284 if (!current_function_decl)
8286 current_function_decl = get_elaboration_procedure ();
8287 went_into_elab_proc = true;
8289 else
8290 went_into_elab_proc = false;
8291 force_global = 0;
8292 gnat_pushlevel ();
8294 tree gnu_result = gnat_to_gnu (gnat_node);
8296 gnat_zaplevel ();
8297 force_global = save_force_global;
8298 if (went_into_elab_proc)
8299 current_function_decl = NULL_TREE;
8301 /* Do not import locations from external units. */
8302 if (gnu_result && EXPR_P (gnu_result))
8303 SET_EXPR_LOCATION (gnu_result, UNKNOWN_LOCATION);
8305 return gnu_result;
8308 /* Return true if the statement list STMT_LIST is empty. */
8310 static bool
8311 empty_stmt_list_p (tree stmt_list)
8313 tree_stmt_iterator tsi;
8315 for (tsi = tsi_start (stmt_list); !tsi_end_p (tsi); tsi_next (&tsi))
8317 tree stmt = tsi_stmt (tsi);
8319 /* Anything else than an empty STMT_STMT counts as something. */
8320 if (TREE_CODE (stmt) != STMT_STMT || STMT_STMT_STMT (stmt))
8321 return false;
8324 return true;
8327 /* Record the current code position in GNAT_NODE. */
8329 static void
8330 record_code_position (Node_Id gnat_node)
8332 tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
8334 add_stmt_with_node (stmt_stmt, gnat_node);
8335 save_gnu_tree (gnat_node, stmt_stmt, true);
8338 /* Insert the code for GNAT_NODE at the position saved for that node. */
8340 static void
8341 insert_code_for (Node_Id gnat_node)
8343 tree code = gnat_to_gnu (gnat_node);
8345 /* It's too late to remove the STMT_STMT itself at this point. */
8346 if (!empty_stmt_list_p (code))
8347 STMT_STMT_STMT (get_gnu_tree (gnat_node)) = code;
8349 save_gnu_tree (gnat_node, NULL_TREE, true);
8352 /* Start a new statement group chained to the previous group. */
8354 void
8355 start_stmt_group (void)
8357 struct stmt_group *group = stmt_group_free_list;
8359 /* First see if we can get one from the free list. */
8360 if (group)
8361 stmt_group_free_list = group->previous;
8362 else
8363 group = ggc_alloc<stmt_group> ();
8365 group->previous = current_stmt_group;
8366 group->stmt_list = group->block = group->cleanups = NULL_TREE;
8367 current_stmt_group = group;
8370 /* Add GNU_STMT to the current statement group. If it is an expression with
8371 no effects, it is ignored. */
8373 void
8374 add_stmt (tree gnu_stmt)
8376 append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
8379 /* Similar, but the statement is always added, regardless of side-effects. */
8381 void
8382 add_stmt_force (tree gnu_stmt)
8384 append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
8387 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE. */
8389 void
8390 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
8392 if (Present (gnat_node))
8393 set_expr_location_from_node (gnu_stmt, gnat_node);
8394 add_stmt (gnu_stmt);
8397 /* Similar, but the statement is always added, regardless of side-effects. */
8399 void
8400 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
8402 if (Present (gnat_node))
8403 set_expr_location_from_node (gnu_stmt, gnat_node);
8404 add_stmt_force (gnu_stmt);
8407 /* Add a declaration statement for GNU_DECL to the current statement group.
8408 Get the SLOC to be put onto the statement from GNAT_NODE. */
8410 void
8411 add_decl_expr (tree gnu_decl, Node_Id gnat_node)
8413 tree type = TREE_TYPE (gnu_decl);
8414 tree gnu_stmt, gnu_init;
8416 /* If this is a variable that Gigi is to ignore, we may have been given
8417 an ERROR_MARK. So test for it. We also might have been given a
8418 reference for a renaming. So only do something for a decl. Also
8419 ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE. */
8420 if (!DECL_P (gnu_decl)
8421 || (TREE_CODE (gnu_decl) == TYPE_DECL
8422 && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
8423 return;
8425 gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
8427 /* If we are external or global, we don't want to output the DECL_EXPR for
8428 this DECL node since we already have evaluated the expressions in the
8429 sizes and positions as globals and doing it again would be wrong. */
8430 if (DECL_EXTERNAL (gnu_decl) || global_bindings_p ())
8432 /* Mark everything as used to prevent node sharing with subprograms.
8433 Note that walk_tree knows how to deal with TYPE_DECL, but neither
8434 VAR_DECL nor CONST_DECL. This appears to be somewhat arbitrary. */
8435 MARK_VISITED (gnu_stmt);
8436 if (TREE_CODE (gnu_decl) == VAR_DECL
8437 || TREE_CODE (gnu_decl) == CONST_DECL)
8439 MARK_VISITED (DECL_SIZE (gnu_decl));
8440 MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
8441 MARK_VISITED (DECL_INITIAL (gnu_decl));
8444 else
8445 add_stmt_with_node (gnu_stmt, gnat_node);
8447 /* Mark our TYPE_ADA_SIZE field now since it will not be gimplified. */
8448 if (TREE_CODE (gnu_decl) == TYPE_DECL
8449 && RECORD_OR_UNION_TYPE_P (type)
8450 && !TYPE_FAT_POINTER_P (type))
8451 MARK_VISITED (TYPE_ADA_SIZE (type));
8453 /* If this is a variable and an initializer is attached to it, it must be
8454 valid for the context. Similar to init_const in create_var_decl. */
8455 if (TREE_CODE (gnu_decl) == VAR_DECL
8456 && (gnu_init = DECL_INITIAL (gnu_decl))
8457 && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
8458 || (TREE_STATIC (gnu_decl)
8459 && !initializer_constant_valid_p (gnu_init,
8460 TREE_TYPE (gnu_init)))))
8462 DECL_INITIAL (gnu_decl) = NULL_TREE;
8463 if (TREE_READONLY (gnu_decl))
8465 TREE_READONLY (gnu_decl) = 0;
8466 DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
8469 /* Remove any padding so the assignment is done properly. */
8470 gnu_decl = maybe_padded_object (gnu_decl);
8472 gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_decl, gnu_init);
8473 add_stmt_with_node (gnu_stmt, gnat_node);
8477 /* Callback for walk_tree to mark the visited trees rooted at *TP. */
8479 static tree
8480 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
8482 tree t = *tp;
8484 if (TREE_VISITED (t))
8485 *walk_subtrees = 0;
8487 /* Don't mark a dummy type as visited because we want to mark its sizes
8488 and fields once it's filled in. */
8489 else if (!TYPE_IS_DUMMY_P (t))
8490 TREE_VISITED (t) = 1;
8492 /* The test in gimplify_type_sizes is on the main variant. */
8493 if (TYPE_P (t))
8494 TYPE_SIZES_GIMPLIFIED (TYPE_MAIN_VARIANT (t)) = 1;
8496 return NULL_TREE;
8499 /* Mark nodes rooted at T with TREE_VISITED and types as having their
8500 sized gimplified. We use this to indicate all variable sizes and
8501 positions in global types may not be shared by any subprogram. */
8503 void
8504 mark_visited (tree t)
8506 walk_tree (&t, mark_visited_r, NULL, NULL);
8509 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
8510 set its location to that of GNAT_NODE if present, but with column info
8511 cleared so that conditional branches generated as part of the cleanup
8512 code do not interfere with coverage analysis tools. */
8514 static void
8515 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
8517 if (Present (gnat_node))
8518 set_expr_location_from_node (gnu_cleanup, gnat_node, true);
8520 /* An EH_ELSE_EXPR must be by itself, and that's all we need when we
8521 use it. The assert below makes sure that is so. Should we ever
8522 need more than that, we could combine EH_ELSE_EXPRs, and copy
8523 non-EH_ELSE_EXPR stmts into both cleanup paths of an
8524 EH_ELSE_EXPR. */
8525 if (TREE_CODE (gnu_cleanup) == EH_ELSE_EXPR)
8527 gcc_assert (!current_stmt_group->cleanups);
8528 current_stmt_group->cleanups = gnu_cleanup;
8530 else
8532 gcc_assert (!current_stmt_group->cleanups
8533 || (TREE_CODE (current_stmt_group->cleanups)
8534 != EH_ELSE_EXPR));
8535 append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
8539 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK. */
8541 void
8542 set_block_for_group (tree gnu_block)
8544 gcc_assert (!current_stmt_group->block);
8545 current_stmt_group->block = gnu_block;
8548 /* Return code corresponding to the current code group. It is normally
8549 a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
8550 BLOCK or cleanups were set. */
8552 tree
8553 end_stmt_group (void)
8555 struct stmt_group *group = current_stmt_group;
8556 tree gnu_retval = group->stmt_list;
8558 /* If this is a null list, allocate a new STATEMENT_LIST. Then, if there
8559 are cleanups, make a TRY_FINALLY_EXPR. Last, if there is a BLOCK,
8560 make a BIND_EXPR. Note that we nest in that because the cleanup may
8561 reference variables in the block. */
8562 if (!gnu_retval)
8563 gnu_retval = alloc_stmt_list ();
8565 if (group->cleanups)
8566 gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
8567 group->cleanups);
8569 if (current_stmt_group->block)
8570 gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
8571 gnu_retval, group->block);
8573 /* Remove this group from the stack and add it to the free list. */
8574 current_stmt_group = group->previous;
8575 group->previous = stmt_group_free_list;
8576 stmt_group_free_list = group;
8578 return gnu_retval;
8581 /* Return whether the current statement group may fall through. */
8583 static inline bool
8584 stmt_group_may_fallthru (void)
8586 if (current_stmt_group->stmt_list)
8587 return block_may_fallthru (current_stmt_group->stmt_list);
8588 else
8589 return true;
8592 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
8593 statements.*/
8595 static void
8596 add_stmt_list (List_Id gnat_list)
8598 Node_Id gnat_node;
8600 if (Present (gnat_list))
8601 for (gnat_node = First (gnat_list); Present (gnat_node);
8602 gnat_node = Next (gnat_node))
8603 add_stmt (gnat_to_gnu (gnat_node));
8606 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
8607 If BINDING_P is true, push and pop a binding level around the list. */
8609 static tree
8610 build_stmt_group (List_Id gnat_list, bool binding_p)
8612 start_stmt_group ();
8614 if (binding_p)
8615 gnat_pushlevel ();
8617 add_stmt_list (gnat_list);
8619 if (binding_p)
8620 gnat_poplevel ();
8622 return end_stmt_group ();
8625 /* Generate GIMPLE in place for the expression at *EXPR_P. */
8628 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
8629 gimple_seq *post_p ATTRIBUTE_UNUSED)
8631 tree expr = *expr_p;
8632 tree type = TREE_TYPE (expr);
8633 tree op;
8635 if (IS_ADA_STMT (expr))
8636 return gnat_gimplify_stmt (expr_p);
8638 switch (TREE_CODE (expr))
8640 case NULL_EXPR:
8641 /* If this is an aggregate type, build a null pointer of the appropriate
8642 type and dereference it. */
8643 if (AGGREGATE_TYPE_P (type)
8644 || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
8645 *expr_p = build_unary_op (INDIRECT_REF, NULL_TREE,
8646 convert (build_pointer_type (type),
8647 integer_zero_node));
8648 /* Otherwise, just make a VAR_DECL. */
8649 else
8651 *expr_p = create_tmp_var (type, NULL);
8652 suppress_warning (*expr_p);
8655 gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
8656 return GS_OK;
8658 case UNCONSTRAINED_ARRAY_REF:
8659 /* We should only do this if we are just elaborating for side-effects,
8660 but we can't know that yet. */
8661 *expr_p = TREE_OPERAND (*expr_p, 0);
8662 return GS_OK;
8664 case ADDR_EXPR:
8665 op = TREE_OPERAND (expr, 0);
8667 /* If we are taking the address of a constant CONSTRUCTOR, make sure it
8668 is put into static memory. We know that it's going to be read-only
8669 given the semantics we have and it must be in static memory when the
8670 reference is in an elaboration procedure. */
8671 if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
8673 tree addr = build_fold_addr_expr (tree_output_constant_def (op));
8674 *expr_p = fold_convert (type, addr);
8675 return GS_ALL_DONE;
8678 /* Replace atomic loads with their first argument. That's necessary
8679 because the gimplifier would create a temporary otherwise. */
8680 if (TREE_SIDE_EFFECTS (op))
8681 while (handled_component_p (op) || CONVERT_EXPR_P (op))
8683 tree inner = TREE_OPERAND (op, 0);
8684 if (TREE_CODE (inner) == CALL_EXPR && call_is_atomic_load (inner))
8686 tree t = CALL_EXPR_ARG (inner, 0);
8687 if (TREE_CODE (t) == NOP_EXPR)
8688 t = TREE_OPERAND (t, 0);
8689 if (TREE_CODE (t) == ADDR_EXPR)
8690 TREE_OPERAND (op, 0) = TREE_OPERAND (t, 0);
8691 else
8692 TREE_OPERAND (op, 0) = build_fold_indirect_ref (t);
8694 else
8695 op = inner;
8698 return GS_UNHANDLED;
8700 case CALL_EXPR:
8701 /* If we are passing a constant fat pointer CONSTRUCTOR, make sure it is
8702 put into static memory; this performs a restricted version of constant
8703 propagation on fat pointers in calls. But do not do it for strings to
8704 avoid blocking concatenation in the caller when it is inlined. */
8705 for (int i = 0; i < call_expr_nargs (expr); i++)
8707 tree arg = *(CALL_EXPR_ARGP (expr) + i);
8709 if (TREE_CODE (arg) == CONSTRUCTOR
8710 && TREE_CONSTANT (arg)
8711 && TYPE_IS_FAT_POINTER_P (TREE_TYPE (arg)))
8713 tree t = CONSTRUCTOR_ELT (arg, 0)->value;
8714 if (TREE_CODE (t) == NOP_EXPR)
8715 t = TREE_OPERAND (t, 0);
8716 if (TREE_CODE (t) == ADDR_EXPR)
8717 t = TREE_OPERAND (t, 0);
8718 if (TREE_CODE (t) != STRING_CST)
8719 *(CALL_EXPR_ARGP (expr) + i) = tree_output_constant_def (arg);
8723 return GS_UNHANDLED;
8725 case VIEW_CONVERT_EXPR:
8726 op = TREE_OPERAND (expr, 0);
8728 /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
8729 type to a scalar one, explicitly create the local temporary. That's
8730 required if the type is passed by reference. */
8731 if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
8732 && AGGREGATE_TYPE_P (TREE_TYPE (op))
8733 && !AGGREGATE_TYPE_P (type))
8735 tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
8736 gimple_add_tmp_var (new_var);
8738 mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
8739 gimplify_and_add (mod, pre_p);
8741 TREE_OPERAND (expr, 0) = new_var;
8742 return GS_OK;
8745 return GS_UNHANDLED;
8747 case DECL_EXPR:
8748 op = DECL_EXPR_DECL (expr);
8750 /* The expressions for the RM bounds must be gimplified to ensure that
8751 they are properly elaborated. See gimplify_decl_expr. */
8752 if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
8753 && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
8754 switch (TREE_CODE (TREE_TYPE (op)))
8756 case INTEGER_TYPE:
8757 case ENUMERAL_TYPE:
8758 case BOOLEAN_TYPE:
8759 case REAL_TYPE:
8761 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
8763 val = TYPE_RM_MIN_VALUE (type);
8764 if (val)
8766 gimplify_one_sizepos (&val, pre_p);
8767 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
8768 SET_TYPE_RM_MIN_VALUE (t, val);
8771 val = TYPE_RM_MAX_VALUE (type);
8772 if (val)
8774 gimplify_one_sizepos (&val, pre_p);
8775 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
8776 SET_TYPE_RM_MAX_VALUE (t, val);
8780 break;
8782 default:
8783 break;
8786 /* ... fall through ... */
8788 default:
8789 return GS_UNHANDLED;
8793 /* Generate GIMPLE in place for the statement at *STMT_P. */
8795 static enum gimplify_status
8796 gnat_gimplify_stmt (tree *stmt_p)
8798 tree stmt = *stmt_p;
8800 switch (TREE_CODE (stmt))
8802 case STMT_STMT:
8803 *stmt_p = STMT_STMT_STMT (stmt);
8804 return GS_OK;
8806 case LOOP_STMT:
8808 tree gnu_start_label = create_artificial_label (input_location);
8809 tree gnu_cond = LOOP_STMT_COND (stmt);
8810 tree gnu_update = LOOP_STMT_UPDATE (stmt);
8811 tree gnu_end_label = LOOP_STMT_LABEL (stmt);
8813 /* Build the condition expression from the test, if any. */
8814 if (gnu_cond)
8816 /* Deal with the optimization hints. */
8817 if (LOOP_STMT_IVDEP (stmt))
8818 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8819 build_int_cst (integer_type_node,
8820 annot_expr_ivdep_kind),
8821 integer_zero_node);
8822 if (LOOP_STMT_NO_UNROLL (stmt))
8823 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8824 build_int_cst (integer_type_node,
8825 annot_expr_unroll_kind),
8826 integer_one_node);
8827 if (LOOP_STMT_UNROLL (stmt))
8828 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8829 build_int_cst (integer_type_node,
8830 annot_expr_unroll_kind),
8831 build_int_cst (NULL_TREE, USHRT_MAX));
8832 if (LOOP_STMT_NO_VECTOR (stmt))
8833 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8834 build_int_cst (integer_type_node,
8835 annot_expr_no_vector_kind),
8836 integer_zero_node);
8837 if (LOOP_STMT_VECTOR (stmt))
8838 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8839 build_int_cst (integer_type_node,
8840 annot_expr_vector_kind),
8841 integer_zero_node);
8843 gnu_cond
8844 = build3 (COND_EXPR, void_type_node, gnu_cond, NULL_TREE,
8845 build1 (GOTO_EXPR, void_type_node, gnu_end_label));
8848 /* Set to emit the statements of the loop. */
8849 *stmt_p = NULL_TREE;
8851 /* We first emit the start label and then a conditional jump to the
8852 end label if there's a top condition, then the update if it's at
8853 the top, then the body of the loop, then a conditional jump to
8854 the end label if there's a bottom condition, then the update if
8855 it's at the bottom, and finally a jump to the start label and the
8856 definition of the end label. */
8857 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
8858 gnu_start_label),
8859 stmt_p);
8861 if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
8862 append_to_statement_list (gnu_cond, stmt_p);
8864 if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
8865 append_to_statement_list (gnu_update, stmt_p);
8867 append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
8869 if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
8870 append_to_statement_list (gnu_cond, stmt_p);
8872 if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
8873 append_to_statement_list (gnu_update, stmt_p);
8875 tree t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
8876 SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
8877 append_to_statement_list (t, stmt_p);
8879 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
8880 gnu_end_label),
8881 stmt_p);
8882 return GS_OK;
8885 case EXIT_STMT:
8886 /* Build a statement to jump to the corresponding end label, then
8887 see if it needs to be conditional. */
8888 *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
8889 if (EXIT_STMT_COND (stmt))
8890 *stmt_p = build3 (COND_EXPR, void_type_node,
8891 EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
8892 return GS_OK;
8894 default:
8895 gcc_unreachable ();
8899 /* Force a reference to each of the entities in GNAT_PACKAGE recursively.
8901 This routine is exclusively called in type_annotate mode, to compute DDA
8902 information for types in withed units, for ASIS use. */
8904 static void
8905 elaborate_all_entities_for_package (Entity_Id gnat_package)
8907 Entity_Id gnat_entity;
8909 for (gnat_entity = First_Entity (gnat_package);
8910 Present (gnat_entity);
8911 gnat_entity = Next_Entity (gnat_entity))
8913 const Entity_Kind kind = Ekind (gnat_entity);
8915 /* We are interested only in entities visible from the main unit. */
8916 if (!Is_Public (gnat_entity))
8917 continue;
8919 /* Skip stuff internal to the compiler. */
8920 if (Is_Intrinsic_Subprogram (gnat_entity))
8921 continue;
8922 if (kind == E_Operator)
8923 continue;
8924 if (IN (kind, Subprogram_Kind)
8925 && (Present (Alias (gnat_entity))
8926 || Is_Intrinsic_Subprogram (gnat_entity)))
8927 continue;
8928 if (Is_Itype (gnat_entity))
8929 continue;
8931 /* Skip named numbers. */
8932 if (IN (kind, Named_Kind))
8933 continue;
8935 /* Skip generic declarations. */
8936 if (IN (kind, Generic_Unit_Kind))
8937 continue;
8939 /* Skip formal objects. */
8940 if (IN (kind, Formal_Object_Kind))
8941 continue;
8943 /* Skip package bodies. */
8944 if (kind == E_Package_Body)
8945 continue;
8947 /* Skip limited views that point back to the main unit. */
8948 if (IN (kind, Incomplete_Kind)
8949 && From_Limited_With (gnat_entity)
8950 && In_Extended_Main_Code_Unit (Non_Limited_View (gnat_entity)))
8951 continue;
8953 /* Skip types that aren't frozen. */
8954 if (IN (kind, Type_Kind) && !Is_Frozen (gnat_entity))
8955 continue;
8957 /* Recurse on real packages that aren't in the main unit. */
8958 if (kind == E_Package)
8960 if (No (Renamed_Entity (gnat_entity))
8961 && !In_Extended_Main_Code_Unit (gnat_entity))
8962 elaborate_all_entities_for_package (gnat_entity);
8964 else
8965 gnat_to_gnu_entity (gnat_entity, NULL_TREE, false);
8969 /* Force a reference to each of the entities in packages withed by GNAT_NODE.
8970 Operate recursively but check that we aren't elaborating something more
8971 than once.
8973 This routine is exclusively called in type_annotate mode, to compute DDA
8974 information for types in withed units, for ASIS use. */
8976 static void
8977 elaborate_all_entities (Node_Id gnat_node)
8979 Entity_Id gnat_with_clause;
8981 /* Process each unit only once. As we trace the context of all relevant
8982 units transitively, including generic bodies, we may encounter the
8983 same generic unit repeatedly. */
8984 if (!present_gnu_tree (gnat_node))
8985 save_gnu_tree (gnat_node, integer_zero_node, true);
8987 /* Save entities in all context units. A body may have an implicit_with
8988 on its own spec, if the context includes a child unit, so don't save
8989 the spec twice. */
8990 for (gnat_with_clause = First (Context_Items (gnat_node));
8991 Present (gnat_with_clause);
8992 gnat_with_clause = Next (gnat_with_clause))
8993 if (Nkind (gnat_with_clause) == N_With_Clause
8994 && !present_gnu_tree (Library_Unit (gnat_with_clause))
8995 && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
8997 Node_Id gnat_unit = Library_Unit (gnat_with_clause);
8998 Entity_Id gnat_entity = Entity (Name (gnat_with_clause));
9000 elaborate_all_entities (gnat_unit);
9002 if (Ekind (gnat_entity) == E_Package
9003 && No (Renamed_Entity (gnat_entity)))
9004 elaborate_all_entities_for_package (gnat_entity);
9006 else if (Ekind (gnat_entity) == E_Generic_Package)
9008 Node_Id gnat_body = Corresponding_Body (Unit (gnat_unit));
9010 /* Retrieve compilation unit node of generic body. */
9011 while (Present (gnat_body)
9012 && Nkind (gnat_body) != N_Compilation_Unit)
9013 gnat_body = Parent (gnat_body);
9015 /* If body is available, elaborate its context. */
9016 if (Present (gnat_body))
9017 elaborate_all_entities (gnat_body);
9021 if (Nkind (Unit (gnat_node)) == N_Package_Body)
9022 elaborate_all_entities (Library_Unit (gnat_node));
9025 /* Do the processing of GNAT_NODE, an N_Freeze_Entity. */
9027 static void
9028 process_freeze_entity (Node_Id gnat_node)
9030 const Entity_Id gnat_entity = Entity (gnat_node);
9031 const Entity_Kind kind = Ekind (gnat_entity);
9032 tree gnu_old, gnu_new;
9034 /* If this is a package, generate code for the package body, if any. */
9035 if (kind == E_Package)
9037 const Node_Id gnat_decl = Parent (Declaration_Node (gnat_entity));
9038 if (Present (Corresponding_Body (gnat_decl)))
9039 insert_code_for (Parent (Corresponding_Body (gnat_decl)));
9040 return;
9043 /* Don't do anything for class-wide types as they are always transformed
9044 into their root type. */
9045 if (kind == E_Class_Wide_Type)
9046 return;
9048 /* Likewise for the entities internally used by the front-end to register
9049 primitives covering abstract interfaces, see Expand_N_Freeze_Entity. */
9050 if (Is_Subprogram (gnat_entity) && Present (Interface_Alias (gnat_entity)))
9051 return;
9053 /* Check for an old definition if this isn't an object with address clause,
9054 since the saved GCC tree is the address expression in that case. */
9055 gnu_old
9056 = present_gnu_tree (gnat_entity) && No (Address_Clause (gnat_entity))
9057 ? get_gnu_tree (gnat_entity) : NULL_TREE;
9059 /* Don't do anything for subprograms that may have been elaborated before
9060 their freeze nodes. This can happen, for example, because of an inner
9061 call in an instance body or because of previous compilation of a spec
9062 for inlining purposes. */
9063 if (gnu_old
9064 && ((TREE_CODE (gnu_old) == FUNCTION_DECL
9065 && (kind == E_Function || kind == E_Procedure))
9066 || (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_old))
9067 && kind == E_Subprogram_Type)))
9068 return;
9070 /* If we have a non-dummy type old tree, we have nothing to do, except for
9071 aborting, since this node was never delayed as it should have been. We
9072 let this happen for concurrent types and their Corresponding_Record_Type,
9073 however, because each might legitimately be elaborated before its own
9074 freeze node, e.g. while processing the other. */
9075 if (gnu_old
9076 && !(TREE_CODE (gnu_old) == TYPE_DECL
9077 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
9079 gcc_assert (Is_Concurrent_Type (gnat_entity)
9080 || (Is_Record_Type (gnat_entity)
9081 && Is_Concurrent_Record_Type (gnat_entity)));
9082 return;
9085 /* Reset the saved tree, if any, and elaborate the object or type for real.
9086 If there is a full view, elaborate it and use the result. And, if this
9087 is the root type of a class-wide type, reuse it for the latter. */
9088 if (gnu_old)
9090 save_gnu_tree (gnat_entity, NULL_TREE, false);
9092 if (Is_Incomplete_Or_Private_Type (gnat_entity)
9093 && Present (Full_View (gnat_entity)))
9095 Entity_Id full_view = Full_View (gnat_entity);
9097 save_gnu_tree (full_view, NULL_TREE, false);
9099 if (Is_Private_Type (full_view)
9100 && Present (Underlying_Full_View (full_view)))
9102 full_view = Underlying_Full_View (full_view);
9103 save_gnu_tree (full_view, NULL_TREE, false);
9107 if (Is_Type (gnat_entity)
9108 && Present (Class_Wide_Type (gnat_entity))
9109 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
9110 save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
9113 if (Is_Incomplete_Or_Private_Type (gnat_entity)
9114 && Present (Full_View (gnat_entity)))
9116 Entity_Id full_view = Full_View (gnat_entity);
9118 if (Is_Private_Type (full_view)
9119 && Present (Underlying_Full_View (full_view)))
9120 full_view = Underlying_Full_View (full_view);
9122 gnu_new = gnat_to_gnu_entity (full_view, NULL_TREE, true);
9124 /* Propagate back-annotations from full view to partial view. */
9125 if (!Known_Alignment (gnat_entity))
9126 Copy_Alignment (gnat_entity, full_view);
9128 if (!Known_Esize (gnat_entity))
9129 Copy_Esize (gnat_entity, full_view);
9131 if (!Known_RM_Size (gnat_entity))
9132 Copy_RM_Size (gnat_entity, full_view);
9134 /* The above call may have defined this entity (the simplest example
9135 of this is when we have a private enumeral type since the bounds
9136 will have the public view). */
9137 if (!present_gnu_tree (gnat_entity))
9138 save_gnu_tree (gnat_entity, gnu_new, false);
9140 else
9142 tree gnu_init
9143 = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
9144 && present_gnu_tree (Declaration_Node (gnat_entity)))
9145 ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
9147 gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, true);
9150 if (Is_Type (gnat_entity)
9151 && Present (Class_Wide_Type (gnat_entity))
9152 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
9153 save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
9155 /* If we have an old type and we've made pointers to this type, update those
9156 pointers. If this is a Taft amendment type in the main unit, we need to
9157 mark the type as used since other units referencing it don't see the full
9158 declaration and, therefore, cannot mark it as used themselves. */
9159 if (gnu_old)
9161 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
9162 TREE_TYPE (gnu_new));
9163 if (TYPE_DUMMY_IN_PROFILE_P (TREE_TYPE (gnu_old)))
9164 update_profiles_with (TREE_TYPE (gnu_old));
9165 if (DECL_TAFT_TYPE_P (gnu_old))
9166 used_types_insert (TREE_TYPE (gnu_new));
9170 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
9171 We make two passes, one to elaborate anything other than bodies (but
9172 we declare a function if there was no spec). The second pass
9173 elaborates the bodies.
9175 GNAT_END_LIST gives the element in the list past the end. Normally,
9176 this is Empty, but can be First_Real_Statement for a
9177 Handled_Sequence_Of_Statements.
9179 We make a complete pass through both lists if PASS1P is true, then make
9180 the second pass over both lists if PASS2P is true. The lists usually
9181 correspond to the public and private parts of a package. */
9183 static void
9184 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
9185 Node_Id gnat_end_list, bool pass1p, bool pass2p)
9187 List_Id gnat_decl_array[2];
9188 Node_Id gnat_decl;
9189 int i;
9191 gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
9193 if (pass1p)
9194 for (i = 0; i <= 1; i++)
9195 if (Present (gnat_decl_array[i]))
9196 for (gnat_decl = First (gnat_decl_array[i]);
9197 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
9199 /* For package specs, we recurse inside the declarations,
9200 thus taking the two pass approach inside the boundary. */
9201 if (Nkind (gnat_decl) == N_Package_Declaration
9202 && (Nkind (Specification (gnat_decl)
9203 == N_Package_Specification)))
9204 process_decls (Visible_Declarations (Specification (gnat_decl)),
9205 Private_Declarations (Specification (gnat_decl)),
9206 Empty, true, false);
9208 /* Similarly for any declarations in the actions of a
9209 freeze node. */
9210 else if (Nkind (gnat_decl) == N_Freeze_Entity)
9212 process_freeze_entity (gnat_decl);
9213 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
9216 /* Package bodies with freeze nodes get their elaboration deferred
9217 until the freeze node, but the code must be placed in the right
9218 place, so record the code position now. */
9219 else if (Nkind (gnat_decl) == N_Package_Body
9220 && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
9221 record_code_position (gnat_decl);
9223 else if (Nkind (gnat_decl) == N_Package_Body_Stub
9224 && Present (Library_Unit (gnat_decl))
9225 && Present (Freeze_Node
9226 (Corresponding_Spec
9227 (Proper_Body (Unit
9228 (Library_Unit (gnat_decl)))))))
9229 record_code_position
9230 (Proper_Body (Unit (Library_Unit (gnat_decl))));
9232 /* We defer most subprogram bodies to the second pass. For bodies
9233 that act as their own specs and stubs, the entity itself must be
9234 elaborated in the first pass, because it may be used in other
9235 declarations. */
9236 else if (Nkind (gnat_decl) == N_Subprogram_Body)
9238 if (Acts_As_Spec (gnat_decl))
9240 Entity_Id gnat_subprog = Defining_Entity (gnat_decl);
9242 if (!Is_Generic_Subprogram (gnat_subprog))
9243 gnat_to_gnu_entity (gnat_subprog, NULL_TREE, true);
9247 else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
9249 Entity_Id gnat_subprog
9250 = Defining_Entity (Specification (gnat_decl));
9252 if (!Is_Generic_Subprogram (gnat_subprog)
9253 && Ekind (gnat_subprog) != E_Subprogram_Body)
9254 gnat_to_gnu_entity (gnat_subprog, NULL_TREE, true);
9257 /* Concurrent stubs stand for the corresponding subprogram bodies,
9258 which are deferred like other bodies. */
9259 else if (Nkind (gnat_decl) == N_Task_Body_Stub
9260 || Nkind (gnat_decl) == N_Protected_Body_Stub)
9263 /* Renamed subprograms may not be elaborated yet at this point
9264 since renamings do not trigger freezing. Wait for the second
9265 pass to take care of them. */
9266 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
9269 else
9270 add_stmt (gnat_to_gnu (gnat_decl));
9273 /* Here we elaborate everything we deferred above except for package bodies,
9274 which are elaborated at their freeze nodes. Note that we must also
9275 go inside things (package specs and freeze nodes) the first pass did. */
9276 if (pass2p)
9277 for (i = 0; i <= 1; i++)
9278 if (Present (gnat_decl_array[i]))
9279 for (gnat_decl = First (gnat_decl_array[i]);
9280 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
9282 if (Nkind (gnat_decl) == N_Subprogram_Body
9283 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
9284 || Nkind (gnat_decl) == N_Task_Body_Stub
9285 || Nkind (gnat_decl) == N_Protected_Body_Stub)
9286 add_stmt (gnat_to_gnu (gnat_decl));
9288 else if (Nkind (gnat_decl) == N_Package_Declaration
9289 && (Nkind (Specification (gnat_decl)
9290 == N_Package_Specification)))
9291 process_decls (Visible_Declarations (Specification (gnat_decl)),
9292 Private_Declarations (Specification (gnat_decl)),
9293 Empty, false, true);
9295 else if (Nkind (gnat_decl) == N_Freeze_Entity)
9296 process_decls (Actions (gnat_decl), Empty, Empty, false, true);
9298 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
9299 add_stmt (gnat_to_gnu (gnat_decl));
9303 /* Make a unary operation of kind CODE using build_unary_op, but guard
9304 the operation by an overflow check. CODE can be one of NEGATE_EXPR
9305 or ABS_EXPR. GNU_TYPE is the type desired for the result. Usually
9306 the operation is to be performed in that type. GNAT_NODE is the gnat
9307 node conveying the source location for which the error should be
9308 signaled. */
9310 static tree
9311 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
9312 Node_Id gnat_node)
9314 gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
9316 operand = gnat_protect_expr (operand);
9318 return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
9319 operand, TYPE_MIN_VALUE (gnu_type)),
9320 build_unary_op (code, gnu_type, operand),
9321 CE_Overflow_Check_Failed, gnat_node);
9324 /* Make a binary operation of kind CODE using build_binary_op, but guard
9325 the operation by an overflow check. CODE can be one of PLUS_EXPR,
9326 MINUS_EXPR or MULT_EXPR. GNU_TYPE is the type desired for the result.
9327 Usually the operation is to be performed in that type. GNAT_NODE is
9328 the GNAT node conveying the source location for which the error should
9329 be signaled. */
9331 static tree
9332 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
9333 tree right, Node_Id gnat_node)
9335 const unsigned int precision = TYPE_PRECISION (gnu_type);
9336 tree lhs = gnat_protect_expr (left);
9337 tree rhs = gnat_protect_expr (right);
9338 tree type_max = TYPE_MAX_VALUE (gnu_type);
9339 tree type_min = TYPE_MIN_VALUE (gnu_type);
9340 tree gnu_expr, check;
9341 int sgn;
9343 /* Assert that the precision is a power of 2. */
9344 gcc_assert ((precision & (precision - 1)) == 0);
9346 /* Prefer a constant on the RHS to simplify checks. */
9347 if (TREE_CODE (rhs) != INTEGER_CST
9348 && TREE_CODE (lhs) == INTEGER_CST
9349 && (code == PLUS_EXPR || code == MULT_EXPR))
9351 tree tmp = lhs;
9352 lhs = rhs;
9353 rhs = tmp;
9356 gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
9358 /* If we can fold the expression to a constant, just return it.
9359 The caller will deal with overflow, no need to generate a check. */
9360 if (TREE_CODE (gnu_expr) == INTEGER_CST)
9361 return gnu_expr;
9363 /* If no operand is a constant, we use the generic implementation. */
9364 if (TREE_CODE (lhs) != INTEGER_CST && TREE_CODE (rhs) != INTEGER_CST)
9366 /* First convert the operands to the result type like build_binary_op.
9367 This is where the bias is made explicit for biased types. */
9368 lhs = convert (gnu_type, lhs);
9369 rhs = convert (gnu_type, rhs);
9371 /* Never inline a 64-bit mult for a 32-bit target, it's way too long. */
9372 if (code == MULT_EXPR && precision == 64 && BITS_PER_WORD < 64)
9374 tree int64 = gnat_type_for_size (64, 0);
9375 return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
9376 convert (int64, lhs),
9377 convert (int64, rhs)));
9380 /* Likewise for a 128-bit mult and a 64-bit target. */
9381 else if (code == MULT_EXPR && precision == 128 && BITS_PER_WORD < 128)
9383 tree int128 = gnat_type_for_size (128, 0);
9384 return convert (gnu_type, build_call_n_expr (mulv128_decl, 2,
9385 convert (int128, lhs),
9386 convert (int128, rhs)));
9389 enum internal_fn icode;
9391 switch (code)
9393 case PLUS_EXPR:
9394 icode = IFN_ADD_OVERFLOW;
9395 break;
9396 case MINUS_EXPR:
9397 icode = IFN_SUB_OVERFLOW;
9398 break;
9399 case MULT_EXPR:
9400 icode = IFN_MUL_OVERFLOW;
9401 break;
9402 default:
9403 gcc_unreachable ();
9406 tree gnu_ctype = build_complex_type (gnu_type);
9407 tree call
9408 = build_call_expr_internal_loc (UNKNOWN_LOCATION, icode, gnu_ctype, 2,
9409 lhs, rhs);
9410 tree tgt = save_expr (call);
9411 gnu_expr = build1 (REALPART_EXPR, gnu_type, tgt);
9412 check = fold_build2 (NE_EXPR, boolean_type_node,
9413 build1 (IMAGPART_EXPR, gnu_type, tgt),
9414 build_int_cst (gnu_type, 0));
9415 return
9416 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
9419 /* If one operand is a constant, we expose the overflow condition to enable
9420 a subsequent simplication or even elimination. */
9421 switch (code)
9423 case PLUS_EXPR:
9424 sgn = tree_int_cst_sgn (rhs);
9425 if (sgn > 0)
9426 /* When rhs > 0, overflow when lhs > type_max - rhs. */
9427 check = build_binary_op (GT_EXPR, boolean_type_node, lhs,
9428 build_binary_op (MINUS_EXPR, gnu_type,
9429 type_max, rhs));
9430 else if (sgn < 0)
9431 /* When rhs < 0, overflow when lhs < type_min - rhs. */
9432 check = build_binary_op (LT_EXPR, boolean_type_node, lhs,
9433 build_binary_op (MINUS_EXPR, gnu_type,
9434 type_min, rhs));
9435 else
9436 return gnu_expr;
9437 break;
9439 case MINUS_EXPR:
9440 if (TREE_CODE (lhs) == INTEGER_CST)
9442 sgn = tree_int_cst_sgn (lhs);
9443 if (sgn > 0)
9444 /* When lhs > 0, overflow when rhs < lhs - type_max. */
9445 check = build_binary_op (LT_EXPR, boolean_type_node, rhs,
9446 build_binary_op (MINUS_EXPR, gnu_type,
9447 lhs, type_max));
9448 else if (sgn < 0)
9449 /* When lhs < 0, overflow when rhs > lhs - type_min. */
9450 check = build_binary_op (GT_EXPR, boolean_type_node, rhs,
9451 build_binary_op (MINUS_EXPR, gnu_type,
9452 lhs, type_min));
9453 else
9454 return gnu_expr;
9456 else
9458 sgn = tree_int_cst_sgn (rhs);
9459 if (sgn > 0)
9460 /* When rhs > 0, overflow when lhs < type_min + rhs. */
9461 check = build_binary_op (LT_EXPR, boolean_type_node, lhs,
9462 build_binary_op (PLUS_EXPR, gnu_type,
9463 type_min, rhs));
9464 else if (sgn < 0)
9465 /* When rhs < 0, overflow when lhs > type_max + rhs. */
9466 check = build_binary_op (GT_EXPR, boolean_type_node, lhs,
9467 build_binary_op (PLUS_EXPR, gnu_type,
9468 type_max, rhs));
9469 else
9470 return gnu_expr;
9472 break;
9474 case MULT_EXPR:
9475 sgn = tree_int_cst_sgn (rhs);
9476 if (sgn > 0)
9478 if (integer_onep (rhs))
9479 return gnu_expr;
9481 tree lb = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
9482 tree ub = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
9484 /* When rhs > 1, overflow outside [type_min/rhs; type_max/rhs]. */
9485 check
9486 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9487 build_binary_op (LT_EXPR, boolean_type_node,
9488 lhs, lb),
9489 build_binary_op (GT_EXPR, boolean_type_node,
9490 lhs, ub));
9492 else if (sgn < 0)
9494 tree lb = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
9495 tree ub = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
9497 if (integer_minus_onep (rhs))
9498 /* When rhs == -1, overflow if lhs == type_min. */
9499 check
9500 = build_binary_op (EQ_EXPR, boolean_type_node, lhs, type_min);
9501 else
9502 /* When rhs < -1, overflow outside [type_max/rhs; type_min/rhs]. */
9503 check
9504 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9505 build_binary_op (LT_EXPR, boolean_type_node,
9506 lhs, lb),
9507 build_binary_op (GT_EXPR, boolean_type_node,
9508 lhs, ub));
9510 else
9511 return gnu_expr;
9512 break;
9514 default:
9515 gcc_unreachable ();
9518 return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
9521 /* GNU_COND contains the condition corresponding to an index, overflow or
9522 range check of value GNU_EXPR. Build a COND_EXPR that returns GNU_EXPR
9523 if GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
9524 REASON is the code that says why the exception is raised. GNAT_NODE is
9525 the node conveying the source location for which the error should be
9526 signaled.
9528 We used to propagate TREE_SIDE_EFFECTS from GNU_EXPR to the COND_EXPR,
9529 overwriting the setting inherited from the call statement, on the ground
9530 that the expression need not be evaluated just for the check. However
9531 that's incorrect because, in the GCC type system, its value is presumed
9532 to be valid so its comparison against the type bounds always yields true
9533 and, therefore, could be done without evaluating it; given that it can
9534 be a computation that overflows the bounds, the language may require the
9535 check to fail and thus the expression to be evaluated in this case. */
9537 static tree
9538 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
9540 tree gnu_call
9541 = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
9542 return
9543 fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
9544 build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
9545 SCALAR_FLOAT_TYPE_P (TREE_TYPE (gnu_expr))
9546 ? build_real (TREE_TYPE (gnu_expr), dconst0)
9547 : build_int_cst (TREE_TYPE (gnu_expr), 0)),
9548 gnu_expr);
9551 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
9552 checks if OVERFLOW_P is true. If TRUNCATE_P is true, do a fp-to-integer
9553 conversion with truncation, otherwise round. GNAT_NODE is the GNAT node
9554 conveying the source location for which the error should be signaled. */
9556 static tree
9557 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflow_p,
9558 bool truncate_p, Node_Id gnat_node)
9560 tree gnu_type = get_unpadded_type (gnat_type);
9561 tree gnu_base_type = get_base_type (gnu_type);
9562 tree gnu_in_type = TREE_TYPE (gnu_expr);
9563 tree gnu_in_base_type = get_base_type (gnu_in_type);
9564 tree gnu_result = gnu_expr;
9566 /* If we are not doing any checks, the output is an integral type and the
9567 input is not a floating-point type, just do the conversion. This is
9568 required for packed array types and is simpler in all cases anyway. */
9569 if (!overflow_p
9570 && INTEGRAL_TYPE_P (gnu_base_type)
9571 && !FLOAT_TYPE_P (gnu_in_base_type))
9572 return convert (gnu_type, gnu_expr);
9574 /* If the mode of the input base type is larger, then converting to it below
9575 may pessimize the final conversion step, for example generate a libcall
9576 instead of a simple instruction, so use a narrower type in this case. */
9577 if (TYPE_MODE (gnu_in_base_type) != TYPE_MODE (gnu_in_type)
9578 && !(TREE_CODE (gnu_in_type) == INTEGER_TYPE
9579 && TYPE_BIASED_REPRESENTATION_P (gnu_in_type)))
9580 gnu_in_base_type = gnat_type_for_mode (TYPE_MODE (gnu_in_type),
9581 TYPE_UNSIGNED (gnu_in_type));
9583 /* First convert the expression to the base type. This will never generate
9584 code, but makes the tests below simpler. But don't do this if converting
9585 from an integer type to an unconstrained array type since then we need to
9586 get the bounds from the original (unpacked) type. */
9587 if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
9588 gnu_result = convert (gnu_in_base_type, gnu_result);
9590 /* If overflow checks are requested, we need to be sure the result will fit
9591 in the output base type. But don't do this if the input is integer and
9592 the output floating-point. */
9593 if (overflow_p
9594 && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_base_type)))
9596 /* Ensure GNU_EXPR only gets evaluated once. */
9597 tree gnu_input = gnat_protect_expr (gnu_result);
9598 tree gnu_cond = boolean_false_node;
9599 tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_base_type);
9600 tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_base_type);
9601 tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
9602 tree gnu_out_ub
9603 = (TREE_CODE (gnu_base_type) == INTEGER_TYPE
9604 && TYPE_MODULAR_P (gnu_base_type))
9605 ? fold_build2 (MINUS_EXPR, gnu_base_type,
9606 TYPE_MODULUS (gnu_base_type),
9607 build_int_cst (gnu_base_type, 1))
9608 : TYPE_MAX_VALUE (gnu_base_type);
9610 /* Convert the lower bounds to signed types, so we're sure we're
9611 comparing them properly. Likewise, convert the upper bounds
9612 to unsigned types. */
9613 if (INTEGRAL_TYPE_P (gnu_in_base_type)
9614 && TYPE_UNSIGNED (gnu_in_base_type))
9615 gnu_in_lb
9616 = convert (gnat_signed_type_for (gnu_in_base_type), gnu_in_lb);
9618 if (INTEGRAL_TYPE_P (gnu_in_base_type)
9619 && !TYPE_UNSIGNED (gnu_in_base_type))
9620 gnu_in_ub
9621 = convert (gnat_unsigned_type_for (gnu_in_base_type), gnu_in_ub);
9623 if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
9624 gnu_out_lb
9625 = convert (gnat_signed_type_for (gnu_base_type), gnu_out_lb);
9627 if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
9628 gnu_out_ub
9629 = convert (gnat_unsigned_type_for (gnu_base_type), gnu_out_ub);
9631 /* Check each bound separately and only if the result bound
9632 is tighter than the bound on the input type. Note that all the
9633 types are base types, so the bounds must be constant. Also,
9634 the comparison is done in the base type of the input, which
9635 always has the proper signedness. First check for input
9636 integer (which means output integer), output float (which means
9637 both float), or mixed, in which case we always compare.
9638 Note that we have to do the comparison which would *fail* in the
9639 case of an error since if it's an FP comparison and one of the
9640 values is a NaN or Inf, the comparison will fail. */
9641 if (INTEGRAL_TYPE_P (gnu_in_base_type)
9642 ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
9643 : (FLOAT_TYPE_P (gnu_base_type)
9644 ? real_less (&TREE_REAL_CST (gnu_in_lb),
9645 &TREE_REAL_CST (gnu_out_lb))
9646 : 1))
9647 gnu_cond
9648 = invert_truthvalue
9649 (build_binary_op (GE_EXPR, boolean_type_node,
9650 gnu_input, convert (gnu_in_base_type,
9651 gnu_out_lb)));
9653 if (INTEGRAL_TYPE_P (gnu_in_base_type)
9654 ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
9655 : (FLOAT_TYPE_P (gnu_base_type)
9656 ? real_less (&TREE_REAL_CST (gnu_out_ub),
9657 &TREE_REAL_CST (gnu_in_ub))
9658 : 1))
9659 gnu_cond
9660 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
9661 invert_truthvalue
9662 (build_binary_op (LE_EXPR, boolean_type_node,
9663 gnu_input,
9664 convert (gnu_in_base_type,
9665 gnu_out_ub))));
9667 if (!integer_zerop (gnu_cond))
9668 gnu_result = emit_check (gnu_cond, gnu_input,
9669 CE_Overflow_Check_Failed, gnat_node);
9672 /* Now convert to the result base type. If this is a non-truncating
9673 float-to-integer conversion, round. */
9674 if (INTEGRAL_TYPE_P (gnu_base_type)
9675 && FLOAT_TYPE_P (gnu_in_base_type)
9676 && !truncate_p)
9678 REAL_VALUE_TYPE half_minus_pred_half, pred_half;
9679 tree gnu_conv, gnu_zero, gnu_comp, calc_type;
9680 tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
9681 const struct real_format *fmt;
9683 /* The following calculations depend on proper rounding to even
9684 of each arithmetic operation. In order to prevent excess
9685 precision from spoiling this property, use the widest hardware
9686 floating-point type if FP_ARITH_MAY_WIDEN is true. */
9687 calc_type
9688 = fp_arith_may_widen ? longest_float_type_node : gnu_in_base_type;
9690 /* Compute the exact value calc_type'Pred (0.5) at compile time. */
9691 fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
9692 real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
9693 real_arithmetic (&pred_half, MINUS_EXPR, &dconsthalf,
9694 &half_minus_pred_half);
9695 gnu_pred_half = build_real (calc_type, pred_half);
9697 /* If the input is strictly negative, subtract this value
9698 and otherwise add it from the input. For 0.5, the result
9699 is exactly between 1.0 and the machine number preceding 1.0
9700 (for calc_type). Since the last bit of 1.0 is even, this 0.5
9701 will round to 1.0, while all other number with an absolute
9702 value less than 0.5 round to 0.0. For larger numbers exactly
9703 halfway between integers, rounding will always be correct as
9704 the true mathematical result will be closer to the higher
9705 integer compared to the lower one. So, this constant works
9706 for all floating-point numbers.
9708 The reason to use the same constant with subtract/add instead
9709 of a positive and negative constant is to allow the comparison
9710 to be scheduled in parallel with retrieval of the constant and
9711 conversion of the input to the calc_type (if necessary). */
9713 gnu_zero = build_real (gnu_in_base_type, dconst0);
9714 gnu_result = gnat_protect_expr (gnu_result);
9715 gnu_conv = convert (calc_type, gnu_result);
9716 gnu_comp
9717 = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
9718 gnu_add_pred_half
9719 = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
9720 gnu_subtract_pred_half
9721 = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
9722 gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
9723 gnu_add_pred_half, gnu_subtract_pred_half);
9726 if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
9727 && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
9728 && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
9729 gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
9730 else
9731 gnu_result = convert (gnu_base_type, gnu_result);
9733 return convert (gnu_type, gnu_result);
9736 /* Return true if GNU_EXPR can be directly addressed. This is the case
9737 unless it is an expression involving computation or if it involves a
9738 reference to a bitfield or to an object not sufficiently aligned for
9739 its type. If GNU_TYPE is non-null, return true only if GNU_EXPR can
9740 be directly addressed as an object of this type.
9742 *** Notes on addressability issues in the Ada compiler ***
9744 This predicate is necessary in order to bridge the gap between Gigi
9745 and the middle-end about addressability of GENERIC trees. A tree
9746 is said to be addressable if it can be directly addressed, i.e. if
9747 its address can be taken, is a multiple of the type's alignment on
9748 strict-alignment architectures and returns the first storage unit
9749 assigned to the object represented by the tree.
9751 In the C family of languages, everything is in practice addressable
9752 at the language level, except for bit-fields. This means that these
9753 compilers will take the address of any tree that doesn't represent
9754 a bit-field reference and expect the result to be the first storage
9755 unit assigned to the object. Even in cases where this will result
9756 in unaligned accesses at run time, nothing is supposed to be done
9757 and the program is considered as erroneous instead (see PR c/18287).
9759 The implicit assumptions made in the middle-end are in keeping with
9760 the C viewpoint described above:
9761 - the address of a bit-field reference is supposed to be never
9762 taken; the compiler (generally) will stop on such a construct,
9763 - any other tree is addressable if it is formally addressable,
9764 i.e. if it is formally allowed to be the operand of ADDR_EXPR.
9766 In Ada, the viewpoint is the opposite one: nothing is addressable
9767 at the language level unless explicitly declared so. This means
9768 that the compiler will both make sure that the trees representing
9769 references to addressable ("aliased" in Ada parlance) objects are
9770 addressable and make no real attempts at ensuring that the trees
9771 representing references to non-addressable objects are addressable.
9773 In the first case, Ada is effectively equivalent to C and handing
9774 down the direct result of applying ADDR_EXPR to these trees to the
9775 middle-end works flawlessly. In the second case, Ada cannot afford
9776 to consider the program as erroneous if the address of trees that
9777 are not addressable is requested for technical reasons, unlike C;
9778 as a consequence, the Ada compiler must arrange for either making
9779 sure that this address is not requested in the middle-end or for
9780 compensating by inserting temporaries if it is requested in Gigi.
9782 The first goal can be achieved because the middle-end should not
9783 request the address of non-addressable trees on its own; the only
9784 exception is for the invocation of low-level block operations like
9785 memcpy, for which the addressability requirements are lower since
9786 the type's alignment can be disregarded. In practice, this means
9787 that Gigi must make sure that such operations cannot be applied to
9788 non-BLKmode bit-fields.
9790 The second goal is achieved by means of the addressable_p predicate,
9791 which computes whether a temporary must be inserted by Gigi when the
9792 address of a tree is requested; if so, the address of the temporary
9793 will be used in lieu of that of the original tree and some glue code
9794 generated to connect everything together. */
9796 static bool
9797 addressable_p (tree gnu_expr, tree gnu_type)
9799 /* For an integral type, the size of the actual type of the object may not
9800 be greater than that of the expected type, otherwise an indirect access
9801 in the latter type wouldn't correctly set all the bits of the object. */
9802 if (gnu_type
9803 && INTEGRAL_TYPE_P (gnu_type)
9804 && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
9805 return false;
9807 /* The size of the actual type of the object may not be smaller than that
9808 of the expected type, otherwise an indirect access in the latter type
9809 would be larger than the object. But only record types need to be
9810 considered in practice for this case. */
9811 if (gnu_type
9812 && TREE_CODE (gnu_type) == RECORD_TYPE
9813 && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
9814 return false;
9816 switch (TREE_CODE (gnu_expr))
9818 case VAR_DECL:
9819 case PARM_DECL:
9820 case FUNCTION_DECL:
9821 case RESULT_DECL:
9822 /* All DECLs are addressable: if they are in a register, we can force
9823 them to memory. */
9824 return true;
9826 case UNCONSTRAINED_ARRAY_REF:
9827 case INDIRECT_REF:
9828 /* Taking the address of a dereference yields the original pointer. */
9829 return true;
9831 case STRING_CST:
9832 case INTEGER_CST:
9833 case REAL_CST:
9834 /* Taking the address yields a pointer to the constant pool. */
9835 return true;
9837 case CONSTRUCTOR:
9838 /* Taking the address of a static constructor yields a pointer to the
9839 tree constant pool. */
9840 return TREE_STATIC (gnu_expr) ? true : false;
9842 case NULL_EXPR:
9843 case ADDR_EXPR:
9844 case SAVE_EXPR:
9845 case CALL_EXPR:
9846 case PLUS_EXPR:
9847 case MINUS_EXPR:
9848 case BIT_IOR_EXPR:
9849 case BIT_XOR_EXPR:
9850 case BIT_AND_EXPR:
9851 case BIT_NOT_EXPR:
9852 /* All rvalues are deemed addressable since taking their address will
9853 force a temporary to be created by the middle-end. */
9854 return true;
9856 case COMPOUND_EXPR:
9857 /* The address of a compound expression is that of its 2nd operand. */
9858 return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
9860 case COND_EXPR:
9861 /* We accept &COND_EXPR as soon as both operands are addressable and
9862 expect the outcome to be the address of the selected operand. */
9863 return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
9864 && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
9866 case COMPONENT_REF:
9867 return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
9868 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
9869 the field is sufficiently aligned, in case it is subject
9870 to a pragma Component_Alignment. But we don't need to
9871 check the alignment of the containing record, as it is
9872 guaranteed to be not smaller than that of its most
9873 aligned field that is not a bit-field. */
9874 && (!STRICT_ALIGNMENT
9875 || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
9876 >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
9877 /* The field of a padding record is always addressable. */
9878 || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
9879 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9881 case ARRAY_REF: case ARRAY_RANGE_REF:
9882 case REALPART_EXPR: case IMAGPART_EXPR:
9883 case NOP_EXPR:
9884 return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
9886 case CONVERT_EXPR:
9887 return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
9888 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9890 case VIEW_CONVERT_EXPR:
9892 /* This is addressable if we can avoid a copy. */
9893 tree type = TREE_TYPE (gnu_expr);
9894 tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
9895 return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
9896 && (!STRICT_ALIGNMENT
9897 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
9898 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
9899 || ((TYPE_MODE (type) == BLKmode
9900 || TYPE_MODE (inner_type) == BLKmode)
9901 && (!STRICT_ALIGNMENT
9902 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
9903 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
9904 || TYPE_ALIGN_OK (type)
9905 || TYPE_ALIGN_OK (inner_type))))
9906 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9909 default:
9910 return false;
9914 /* Do the processing for the declaration of a GNAT_ENTITY, a type or subtype.
9915 If a Freeze node exists for the entity, delay the bulk of the processing.
9916 Otherwise make a GCC type for GNAT_ENTITY and set up the correspondence. */
9918 void
9919 process_type (Entity_Id gnat_entity)
9921 tree gnu_old
9922 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
9924 /* If we are to delay elaboration of this type, just do any elaboration
9925 needed for expressions within the declaration and make a dummy node
9926 for it and its Full_View (if any), in case something points to it.
9927 Do not do this if it has already been done (the only way that can
9928 happen is if the private completion is also delayed). */
9929 if (Present (Freeze_Node (gnat_entity)))
9931 elaborate_entity (gnat_entity);
9933 if (!gnu_old)
9935 tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
9936 save_gnu_tree (gnat_entity, gnu_decl, false);
9937 if (Is_Incomplete_Or_Private_Type (gnat_entity)
9938 && Present (Full_View (gnat_entity)))
9940 if (Has_Completion_In_Body (gnat_entity))
9941 DECL_TAFT_TYPE_P (gnu_decl) = 1;
9942 save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
9946 return;
9949 /* If we saved away a dummy type for this node, it means that this made the
9950 type that corresponds to the full type of an incomplete type. Clear that
9951 type for now and then update the type in the pointers below. But, if the
9952 saved type is not dummy, it very likely means that we have a use before
9953 declaration for the type in the tree, what we really cannot handle. */
9954 if (gnu_old)
9956 gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
9957 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
9959 save_gnu_tree (gnat_entity, NULL_TREE, false);
9962 /* Now fully elaborate the type. */
9963 tree gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, true);
9964 gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
9966 /* If we have an old type and we've made pointers to this type, update those
9967 pointers. If this is a Taft amendment type in the main unit, we need to
9968 mark the type as used since other units referencing it don't see the full
9969 declaration and, therefore, cannot mark it as used themselves. */
9970 if (gnu_old)
9972 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
9973 TREE_TYPE (gnu_new));
9974 if (DECL_TAFT_TYPE_P (gnu_old))
9975 used_types_insert (TREE_TYPE (gnu_new));
9978 /* If this is a record type corresponding to a task or protected type
9979 that is a completion of an incomplete type, perform a similar update
9980 on the type. ??? Including protected types here is a guess. */
9981 if (Is_Record_Type (gnat_entity)
9982 && Is_Concurrent_Record_Type (gnat_entity)
9983 && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
9985 tree gnu_task_old
9986 = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
9988 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9989 NULL_TREE, false);
9990 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9991 gnu_new, false);
9993 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
9994 TREE_TYPE (gnu_new));
9998 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
9999 some of which are from RECORD_TYPE. Return a CONSTRUCTOR consisting of the
10000 associations that are from RECORD_TYPE. If we see an internal record, make
10001 a recursive call to fill it in as well. */
10003 static tree
10004 extract_values (tree values, tree record_type)
10006 vec<constructor_elt, va_gc> *v = NULL;
10007 tree field;
10009 for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
10011 tree tem, value = NULL_TREE;
10013 /* _Parent is an internal field, but may have values in the aggregate,
10014 so check for values first. */
10015 if ((tem = purpose_member (field, values)))
10017 value = TREE_VALUE (tem);
10018 TREE_ADDRESSABLE (tem) = 1;
10021 else if (DECL_INTERNAL_P (field))
10023 value = extract_values (values, TREE_TYPE (field));
10024 if (TREE_CODE (value) == CONSTRUCTOR
10025 && vec_safe_is_empty (CONSTRUCTOR_ELTS (value)))
10026 value = NULL_TREE;
10028 else
10029 /* If we have a record subtype, the names will match, but not the
10030 actual FIELD_DECLs. */
10031 for (tem = values; tem; tem = TREE_CHAIN (tem))
10032 if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
10034 value = convert (TREE_TYPE (field), TREE_VALUE (tem));
10035 TREE_ADDRESSABLE (tem) = 1;
10038 if (!value)
10039 continue;
10041 CONSTRUCTOR_APPEND_ELT (v, field, value);
10044 return gnat_build_constructor (record_type, v);
10047 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
10048 front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
10049 GCC type of the corresponding record type. Return the CONSTRUCTOR. */
10051 static tree
10052 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
10054 tree gnu_list = NULL_TREE, gnu_result;
10056 /* We test for GNU_FIELD being empty in the case where a variant
10057 was the last thing since we don't take things off GNAT_ASSOC in
10058 that case. We check GNAT_ASSOC in case we have a variant, but it
10059 has no fields. */
10061 for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
10063 const Node_Id gnat_field = First (Choices (gnat_assoc));
10064 const Node_Id gnat_expr = Expression (gnat_assoc);
10065 tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
10066 tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
10068 /* The expander is supposed to put a single component selector name
10069 in every record component association. */
10070 gcc_assert (No (Next (gnat_field)));
10072 /* Ignore discriminants that have Corresponding_Discriminants in tagged
10073 types since we'll be setting those fields in the parent subtype. */
10074 if (Ekind (Entity (gnat_field)) == E_Discriminant
10075 && Present (Corresponding_Discriminant (Entity (gnat_field)))
10076 && Is_Tagged_Type (Scope (Entity (gnat_field))))
10077 continue;
10079 /* Also ignore discriminants of Unchecked_Unions. */
10080 if (Ekind (Entity (gnat_field)) == E_Discriminant
10081 && Is_Unchecked_Union (gnat_entity))
10082 continue;
10084 gigi_checking_assert (!Do_Range_Check (gnat_expr));
10086 /* Convert to the type of the field. */
10087 gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
10089 /* Add the field and expression to the list. */
10090 gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
10093 gnu_result = extract_values (gnu_list, gnu_type);
10095 if (flag_checking)
10097 /* Verify that every entry in GNU_LIST was used. */
10098 for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
10099 gcc_assert (TREE_ADDRESSABLE (gnu_list));
10102 return gnu_result;
10105 /* Build a possibly nested constructor for array aggregates. GNAT_EXPR is
10106 the first element of an array aggregate. It may itself be an aggregate.
10107 GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate. */
10109 static tree
10110 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type)
10112 tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
10113 vec<constructor_elt, va_gc> *gnu_expr_vec = NULL;
10115 for (; Present (gnat_expr); gnat_expr = Next (gnat_expr))
10117 tree gnu_expr;
10119 /* If the expression is itself an array aggregate then first build the
10120 innermost constructor if it is part of our array (multi-dimensional
10121 case). */
10122 if (Nkind (gnat_expr) == N_Aggregate
10123 && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
10124 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
10125 gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
10126 TREE_TYPE (gnu_array_type));
10127 else
10129 /* If the expression is a conversion to an unconstrained array type,
10130 skip it to avoid spilling to memory. */
10131 if (Nkind (gnat_expr) == N_Type_Conversion
10132 && Is_Array_Type (Etype (gnat_expr))
10133 && !Is_Constrained (Etype (gnat_expr)))
10134 gnu_expr = gnat_to_gnu (Expression (gnat_expr));
10135 else
10136 gnu_expr = gnat_to_gnu (gnat_expr);
10138 gigi_checking_assert (!Do_Range_Check (gnat_expr));
10141 CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
10142 convert (TREE_TYPE (gnu_array_type), gnu_expr));
10144 gnu_index = int_const_binop (PLUS_EXPR, gnu_index,
10145 convert (TREE_TYPE (gnu_index),
10146 integer_one_node));
10149 return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
10152 /* Process a N_Validate_Unchecked_Conversion node. */
10154 static void
10155 validate_unchecked_conversion (Node_Id gnat_node)
10157 tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
10158 tree gnu_target_type = gnat_to_gnu_type (Target_Type (gnat_node));
10160 /* If the target is a pointer type, see if we are either converting from a
10161 non-pointer or from a pointer to a type with a different alias set and
10162 warn if so, unless the pointer has been marked to alias everything. */
10163 if (POINTER_TYPE_P (gnu_target_type)
10164 && !TYPE_REF_CAN_ALIAS_ALL (gnu_target_type))
10166 tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
10167 ? TREE_TYPE (gnu_source_type)
10168 : NULL_TREE;
10169 tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
10170 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
10172 if (target_alias_set != 0
10173 && (!POINTER_TYPE_P (gnu_source_type)
10174 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
10175 target_alias_set)))
10177 post_error_ne ("??possible aliasing problem for type&",
10178 gnat_node, Target_Type (gnat_node));
10179 post_error ("\\?use -fno-strict-aliasing switch for references",
10180 gnat_node);
10181 post_error_ne ("\\?or use `pragma No_Strict_Aliasing (&);`",
10182 gnat_node, Target_Type (gnat_node));
10186 /* Likewise if the target is a fat pointer type, but we have no mechanism to
10187 mitigate the problem in this case, so we unconditionally warn. */
10188 else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
10190 tree gnu_source_desig_type
10191 = TYPE_IS_FAT_POINTER_P (gnu_source_type)
10192 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
10193 : NULL_TREE;
10194 tree gnu_target_desig_type
10195 = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
10196 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
10198 if (target_alias_set != 0
10199 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
10200 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
10201 target_alias_set)))
10203 post_error_ne ("??possible aliasing problem for type&",
10204 gnat_node, Target_Type (gnat_node));
10205 post_error ("\\?use -fno-strict-aliasing switch for references",
10206 gnat_node);
10211 /* Convert SLOC into LOCUS. Return true if SLOC corresponds to a
10212 source code location and false if it doesn't. If CLEAR_COLUMN is
10213 true, set the column information to 0. If DECL is given and SLOC
10214 refers to a File with an instance, map DECL to that instance. */
10216 bool
10217 Sloc_to_locus (Source_Ptr Sloc, location_t *locus, bool clear_column,
10218 const_tree decl)
10220 if (Sloc == No_Location)
10221 return false;
10223 if (Sloc <= Standard_Location)
10225 *locus = BUILTINS_LOCATION;
10226 return false;
10229 Source_File_Index file = Get_Source_File_Index (Sloc);
10230 Line_Number_Type line = Get_Logical_Line_Number (Sloc);
10231 Column_Number_Type column = (clear_column ? 0 : Get_Column_Number (Sloc));
10232 line_map_ordinary *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
10234 /* We can have zero if pragma Source_Reference is in effect. */
10235 if (line < 1)
10236 line = 1;
10238 /* Translate the location. */
10239 *locus
10240 = linemap_position_for_line_and_column (line_table, map, line, column);
10242 if (file_map && file_map[file - 1].Instance)
10243 decl_to_instance_map->put (decl, file_map[file - 1].Instance);
10245 return true;
10248 /* Return whether GNAT_NODE is a defining identifier for a renaming that comes
10249 from the parameter association for the instantiation of a generic. We do
10250 not want to emit source location for them: the code generated for their
10251 initialization is likely to disturb debugging. */
10253 bool
10254 renaming_from_instantiation_p (Node_Id gnat_node)
10256 if (Nkind (gnat_node) != N_Defining_Identifier
10257 || !Is_Object (gnat_node)
10258 || Comes_From_Source (gnat_node)
10259 || !Present (Renamed_Object (gnat_node)))
10260 return false;
10262 /* Get the object declaration of the renamed object, if any and if the
10263 renamed object is a mere identifier. */
10264 gnat_node = Renamed_Object (gnat_node);
10265 if (Nkind (gnat_node) != N_Identifier)
10266 return false;
10268 gnat_node = Parent (Entity (gnat_node));
10269 return (Present (gnat_node)
10270 && Nkind (gnat_node) == N_Object_Declaration
10271 && Present (Corresponding_Generic_Association (gnat_node)));
10274 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
10275 don't do anything if it doesn't correspond to a source location. And,
10276 if CLEAR_COLUMN is true, set the column information to 0. */
10278 static void
10279 set_expr_location_from_node (tree node, Node_Id gnat_node, bool clear_column)
10281 location_t locus;
10283 /* Do not set a location for constructs likely to disturb debugging. */
10284 if (Nkind (gnat_node) == N_Defining_Identifier)
10286 if (Is_Type (gnat_node) && Is_Actual_Subtype (gnat_node))
10287 return;
10289 if (renaming_from_instantiation_p (gnat_node))
10290 return;
10293 if (!Sloc_to_locus (Sloc (gnat_node), &locus, clear_column))
10294 return;
10296 SET_EXPR_LOCATION (node, locus);
10299 /* More elaborate version of set_expr_location_from_node to be used in more
10300 general contexts, for example the result of the translation of a generic
10301 GNAT node. */
10303 static void
10304 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
10306 /* Set the location information on the node if it is a real expression.
10307 References can be reused for multiple GNAT nodes and they would get
10308 the location information of their last use. Also make sure not to
10309 overwrite an existing location as it is probably more precise. */
10311 switch (TREE_CODE (node))
10313 CASE_CONVERT:
10314 case NON_LVALUE_EXPR:
10315 case SAVE_EXPR:
10316 break;
10318 case COMPOUND_EXPR:
10319 if (EXPR_P (TREE_OPERAND (node, 1)))
10320 set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
10322 /* ... fall through ... */
10324 default:
10325 if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
10327 set_expr_location_from_node (node, gnat_node);
10328 set_end_locus_from_node (node, gnat_node);
10330 break;
10334 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
10335 location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
10336 most sense. Return true if a sensible assignment was performed. */
10338 static bool
10339 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
10341 Node_Id gnat_end_label;
10342 location_t end_locus;
10344 /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
10345 end_locus when there is one. We consider only GNAT nodes with a possible
10346 End_Label attached. If the End_Label actually was unassigned, fallback
10347 on the original node. We'd better assign an explicit sloc associated with
10348 the outer construct in any case. */
10350 switch (Nkind (gnat_node))
10352 case N_Package_Body:
10353 case N_Subprogram_Body:
10354 case N_Block_Statement:
10355 if (Present (Handled_Statement_Sequence (gnat_node)))
10356 gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
10357 else
10358 gnat_end_label = Empty;
10360 break;
10362 case N_Package_Declaration:
10363 gcc_checking_assert (Present (Specification (gnat_node)));
10364 gnat_end_label = End_Label (Specification (gnat_node));
10365 break;
10367 default:
10368 return false;
10371 if (Present (gnat_end_label))
10372 gnat_node = gnat_end_label;
10374 /* Some expanded subprograms have neither an End_Label nor a Sloc
10375 attached. Notify that to callers. For a block statement with no
10376 End_Label, clear column information, so that the tree for a
10377 transient block does not receive the sloc of a source condition. */
10378 if (!Sloc_to_locus (Sloc (gnat_node), &end_locus,
10379 No (gnat_end_label)
10380 && (Nkind (gnat_node) == N_Block_Statement)))
10381 return false;
10383 switch (TREE_CODE (gnu_node))
10385 case BIND_EXPR:
10386 BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
10387 return true;
10389 case FUNCTION_DECL:
10390 DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
10391 return true;
10393 default:
10394 return false;
10398 /* Post an error message. MSG is the error message, properly annotated.
10399 NODE is the node at which to post the error and the node to use for the
10400 '&' substitution. */
10402 void
10403 post_error (const char *msg, Node_Id node)
10405 String_Template temp;
10406 String_Pointer sp;
10408 if (No (node))
10409 return;
10411 temp.Low_Bound = 1;
10412 temp.High_Bound = strlen (msg);
10413 sp.Bounds = &temp;
10414 sp.Array = msg;
10415 Error_Msg_N (sp, node);
10418 /* Similar to post_error, but NODE is the node at which to post the error and
10419 ENT is the node to use for the '&' substitution. */
10421 void
10422 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
10424 String_Template temp;
10425 String_Pointer sp;
10427 if (No (node))
10428 return;
10430 temp.Low_Bound = 1;
10431 temp.High_Bound = strlen (msg);
10432 sp.Bounds = &temp;
10433 sp.Array = msg;
10434 Error_Msg_NE (sp, node, ent);
10437 /* Similar to post_error_ne, but NUM is the number to use for the '^'. */
10439 void
10440 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
10442 Error_Msg_Uint_1 = UI_From_Int (num);
10443 post_error_ne (msg, node, ent);
10446 /* Similar to post_error_ne, but T is a GCC tree representing the number to
10447 write. If T represents a constant, the text inside curly brackets in
10448 MSG will be output (presumably including a '^'). Otherwise it will not
10449 be output and the text inside square brackets will be output instead. */
10451 void
10452 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
10454 char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
10455 char start_yes, end_yes, start_no, end_no;
10456 const char *p;
10457 char *q;
10459 if (TREE_CODE (t) == INTEGER_CST)
10461 Error_Msg_Uint_1 = UI_From_gnu (t);
10462 start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
10464 else
10465 start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
10467 for (p = msg, q = new_msg; *p; p++)
10469 if (*p == start_yes)
10470 for (p++; *p != end_yes; p++)
10471 *q++ = *p;
10472 else if (*p == start_no)
10473 for (p++; *p != end_no; p++)
10475 else
10476 *q++ = *p;
10479 *q = 0;
10481 post_error_ne (new_msg, node, ent);
10484 /* Similar to post_error_ne_tree, but NUM is a second integer to write. */
10486 void
10487 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
10488 int num)
10490 Error_Msg_Uint_2 = UI_From_Int (num);
10491 post_error_ne_tree (msg, node, ent, t);
10494 /* Return a label to branch to for the exception type in KIND or Empty
10495 if none. */
10497 Entity_Id
10498 get_exception_label (char kind)
10500 switch (kind)
10502 case N_Raise_Constraint_Error:
10503 return gnu_constraint_error_label_stack.last ();
10505 case N_Raise_Storage_Error:
10506 return gnu_storage_error_label_stack.last ();
10508 case N_Raise_Program_Error:
10509 return gnu_program_error_label_stack.last ();
10511 default:
10512 return Empty;
10515 gcc_unreachable ();
10518 /* Return the decl for the current elaboration procedure. */
10520 static tree
10521 get_elaboration_procedure (void)
10523 return gnu_elab_proc_stack->last ();
10526 /* Return the controlling type of a dispatching subprogram. */
10528 static Entity_Id
10529 get_controlling_type (Entity_Id subprog)
10531 /* This is modeled on Expand_Interface_Thunk. */
10532 Entity_Id controlling_type = Etype (First_Formal (subprog));
10533 if (Is_Access_Type (controlling_type))
10534 controlling_type = Directly_Designated_Type (controlling_type);
10535 controlling_type = Underlying_Type (controlling_type);
10536 if (Is_Concurrent_Type (controlling_type))
10537 controlling_type = Corresponding_Record_Type (controlling_type);
10538 controlling_type = Base_Type (controlling_type);
10539 return controlling_type;
10542 /* Return whether we should use an alias for the TARGET of a thunk
10543 in order to make the call generated in the thunk local. */
10545 static bool
10546 use_alias_for_thunk_p (tree target)
10548 /* We cannot generate a local call in this case. */
10549 if (DECL_EXTERNAL (target))
10550 return false;
10552 /* The call is already local in this case. */
10553 if (TREE_CODE (DECL_CONTEXT (target)) == FUNCTION_DECL)
10554 return false;
10556 return TARGET_USE_LOCAL_THUNK_ALIAS_P (target);
10559 static GTY(()) unsigned long thunk_labelno = 0;
10561 /* Create an alias for TARGET to be used as the target of a thunk. */
10563 static tree
10564 make_alias_for_thunk (tree target)
10566 char buf[64];
10567 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno++);
10569 tree alias = build_decl (DECL_SOURCE_LOCATION (target), TREE_CODE (target),
10570 get_identifier (buf), TREE_TYPE (target));
10572 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (target);
10573 DECL_CONTEXT (alias) = DECL_CONTEXT (target);
10574 TREE_READONLY (alias) = TREE_READONLY (target);
10575 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (target);
10576 DECL_ARTIFICIAL (alias) = 1;
10577 DECL_INITIAL (alias) = error_mark_node;
10578 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (target));
10579 TREE_ADDRESSABLE (alias) = 1;
10580 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
10582 cgraph_node *n = cgraph_node::create_same_body_alias (alias, target);
10583 gcc_assert (n);
10585 return alias;
10588 /* Create the local covariant part of {GNAT,GNU}_THUNK. */
10590 static tree
10591 make_covariant_thunk (Entity_Id gnat_thunk, tree gnu_thunk)
10593 tree gnu_name = create_concat_name (gnat_thunk, "CV");
10594 tree gnu_cv_thunk
10595 = build_decl (DECL_SOURCE_LOCATION (gnu_thunk), TREE_CODE (gnu_thunk),
10596 gnu_name, TREE_TYPE (gnu_thunk));
10598 DECL_ARGUMENTS (gnu_cv_thunk) = copy_list (DECL_ARGUMENTS (gnu_thunk));
10599 for (tree param_decl = DECL_ARGUMENTS (gnu_cv_thunk);
10600 param_decl;
10601 param_decl = DECL_CHAIN (param_decl))
10602 DECL_CONTEXT (param_decl) = gnu_cv_thunk;
10604 DECL_RESULT (gnu_cv_thunk) = copy_node (DECL_RESULT (gnu_thunk));
10605 DECL_CONTEXT (DECL_RESULT (gnu_cv_thunk)) = gnu_cv_thunk;
10607 DECL_LANG_SPECIFIC (gnu_cv_thunk) = DECL_LANG_SPECIFIC (gnu_thunk);
10608 DECL_CONTEXT (gnu_cv_thunk) = DECL_CONTEXT (gnu_thunk);
10609 TREE_READONLY (gnu_cv_thunk) = TREE_READONLY (gnu_thunk);
10610 TREE_THIS_VOLATILE (gnu_cv_thunk) = TREE_THIS_VOLATILE (gnu_thunk);
10611 DECL_ARTIFICIAL (gnu_cv_thunk) = 1;
10613 return gnu_cv_thunk;
10616 /* Try to create a GNU thunk for {GNAT,GNU}_THUNK and return true on success.
10618 GNU thunks are more efficient than GNAT thunks because they don't call into
10619 the runtime to retrieve the offset used in the displacement operation, but
10620 they are tailored to C++ and thus too limited to support the full range of
10621 thunks generated in Ada. Here's the complete list of limitations:
10623 1. Multi-controlling thunks, i.e thunks with more than one controlling
10624 parameter, are simply not supported.
10626 2. Covariant thunks, i.e. thunks for which the result is also controlling,
10627 are split into a pair of (this, covariant-only) thunks.
10629 3. Variable-offset thunks, i.e. thunks for which the offset depends on the
10630 object and not only on its type, are supported as 2nd class citizens.
10632 4. External thunks, i.e. thunks for which the target is not declared in
10633 the same unit as the thunk, are supported as 2nd class citizens.
10635 5. Local thunks, i.e. thunks generated for a local type, are supported as
10636 2nd class citizens. */
10638 static bool
10639 maybe_make_gnu_thunk (Entity_Id gnat_thunk, tree gnu_thunk)
10641 const Entity_Id gnat_target = Thunk_Entity (gnat_thunk);
10643 /* Check that the first formal of the target is the only controlling one. */
10644 Entity_Id gnat_formal = First_Formal (gnat_target);
10645 if (!Is_Controlling_Formal (gnat_formal))
10646 return false;
10647 for (gnat_formal = Next_Formal (gnat_formal);
10648 Present (gnat_formal);
10649 gnat_formal = Next_Formal (gnat_formal))
10650 if (Is_Controlling_Formal (gnat_formal))
10651 return false;
10653 /* Look for the types that control the target and the thunk. */
10654 const Entity_Id gnat_controlling_type = get_controlling_type (gnat_target);
10655 const Entity_Id gnat_interface_type = get_controlling_type (gnat_thunk);
10657 /* We must have an interface type at this point. */
10658 gcc_assert (Is_Interface (gnat_interface_type));
10660 /* Now compute whether the former covers the latter. */
10661 const Entity_Id gnat_interface_tag
10662 = Find_Interface_Tag (gnat_controlling_type, gnat_interface_type);
10663 tree gnu_interface_tag
10664 = Present (gnat_interface_tag)
10665 ? gnat_to_gnu_field_decl (gnat_interface_tag)
10666 : NULL_TREE;
10667 tree gnu_interface_offset
10668 = gnu_interface_tag ? byte_position (gnu_interface_tag) : NULL_TREE;
10670 /* There are three ways to retrieve the offset between the interface view
10671 and the base object. Either the controlling type covers the interface
10672 type and the offset of the corresponding tag is fixed, in which case it
10673 can be statically encoded in the thunk (see FIXED_OFFSET below). Or the
10674 controlling type doesn't cover the interface type but is of fixed size,
10675 in which case the offset is stored in the dispatch table, two pointers
10676 above the dispatch table address (see VIRTUAL_VALUE below). Otherwise,
10677 the offset is variable and is stored right after the tag in every object
10678 (see INDIRECT_OFFSET below). See also a-tags.ads for more details. */
10679 HOST_WIDE_INT fixed_offset, virtual_value, indirect_offset;
10680 tree virtual_offset;
10682 if (gnu_interface_offset && TREE_CODE (gnu_interface_offset) == INTEGER_CST)
10684 fixed_offset = - tree_to_shwi (gnu_interface_offset);
10685 virtual_value = 0;
10686 virtual_offset = NULL_TREE;
10687 indirect_offset = 0;
10689 else if (!gnu_interface_offset
10690 && !Is_Variable_Size_Record (gnat_controlling_type))
10692 fixed_offset = 0;
10693 virtual_value = - 2 * (HOST_WIDE_INT) (POINTER_SIZE / BITS_PER_UNIT);
10694 virtual_offset = build_int_cst (integer_type_node, virtual_value);
10695 indirect_offset = 0;
10697 else
10699 /* Covariant thunks with variable offset are not supported. */
10700 if (Has_Controlling_Result (gnat_target))
10701 return false;
10703 fixed_offset = 0;
10704 virtual_value = 0;
10705 virtual_offset = NULL_TREE;
10706 indirect_offset = (HOST_WIDE_INT) (POINTER_SIZE / BITS_PER_UNIT);
10709 tree gnu_target = gnat_to_gnu_entity (gnat_target, NULL_TREE, false);
10711 /* If the target is local, then thunk and target must have the same context
10712 because cgraph_node::expand_thunk can only forward the static chain. */
10713 if (DECL_STATIC_CHAIN (gnu_target)
10714 && DECL_CONTEXT (gnu_thunk) != DECL_CONTEXT (gnu_target))
10715 return false;
10717 /* If the target returns by invisible reference and is external, apply the
10718 same transformation as Subprogram_Body_to_gnu here. */
10719 if (TREE_ADDRESSABLE (TREE_TYPE (gnu_target))
10720 && DECL_EXTERNAL (gnu_target)
10721 && !POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (gnu_target))))
10723 TREE_TYPE (DECL_RESULT (gnu_target))
10724 = build_reference_type (TREE_TYPE (DECL_RESULT (gnu_target)));
10725 relayout_decl (DECL_RESULT (gnu_target));
10728 /* The thunk expander requires the return types of thunk and target to be
10729 compatible, which is not fully the case with the CICO mechanism. */
10730 if (TYPE_CI_CO_LIST (TREE_TYPE (gnu_thunk)))
10732 tree gnu_target_type = TREE_TYPE (gnu_target);
10733 gcc_assert (TYPE_CI_CO_LIST (gnu_target_type));
10734 TYPE_CANONICAL (TREE_TYPE (TREE_TYPE (gnu_thunk)))
10735 = TYPE_CANONICAL (TREE_TYPE (gnu_target_type));
10738 cgraph_node *target_node = cgraph_node::get_create (gnu_target);
10740 /* We may also need to create an alias for the target in order to make
10741 the call local, depending on the linkage of the target. */
10742 tree gnu_alias = use_alias_for_thunk_p (gnu_target)
10743 ? make_alias_for_thunk (gnu_target)
10744 : gnu_target;
10746 /* If the return type of the target is a controlling type, then we need
10747 both an usual this thunk and a covariant thunk in this order:
10749 this thunk --> covariant thunk --> target
10751 For covariant thunks, we can only handle a fixed offset. */
10752 if (Has_Controlling_Result (gnat_target))
10754 gcc_assert (fixed_offset < 0);
10755 tree gnu_cv_thunk = make_covariant_thunk (gnat_thunk, gnu_thunk);
10756 target_node->create_thunk (gnu_cv_thunk, gnu_target, false,
10757 - fixed_offset, 0, 0,
10758 NULL_TREE, gnu_alias);
10760 gnu_alias = gnu_target = gnu_cv_thunk;
10763 target_node->create_thunk (gnu_thunk, gnu_target, true,
10764 fixed_offset, virtual_value, indirect_offset,
10765 virtual_offset, gnu_alias);
10767 return true;
10770 /* Initialize the table that maps GNAT codes to GCC codes for simple
10771 binary and unary operations. */
10773 static void
10774 init_code_table (void)
10776 gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
10777 gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
10778 gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
10779 gnu_codes[N_Op_Eq] = EQ_EXPR;
10780 gnu_codes[N_Op_Ne] = NE_EXPR;
10781 gnu_codes[N_Op_Lt] = LT_EXPR;
10782 gnu_codes[N_Op_Le] = LE_EXPR;
10783 gnu_codes[N_Op_Gt] = GT_EXPR;
10784 gnu_codes[N_Op_Ge] = GE_EXPR;
10785 gnu_codes[N_Op_Add] = PLUS_EXPR;
10786 gnu_codes[N_Op_Subtract] = MINUS_EXPR;
10787 gnu_codes[N_Op_Multiply] = MULT_EXPR;
10788 gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
10789 gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
10790 gnu_codes[N_Op_Minus] = NEGATE_EXPR;
10791 gnu_codes[N_Op_Abs] = ABS_EXPR;
10792 gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
10793 gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
10794 gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
10795 gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
10796 gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
10797 gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
10798 gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
10799 gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
10802 #include "gt-ada-trans.h"