]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/ada/gcc-interface/trans.c
* gcc-interface/trans.c (gnat_to_gnu) <N_Aggregate>: Minor tweak.
[thirdparty/gcc.git] / gcc / ada / gcc-interface / trans.c
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * T R A N S *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2019, Free Software Foundation, Inc. *
10 * *
11 * GNAT is free software; you can redistribute it and/or modify it under *
12 * terms of the GNU General Public License as published by the Free Soft- *
13 * ware Foundation; either version 3, or (at your option) any later ver- *
14 * sion. GNAT is distributed in the hope that it will be useful, but WITH- *
15 * OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *
16 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
17 * for more details. You should have received a copy of the GNU General *
18 * Public License distributed with GNAT; see file COPYING3. If not see *
19 * <http://www.gnu.org/licenses/>. *
20 * *
21 * GNAT was originally developed by the GNAT team at New York University. *
22 * Extensive contributions were provided by Ada Core Technologies Inc. *
23 * *
24 ****************************************************************************/
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "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
54 #include "ada.h"
55 #include "adadecode.h"
56 #include "types.h"
57 #include "atree.h"
58 #include "namet.h"
59 #include "nlists.h"
60 #include "snames.h"
61 #include "stringt.h"
62 #include "uintp.h"
63 #include "urealp.h"
64 #include "fe.h"
65 #include "sinfo.h"
66 #include "einfo.h"
67 #include "gadaint.h"
68 #include "ada-tree.h"
69 #include "gigi.h"
70
71 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
72 for fear of running out of stack space. If we need more, we use xmalloc
73 instead. */
74 #define ALLOCA_THRESHOLD 1000
75
76 /* Pointers to front-end tables accessed through macros. */
77 struct Node *Nodes_Ptr;
78 struct Flags *Flags_Ptr;
79 Node_Id *Next_Node_Ptr;
80 Node_Id *Prev_Node_Ptr;
81 struct Elist_Header *Elists_Ptr;
82 struct Elmt_Item *Elmts_Ptr;
83 struct String_Entry *Strings_Ptr;
84 Char_Code *String_Chars_Ptr;
85 struct List_Header *List_Headers_Ptr;
86
87 /* Highest number in the front-end node table. */
88 int max_gnat_nodes;
89
90 /* True when gigi is being called on an analyzed but unexpanded
91 tree, and the only purpose of the call is to properly annotate
92 types with representation information. */
93 bool type_annotate_only;
94
95 /* List of N_Validate_Unchecked_Conversion nodes in the unit. */
96 static vec<Node_Id> gnat_validate_uc_list;
97
98 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
99 of unconstrained array IN parameters to avoid emitting a great deal of
100 redundant instructions to recompute them each time. */
101 struct GTY (()) parm_attr_d {
102 int id; /* GTY doesn't like Entity_Id. */
103 int dim;
104 tree first;
105 tree last;
106 tree length;
107 };
108
109 typedef struct parm_attr_d *parm_attr;
110
111
112 struct GTY(()) language_function {
113 vec<parm_attr, va_gc> *parm_attr_cache;
114 bitmap named_ret_val;
115 vec<tree, va_gc> *other_ret_val;
116 int gnat_ret;
117 };
118
119 #define f_parm_attr_cache \
120 DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
121
122 #define f_named_ret_val \
123 DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
124
125 #define f_other_ret_val \
126 DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
127
128 #define f_gnat_ret \
129 DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
130
131 /* A structure used to gather together information about a statement group.
132 We use this to gather related statements, for example the "then" part
133 of a IF. In the case where it represents a lexical scope, we may also
134 have a BLOCK node corresponding to it and/or cleanups. */
135
136 struct GTY((chain_next ("%h.previous"))) stmt_group {
137 struct stmt_group *previous; /* Previous code group. */
138 tree stmt_list; /* List of statements for this code group. */
139 tree block; /* BLOCK for this code group, if any. */
140 tree cleanups; /* Cleanups for this code group, if any. */
141 };
142
143 static GTY(()) struct stmt_group *current_stmt_group;
144
145 /* List of unused struct stmt_group nodes. */
146 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
147
148 /* A structure used to record information on elaboration procedures
149 we've made and need to process.
150
151 ??? gnat_node should be Node_Id, but gengtype gets confused. */
152
153 struct GTY((chain_next ("%h.next"))) elab_info {
154 struct elab_info *next; /* Pointer to next in chain. */
155 tree elab_proc; /* Elaboration procedure. */
156 int gnat_node; /* The N_Compilation_Unit. */
157 };
158
159 static GTY(()) struct elab_info *elab_info_list;
160
161 /* Stack of exception pointer variables. Each entry is the VAR_DECL
162 that stores the address of the raised exception. Nonzero means we
163 are in an exception handler. Not used in the zero-cost case. */
164 static GTY(()) vec<tree, va_gc> *gnu_except_ptr_stack;
165
166 /* In ZCX case, current exception pointer. Used to re-raise it. */
167 static GTY(()) tree gnu_incoming_exc_ptr;
168
169 /* Stack for storing the current elaboration procedure decl. */
170 static GTY(()) vec<tree, va_gc> *gnu_elab_proc_stack;
171
172 /* Stack of labels to be used as a goto target instead of a return in
173 some functions. See processing for N_Subprogram_Body. */
174 static GTY(()) vec<tree, va_gc> *gnu_return_label_stack;
175
176 /* Stack of variable for the return value of a function with copy-in/copy-out
177 parameters. See processing for N_Subprogram_Body. */
178 static GTY(()) vec<tree, va_gc> *gnu_return_var_stack;
179
180 /* Structure used to record information for a range check. */
181 struct GTY(()) range_check_info_d {
182 tree low_bound;
183 tree high_bound;
184 tree disp;
185 bool neg_p;
186 tree type;
187 tree invariant_cond;
188 tree inserted_cond;
189 };
190
191 typedef struct range_check_info_d *range_check_info;
192
193
194 /* Structure used to record information for a loop. */
195 struct GTY(()) loop_info_d {
196 tree stmt;
197 tree loop_var;
198 tree low_bound;
199 tree high_bound;
200 tree omp_loop_clauses;
201 tree omp_construct_clauses;
202 enum tree_code omp_code;
203 vec<range_check_info, va_gc> *checks;
204 };
205
206 typedef struct loop_info_d *loop_info;
207
208
209 /* Stack of loop_info structures associated with LOOP_STMT nodes. */
210 static GTY(()) vec<loop_info, va_gc> *gnu_loop_stack;
211
212 /* The stacks for N_{Push,Pop}_*_Label. */
213 static vec<Entity_Id> gnu_constraint_error_label_stack;
214 static vec<Entity_Id> gnu_storage_error_label_stack;
215 static vec<Entity_Id> gnu_program_error_label_stack;
216
217 /* Map GNAT tree codes to GCC tree codes for simple expressions. */
218 static enum tree_code gnu_codes[Number_Node_Kinds];
219
220 static void init_code_table (void);
221 static tree get_elaboration_procedure (void);
222 static void Compilation_Unit_to_gnu (Node_Id);
223 static bool empty_stmt_list_p (tree);
224 static void record_code_position (Node_Id);
225 static void insert_code_for (Node_Id);
226 static void add_cleanup (tree, Node_Id);
227 static void add_stmt_list (List_Id);
228 static tree build_stmt_group (List_Id, bool);
229 static inline bool stmt_group_may_fallthru (void);
230 static enum gimplify_status gnat_gimplify_stmt (tree *);
231 static void elaborate_all_entities (Node_Id);
232 static void process_freeze_entity (Node_Id);
233 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
234 static tree emit_range_check (tree, Node_Id, Node_Id);
235 static tree emit_check (tree, tree, int, Node_Id);
236 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
237 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
238 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
239 static bool addressable_p (tree, tree);
240 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
241 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
242 static void validate_unchecked_conversion (Node_Id);
243 static Node_Id adjust_for_implicit_deref (Node_Id);
244 static tree maybe_implicit_deref (tree);
245 static void set_expr_location_from_node (tree, Node_Id, bool = false);
246 static void set_gnu_expr_location_from_node (tree, Node_Id);
247 static bool set_end_locus_from_node (tree, Node_Id);
248 static int lvalue_required_p (Node_Id, tree, bool, bool);
249 static tree build_raise_check (int, enum exception_info_kind);
250 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
251 static bool maybe_make_gnu_thunk (Entity_Id gnat_thunk, tree gnu_thunk);
252
253 /* Hooks for debug info back-ends, only supported and used in a restricted set
254 of configurations. */
255 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
256 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
257 \f
258 /* This makes gigi's file_info_ptr visible in this translation unit,
259 so that Sloc_to_locus can look it up when deciding whether to map
260 decls to instances. */
261
262 static struct File_Info_Type *file_map;
263
264 /* This is the main program of the back-end. It sets up all the table
265 structures and then generates code. */
266
267 void
268 gigi (Node_Id gnat_root,
269 int max_gnat_node,
270 int number_name ATTRIBUTE_UNUSED,
271 struct Node *nodes_ptr,
272 struct Flags *flags_ptr,
273 Node_Id *next_node_ptr,
274 Node_Id *prev_node_ptr,
275 struct Elist_Header *elists_ptr,
276 struct Elmt_Item *elmts_ptr,
277 struct String_Entry *strings_ptr,
278 Char_Code *string_chars_ptr,
279 struct List_Header *list_headers_ptr,
280 Nat number_file,
281 struct File_Info_Type *file_info_ptr,
282 Entity_Id standard_boolean,
283 Entity_Id standard_integer,
284 Entity_Id standard_character,
285 Entity_Id standard_long_long_float,
286 Entity_Id standard_exception_type,
287 Int gigi_operating_mode)
288 {
289 Node_Id gnat_iter;
290 Entity_Id gnat_literal;
291 tree t, ftype, int64_type;
292 struct elab_info *info;
293 int i;
294
295 max_gnat_nodes = max_gnat_node;
296
297 Nodes_Ptr = nodes_ptr;
298 Flags_Ptr = flags_ptr;
299 Next_Node_Ptr = next_node_ptr;
300 Prev_Node_Ptr = prev_node_ptr;
301 Elists_Ptr = elists_ptr;
302 Elmts_Ptr = elmts_ptr;
303 Strings_Ptr = strings_ptr;
304 String_Chars_Ptr = string_chars_ptr;
305 List_Headers_Ptr = list_headers_ptr;
306
307 type_annotate_only = (gigi_operating_mode == 1);
308
309 if (Generate_SCO_Instance_Table != 0)
310 {
311 file_map = file_info_ptr;
312 maybe_create_decl_to_instance_map (number_file);
313 }
314
315 for (i = 0; i < number_file; i++)
316 {
317 /* Use the identifier table to make a permanent copy of the filename as
318 the name table gets reallocated after Gigi returns but before all the
319 debugging information is output. The __gnat_to_canonical_file_spec
320 call translates filenames from pragmas Source_Reference that contain
321 host style syntax not understood by gdb. */
322 const char *filename
323 = IDENTIFIER_POINTER
324 (get_identifier
325 (__gnat_to_canonical_file_spec
326 (Get_Name_String (file_info_ptr[i].File_Name))));
327
328 /* We rely on the order isomorphism between files and line maps. */
329 gcc_assert ((int) LINEMAPS_ORDINARY_USED (line_table) == i);
330
331 /* We create the line map for a source file at once, with a fixed number
332 of columns chosen to avoid jumping over the next power of 2. */
333 linemap_add (line_table, LC_ENTER, 0, filename, 1);
334 linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
335 linemap_position_for_column (line_table, 252 - 1);
336 linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
337 }
338
339 gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
340
341 /* Declare the name of the compilation unit as the first global
342 name in order to make the middle-end fully deterministic. */
343 t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
344 first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
345
346 /* Initialize ourselves. */
347 init_code_table ();
348 init_gnat_decl ();
349 init_gnat_utils ();
350
351 /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
352 errors. */
353 if (type_annotate_only)
354 {
355 TYPE_SIZE (void_type_node) = bitsize_zero_node;
356 TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
357 }
358
359 /* Enable GNAT stack checking method if needed */
360 if (!Stack_Check_Probes_On_Target)
361 set_stack_check_libfunc ("_gnat_stack_check");
362
363 /* Retrieve alignment settings. */
364 double_float_alignment = get_target_double_float_alignment ();
365 double_scalar_alignment = get_target_double_scalar_alignment ();
366
367 /* Record the builtin types. Define `integer' and `character' first so that
368 dbx will output them first. */
369 record_builtin_type ("integer", integer_type_node, false);
370 record_builtin_type ("character", char_type_node, false);
371 record_builtin_type ("boolean", boolean_type_node, false);
372 record_builtin_type ("void", void_type_node, false);
373
374 /* Save the type we made for integer as the type for Standard.Integer. */
375 save_gnu_tree (Base_Type (standard_integer),
376 TYPE_NAME (integer_type_node),
377 false);
378
379 /* Likewise for character as the type for Standard.Character. */
380 finish_character_type (char_type_node);
381 save_gnu_tree (Base_Type (standard_character),
382 TYPE_NAME (char_type_node),
383 false);
384
385 /* Likewise for boolean as the type for Standard.Boolean. */
386 save_gnu_tree (Base_Type (standard_boolean),
387 TYPE_NAME (boolean_type_node),
388 false);
389 gnat_literal = First_Literal (Base_Type (standard_boolean));
390 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
391 gcc_assert (t == boolean_false_node);
392 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
393 boolean_type_node, t, true, false, false, false, false,
394 true, false, NULL, gnat_literal);
395 save_gnu_tree (gnat_literal, t, false);
396 gnat_literal = Next_Literal (gnat_literal);
397 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
398 gcc_assert (t == boolean_true_node);
399 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
400 boolean_type_node, t, true, false, false, false, false,
401 true, false, NULL, gnat_literal);
402 save_gnu_tree (gnat_literal, t, false);
403
404 /* Declare the building blocks of function nodes. */
405 void_list_node = build_tree_list (NULL_TREE, void_type_node);
406 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
407 ptr_void_ftype = build_pointer_type (void_ftype);
408
409 /* Now declare run-time functions. */
410 malloc_decl
411 = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
412 build_function_type_list (ptr_type_node, sizetype,
413 NULL_TREE),
414 NULL_TREE, is_default, true, true, true, false,
415 false, NULL, Empty);
416 DECL_IS_MALLOC (malloc_decl) = 1;
417
418 free_decl
419 = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
420 build_function_type_list (void_type_node,
421 ptr_type_node, NULL_TREE),
422 NULL_TREE, is_default, true, true, true, false,
423 false, NULL, Empty);
424
425 realloc_decl
426 = create_subprog_decl (get_identifier ("__gnat_realloc"), NULL_TREE,
427 build_function_type_list (ptr_type_node,
428 ptr_type_node, sizetype,
429 NULL_TREE),
430 NULL_TREE, is_default, true, true, true, false,
431 false, NULL, Empty);
432
433 /* This is used for 64-bit multiplication with overflow checking. */
434 int64_type = gnat_type_for_size (64, 0);
435 mulv64_decl
436 = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
437 build_function_type_list (int64_type, int64_type,
438 int64_type, NULL_TREE),
439 NULL_TREE, is_default, true, true, true, false,
440 false, NULL, Empty);
441
442 /* Name of the _Parent field in tagged record types. */
443 parent_name_id = get_identifier (Get_Name_String (Name_uParent));
444
445 /* Name of the Exception_Data type defined in System.Standard_Library. */
446 exception_data_name_id
447 = get_identifier ("system__standard_library__exception_data");
448
449 /* Make the types and functions used for exception processing. */
450 except_type_node = gnat_to_gnu_type (Base_Type (standard_exception_type));
451
452 jmpbuf_type
453 = build_array_type (gnat_type_for_mode (Pmode, 0),
454 build_index_type (size_int (5)));
455 record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
456 jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
457
458 /* Functions to get and set the jumpbuf pointer for the current thread. */
459 get_jmpbuf_decl
460 = create_subprog_decl
461 (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
462 NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
463 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
464
465 set_jmpbuf_decl
466 = create_subprog_decl
467 (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
468 NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
469 NULL_TREE),
470 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
471
472 get_excptr_decl
473 = create_subprog_decl
474 (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
475 build_function_type_list (build_pointer_type (except_type_node),
476 NULL_TREE),
477 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
478
479 not_handled_by_others_decl = get_identifier ("not_handled_by_others");
480 for (t = TYPE_FIELDS (except_type_node); t; t = DECL_CHAIN (t))
481 if (DECL_NAME (t) == not_handled_by_others_decl)
482 {
483 not_handled_by_others_decl = t;
484 break;
485 }
486 gcc_assert (DECL_P (not_handled_by_others_decl));
487
488 /* setjmp returns an integer and has one operand, which is a pointer to
489 a jmpbuf. */
490 setjmp_decl
491 = create_subprog_decl
492 (get_identifier ("__builtin_setjmp"), NULL_TREE,
493 build_function_type_list (integer_type_node, jmpbuf_ptr_type,
494 NULL_TREE),
495 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
496 DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
497 DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
498
499 /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
500 address. */
501 update_setjmp_buf_decl
502 = create_subprog_decl
503 (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
504 build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
505 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
506 DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
507 DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
508
509 /* Indicate that it never returns. */
510 ftype = build_function_type_list (void_type_node,
511 build_pointer_type (except_type_node),
512 NULL_TREE);
513 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
514 raise_nodefer_decl
515 = create_subprog_decl
516 (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE, ftype,
517 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
518
519 set_exception_parameter_decl
520 = create_subprog_decl
521 (get_identifier ("__gnat_set_exception_parameter"), NULL_TREE,
522 build_function_type_list (void_type_node, ptr_type_node, ptr_type_node,
523 NULL_TREE),
524 NULL_TREE, is_default, true, true, true, false, false, NULL, Empty);
525
526 /* Hooks to call when entering/leaving an exception handler. */
527 ftype = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
528
529 begin_handler_decl
530 = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
531 ftype, NULL_TREE,
532 is_default, true, true, true, false, false, NULL,
533 Empty);
534 /* __gnat_begin_handler is a dummy procedure. */
535 TREE_NOTHROW (begin_handler_decl) = 1;
536
537 end_handler_decl
538 = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
539 ftype, NULL_TREE,
540 is_default, true, true, true, false, false, NULL,
541 Empty);
542
543 unhandled_except_decl
544 = create_subprog_decl (get_identifier ("__gnat_unhandled_except_handler"),
545 NULL_TREE, ftype, NULL_TREE,
546 is_default, true, true, true, false, false, NULL,
547 Empty);
548
549 /* Indicate that it never returns. */
550 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
551 reraise_zcx_decl
552 = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
553 ftype, NULL_TREE,
554 is_default, true, true, true, false, false, NULL,
555 Empty);
556
557 /* Dummy objects to materialize "others" and "all others" in the exception
558 tables. These are exported by a-exexpr-gcc.adb, so see this unit for
559 the types to use. */
560 others_decl
561 = create_var_decl (get_identifier ("OTHERS"),
562 get_identifier ("__gnat_others_value"),
563 char_type_node, NULL_TREE,
564 true, false, true, false, false, true, false,
565 NULL, Empty);
566
567 all_others_decl
568 = create_var_decl (get_identifier ("ALL_OTHERS"),
569 get_identifier ("__gnat_all_others_value"),
570 char_type_node, NULL_TREE,
571 true, false, true, false, false, true, false,
572 NULL, Empty);
573
574 unhandled_others_decl
575 = create_var_decl (get_identifier ("UNHANDLED_OTHERS"),
576 get_identifier ("__gnat_unhandled_others_value"),
577 char_type_node, NULL_TREE,
578 true, false, true, false, false, true, false,
579 NULL, Empty);
580
581 /* If in no exception handlers mode, all raise statements are redirected to
582 __gnat_last_chance_handler. No need to redefine raise_nodefer_decl since
583 this procedure will never be called in this mode. */
584 if (No_Exception_Handlers_Set ())
585 {
586 /* Indicate that it never returns. */
587 ftype = build_function_type_list (void_type_node,
588 build_pointer_type (char_type_node),
589 integer_type_node, NULL_TREE);
590 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
591 tree decl
592 = create_subprog_decl
593 (get_identifier ("__gnat_last_chance_handler"), NULL_TREE, ftype,
594 NULL_TREE, is_default, true, true, true, false, false, NULL,
595 Empty);
596 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
597 gnat_raise_decls[i] = decl;
598 }
599 else
600 {
601 /* Otherwise, make one decl for each exception reason. */
602 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
603 gnat_raise_decls[i] = build_raise_check (i, exception_simple);
604 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
605 gnat_raise_decls_ext[i]
606 = build_raise_check (i,
607 i == CE_Index_Check_Failed
608 || i == CE_Range_Check_Failed
609 || i == CE_Invalid_Data
610 ? exception_range : exception_column);
611 }
612
613 /* Build the special descriptor type and its null node if needed. */
614 if (TARGET_VTABLE_USES_DESCRIPTORS)
615 {
616 tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
617 tree field_list = NULL_TREE;
618 int j;
619 vec<constructor_elt, va_gc> *null_vec = NULL;
620 constructor_elt *elt;
621
622 fdesc_type_node = make_node (RECORD_TYPE);
623 vec_safe_grow (null_vec, TARGET_VTABLE_USES_DESCRIPTORS);
624 elt = (null_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
625
626 for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
627 {
628 tree field
629 = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
630 NULL_TREE, NULL_TREE, 0, 1);
631 DECL_CHAIN (field) = field_list;
632 field_list = field;
633 elt->index = field;
634 elt->value = null_node;
635 elt--;
636 }
637
638 finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
639 record_builtin_type ("descriptor", fdesc_type_node, true);
640 null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
641 }
642
643 longest_float_type_node
644 = get_unpadded_type (Base_Type (standard_long_long_float));
645
646 main_identifier_node = get_identifier ("main");
647
648 /* If we are using the GCC exception mechanism, let GCC know. */
649 if (Back_End_Exceptions ())
650 gnat_init_gcc_eh ();
651
652 /* Initialize the GCC support for FP operations. */
653 gnat_init_gcc_fp ();
654
655 /* Install the builtins we might need, either internally or as user-available
656 facilities for Intrinsic imports. Note that this must be done after the
657 GCC exception mechanism is initialized. */
658 gnat_install_builtins ();
659
660 vec_safe_push (gnu_except_ptr_stack, NULL_TREE);
661
662 gnu_constraint_error_label_stack.safe_push (Empty);
663 gnu_storage_error_label_stack.safe_push (Empty);
664 gnu_program_error_label_stack.safe_push (Empty);
665
666 /* Process any Pragma Ident for the main unit. */
667 if (Present (Ident_String (Main_Unit)))
668 targetm.asm_out.output_ident
669 (TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
670
671 /* Force -fno-strict-aliasing if the configuration pragma was seen. */
672 if (No_Strict_Aliasing_CP)
673 flag_strict_aliasing = 0;
674
675 /* Save the current optimization options again after the above possible
676 global_options changes. */
677 optimization_default_node = build_optimization_node (&global_options);
678 optimization_current_node = optimization_default_node;
679
680 /* Now translate the compilation unit proper. */
681 Compilation_Unit_to_gnu (gnat_root);
682
683 /* Then process the N_Validate_Unchecked_Conversion nodes. We do this at
684 the very end to avoid having to second-guess the front-end when we run
685 into dummy nodes during the regular processing. */
686 for (i = 0; gnat_validate_uc_list.iterate (i, &gnat_iter); i++)
687 validate_unchecked_conversion (gnat_iter);
688 gnat_validate_uc_list.release ();
689
690 /* Finally see if we have any elaboration procedures to deal with. */
691 for (info = elab_info_list; info; info = info->next)
692 {
693 tree gnu_body = DECL_SAVED_TREE (info->elab_proc);
694
695 /* We should have a BIND_EXPR but it may not have any statements in it.
696 If it doesn't have any, we have nothing to do except for setting the
697 flag on the GNAT node. Otherwise, process the function as others. */
698 tree gnu_stmts = gnu_body;
699 if (TREE_CODE (gnu_stmts) == BIND_EXPR)
700 gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
701 if (!gnu_stmts || empty_stmt_list_p (gnu_stmts))
702 Set_Has_No_Elaboration_Code (info->gnat_node, 1);
703 else
704 {
705 begin_subprog_body (info->elab_proc);
706 end_subprog_body (gnu_body);
707 rest_of_subprog_body_compilation (info->elab_proc);
708 }
709 }
710
711 /* Destroy ourselves. */
712 file_map = NULL;
713 destroy_gnat_decl ();
714 destroy_gnat_utils ();
715
716 /* We cannot track the location of errors past this point. */
717 Current_Error_Node = Empty;
718 }
719 \f
720 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
721 CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext. */
722
723 static tree
724 build_raise_check (int check, enum exception_info_kind kind)
725 {
726 tree result, ftype;
727 const char pfx[] = "__gnat_rcheck_";
728
729 strcpy (Name_Buffer, pfx);
730 Name_Len = sizeof (pfx) - 1;
731 Get_RT_Exception_Name (check);
732
733 if (kind == exception_simple)
734 {
735 Name_Buffer[Name_Len] = 0;
736 ftype
737 = build_function_type_list (void_type_node,
738 build_pointer_type (char_type_node),
739 integer_type_node, NULL_TREE);
740 }
741 else
742 {
743 tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
744
745 strcpy (Name_Buffer + Name_Len, "_ext");
746 Name_Buffer[Name_Len + 4] = 0;
747 ftype
748 = build_function_type_list (void_type_node,
749 build_pointer_type (char_type_node),
750 integer_type_node, integer_type_node,
751 t, t, NULL_TREE);
752 }
753
754 /* Indicate that it never returns. */
755 ftype = build_qualified_type (ftype, TYPE_QUAL_VOLATILE);
756 result
757 = create_subprog_decl (get_identifier (Name_Buffer), NULL_TREE, ftype,
758 NULL_TREE, is_default, true, true, true, false,
759 false, NULL, Empty);
760
761 return result;
762 }
763 \f
764 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
765 an N_Attribute_Reference. */
766
767 static int
768 lvalue_required_for_attribute_p (Node_Id gnat_node)
769 {
770 switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
771 {
772 case Attr_Pos:
773 case Attr_Val:
774 case Attr_Pred:
775 case Attr_Succ:
776 case Attr_First:
777 case Attr_Last:
778 case Attr_Range_Length:
779 case Attr_Length:
780 case Attr_Object_Size:
781 case Attr_Value_Size:
782 case Attr_Component_Size:
783 case Attr_Descriptor_Size:
784 case Attr_Max_Size_In_Storage_Elements:
785 case Attr_Min:
786 case Attr_Max:
787 case Attr_Null_Parameter:
788 case Attr_Passed_By_Reference:
789 case Attr_Mechanism_Code:
790 case Attr_Machine:
791 case Attr_Model:
792 return 0;
793
794 case Attr_Address:
795 case Attr_Access:
796 case Attr_Unchecked_Access:
797 case Attr_Unrestricted_Access:
798 case Attr_Code_Address:
799 case Attr_Pool_Address:
800 case Attr_Size:
801 case Attr_Alignment:
802 case Attr_Bit_Position:
803 case Attr_Position:
804 case Attr_First_Bit:
805 case Attr_Last_Bit:
806 case Attr_Bit:
807 case Attr_Asm_Input:
808 case Attr_Asm_Output:
809 default:
810 return 1;
811 }
812 }
813
814 /* Return a positive value if an lvalue is required for GNAT_NODE. GNU_TYPE
815 is the type that will be used for GNAT_NODE in the translated GNU tree.
816 CONSTANT indicates whether the underlying object represented by GNAT_NODE
817 is constant in the Ada sense. If it is, ADDRESS_OF_CONSTANT indicates
818 whether its value is the address of another constant. If it isn't, then
819 ADDRESS_OF_CONSTANT is ignored.
820
821 The function climbs up the GNAT tree starting from the node and returns 1
822 upon encountering a node that effectively requires an lvalue downstream.
823 It returns int instead of bool to facilitate usage in non-purely binary
824 logic contexts. */
825
826 static int
827 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
828 bool address_of_constant)
829 {
830 Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
831
832 switch (Nkind (gnat_parent))
833 {
834 case N_Reference:
835 return 1;
836
837 case N_Attribute_Reference:
838 return lvalue_required_for_attribute_p (gnat_parent);
839
840 case N_Parameter_Association:
841 case N_Function_Call:
842 case N_Procedure_Call_Statement:
843 /* If the parameter is by reference, an lvalue is required. */
844 return (!constant
845 || must_pass_by_ref (gnu_type)
846 || default_pass_by_ref (gnu_type));
847
848 case N_Indexed_Component:
849 /* Only the array expression can require an lvalue. */
850 if (Prefix (gnat_parent) != gnat_node)
851 return 0;
852
853 /* ??? Consider that referencing an indexed component with a variable
854 index forces the whole aggregate to memory. Note that testing only
855 for literals is conservative, any static expression in the RM sense
856 could probably be accepted with some additional work. */
857 for (gnat_temp = First (Expressions (gnat_parent));
858 Present (gnat_temp);
859 gnat_temp = Next (gnat_temp))
860 if (Nkind (gnat_temp) != N_Character_Literal
861 && Nkind (gnat_temp) != N_Integer_Literal
862 && !(Is_Entity_Name (gnat_temp)
863 && Ekind (Entity (gnat_temp)) == E_Enumeration_Literal))
864 return 1;
865
866 /* ... fall through ... */
867
868 case N_Slice:
869 /* Only the array expression can require an lvalue. */
870 if (Prefix (gnat_parent) != gnat_node)
871 return 0;
872
873 return lvalue_required_p (gnat_parent, gnu_type, constant,
874 address_of_constant);
875
876 case N_Selected_Component:
877 return lvalue_required_p (gnat_parent, gnu_type, constant,
878 address_of_constant);
879
880 case N_Object_Renaming_Declaration:
881 /* We need to preserve addresses through a renaming. */
882 return 1;
883
884 case N_Object_Declaration:
885 /* We cannot use a constructor if this is an atomic object because
886 the actual assignment might end up being done component-wise. */
887 return (!constant
888 ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
889 && Is_Atomic_Or_VFA (Defining_Entity (gnat_parent)))
890 /* We don't use a constructor if this is a class-wide object
891 because the effective type of the object is the equivalent
892 type of the class-wide subtype and it smashes most of the
893 data into an array of bytes to which we cannot convert. */
894 || Ekind ((Etype (Defining_Entity (gnat_parent))))
895 == E_Class_Wide_Subtype);
896
897 case N_Assignment_Statement:
898 /* We cannot use a constructor if the LHS is an atomic object because
899 the actual assignment might end up being done component-wise. */
900 return (!constant
901 || Name (gnat_parent) == gnat_node
902 || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
903 && Is_Entity_Name (Name (gnat_parent))
904 && Is_Atomic_Or_VFA (Entity (Name (gnat_parent)))));
905
906 case N_Unchecked_Type_Conversion:
907 if (!constant)
908 return 1;
909
910 /* ... fall through ... */
911
912 case N_Type_Conversion:
913 case N_Qualified_Expression:
914 /* We must look through all conversions because we may need to bypass
915 an intermediate conversion that is meant to be purely formal. */
916 return lvalue_required_p (gnat_parent,
917 get_unpadded_type (Etype (gnat_parent)),
918 constant, address_of_constant);
919
920 case N_Allocator:
921 /* We should only reach here through the N_Qualified_Expression case.
922 Force an lvalue for composite types since a block-copy to the newly
923 allocated area of memory is made. */
924 return Is_Composite_Type (Underlying_Type (Etype (gnat_node)));
925
926 case N_Explicit_Dereference:
927 /* We look through dereferences for address of constant because we need
928 to handle the special cases listed above. */
929 if (constant && address_of_constant)
930 return lvalue_required_p (gnat_parent,
931 get_unpadded_type (Etype (gnat_parent)),
932 true, false);
933
934 /* ... fall through ... */
935
936 default:
937 return 0;
938 }
939
940 gcc_unreachable ();
941 }
942
943 /* Return true if T is a constant DECL node that can be safely replaced
944 by its initializer. */
945
946 static bool
947 constant_decl_with_initializer_p (tree t)
948 {
949 if (!TREE_CONSTANT (t) || !DECL_P (t) || !DECL_INITIAL (t))
950 return false;
951
952 /* Return false for aggregate types that contain a placeholder since
953 their initializers cannot be manipulated easily. */
954 if (AGGREGATE_TYPE_P (TREE_TYPE (t))
955 && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (t))
956 && type_contains_placeholder_p (TREE_TYPE (t)))
957 return false;
958
959 return true;
960 }
961
962 /* Return an expression equivalent to EXP but where constant DECL nodes
963 have been replaced by their initializer. */
964
965 static tree
966 fold_constant_decl_in_expr (tree exp)
967 {
968 enum tree_code code = TREE_CODE (exp);
969 tree op0;
970
971 switch (code)
972 {
973 case CONST_DECL:
974 case VAR_DECL:
975 if (!constant_decl_with_initializer_p (exp))
976 return exp;
977
978 return DECL_INITIAL (exp);
979
980 case COMPONENT_REF:
981 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
982 if (op0 == TREE_OPERAND (exp, 0))
983 return exp;
984
985 return fold_build3 (COMPONENT_REF, TREE_TYPE (exp), op0,
986 TREE_OPERAND (exp, 1), NULL_TREE);
987
988 case BIT_FIELD_REF:
989 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
990 if (op0 == TREE_OPERAND (exp, 0))
991 return exp;
992
993 return fold_build3 (BIT_FIELD_REF, TREE_TYPE (exp), op0,
994 TREE_OPERAND (exp, 1), TREE_OPERAND (exp, 2));
995
996 case ARRAY_REF:
997 case ARRAY_RANGE_REF:
998 /* If the index is not itself constant, then nothing can be folded. */
999 if (!TREE_CONSTANT (TREE_OPERAND (exp, 1)))
1000 return exp;
1001 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1002 if (op0 == TREE_OPERAND (exp, 0))
1003 return exp;
1004
1005 return fold (build4 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
1006 TREE_OPERAND (exp, 2), NULL_TREE));
1007
1008 case REALPART_EXPR:
1009 case IMAGPART_EXPR:
1010 case VIEW_CONVERT_EXPR:
1011 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1012 if (op0 == TREE_OPERAND (exp, 0))
1013 return exp;
1014
1015 return fold_build1 (code, TREE_TYPE (exp), op0);
1016
1017 default:
1018 return exp;
1019 }
1020
1021 gcc_unreachable ();
1022 }
1023
1024 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
1025 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer
1026 to where we should place the result type. */
1027
1028 static tree
1029 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
1030 {
1031 Node_Id gnat_temp, gnat_temp_type;
1032 tree gnu_result, gnu_result_type;
1033
1034 /* Whether we should require an lvalue for GNAT_NODE. Needed in
1035 specific circumstances only, so evaluated lazily. < 0 means
1036 unknown, > 0 means known true, 0 means known false. */
1037 int require_lvalue = -1;
1038
1039 /* If GNAT_NODE is a constant, whether we should use the initialization
1040 value instead of the constant entity, typically for scalars with an
1041 address clause when the parent doesn't require an lvalue. */
1042 bool use_constant_initializer = false;
1043
1044 /* If the Etype of this node is not the same as that of the Entity, then
1045 something went wrong, probably in generic instantiation. However, this
1046 does not apply to types. Since we sometime have strange Ekind's, just
1047 do this test for objects. Moreover, if the Etype of the Entity is private
1048 or incomplete coming from a limited context, the Etype of the N_Identifier
1049 is allowed to be the full/non-limited view and we also consider a packed
1050 array type to be the same as the original type. Similarly, a CW type is
1051 equivalent to a subtype of itself. Finally, if the types are Itypes, one
1052 may be a copy of the other, which is also legal. */
1053 gnat_temp = ((Nkind (gnat_node) == N_Defining_Identifier
1054 || Nkind (gnat_node) == N_Defining_Operator_Symbol)
1055 ? gnat_node : Entity (gnat_node));
1056 gnat_temp_type = Etype (gnat_temp);
1057
1058 gcc_assert (Etype (gnat_node) == gnat_temp_type
1059 || (Is_Packed (gnat_temp_type)
1060 && (Etype (gnat_node)
1061 == Packed_Array_Impl_Type (gnat_temp_type)))
1062 || (Is_Class_Wide_Type (Etype (gnat_node)))
1063 || (Is_Incomplete_Or_Private_Type (gnat_temp_type)
1064 && Present (Full_View (gnat_temp_type))
1065 && ((Etype (gnat_node) == Full_View (gnat_temp_type))
1066 || (Is_Packed (Full_View (gnat_temp_type))
1067 && (Etype (gnat_node)
1068 == Packed_Array_Impl_Type
1069 (Full_View (gnat_temp_type))))))
1070 || (Is_Incomplete_Type (gnat_temp_type)
1071 && From_Limited_With (gnat_temp_type)
1072 && Present (Non_Limited_View (gnat_temp_type))
1073 && Etype (gnat_node) == Non_Limited_View (gnat_temp_type))
1074 || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
1075 || !(Ekind (gnat_temp) == E_Variable
1076 || Ekind (gnat_temp) == E_Component
1077 || Ekind (gnat_temp) == E_Constant
1078 || Ekind (gnat_temp) == E_Loop_Parameter
1079 || Is_Formal (gnat_temp)));
1080
1081 /* If this is a reference to a deferred constant whose partial view is an
1082 unconstrained private type, the proper type is on the full view of the
1083 constant, not on the full view of the type, which may be unconstrained.
1084
1085 This may be a reference to a type, for example in the prefix of the
1086 attribute Position, generated for dispatching code (see Make_DT in
1087 exp_disp,adb). In that case we need the type itself, not is parent,
1088 in particular if it is a derived type */
1089 if (Ekind (gnat_temp) == E_Constant
1090 && Is_Private_Type (gnat_temp_type)
1091 && (Has_Unknown_Discriminants (gnat_temp_type)
1092 || (Present (Full_View (gnat_temp_type))
1093 && Has_Discriminants (Full_View (gnat_temp_type))))
1094 && Present (Full_View (gnat_temp)))
1095 {
1096 gnat_temp = Full_View (gnat_temp);
1097 gnat_temp_type = Etype (gnat_temp);
1098 }
1099 else
1100 {
1101 /* We want to use the Actual_Subtype if it has already been elaborated,
1102 otherwise the Etype. Avoid using Actual_Subtype for packed arrays to
1103 simplify things. */
1104 if ((Ekind (gnat_temp) == E_Constant
1105 || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
1106 && !(Is_Array_Type (Etype (gnat_temp))
1107 && Present (Packed_Array_Impl_Type (Etype (gnat_temp))))
1108 && Present (Actual_Subtype (gnat_temp))
1109 && present_gnu_tree (Actual_Subtype (gnat_temp)))
1110 gnat_temp_type = Actual_Subtype (gnat_temp);
1111 else
1112 gnat_temp_type = Etype (gnat_node);
1113 }
1114
1115 /* Expand the type of this identifier first, in case it is an enumeral
1116 literal, which only get made when the type is expanded. There is no
1117 order-of-elaboration issue here. */
1118 gnu_result_type = get_unpadded_type (gnat_temp_type);
1119
1120 /* If this is a non-imported elementary constant with an address clause,
1121 retrieve the value instead of a pointer to be dereferenced unless
1122 an lvalue is required. This is generally more efficient and actually
1123 required if this is a static expression because it might be used
1124 in a context where a dereference is inappropriate, such as a case
1125 statement alternative or a record discriminant. There is no possible
1126 volatile-ness short-circuit here since Volatile constants must be
1127 imported per C.6. */
1128 if (Ekind (gnat_temp) == E_Constant
1129 && Is_Elementary_Type (gnat_temp_type)
1130 && !Is_Imported (gnat_temp)
1131 && Present (Address_Clause (gnat_temp)))
1132 {
1133 require_lvalue
1134 = lvalue_required_p (gnat_node, gnu_result_type, true, false);
1135 use_constant_initializer = !require_lvalue;
1136 }
1137
1138 if (use_constant_initializer)
1139 {
1140 /* If this is a deferred constant, the initializer is attached to
1141 the full view. */
1142 if (Present (Full_View (gnat_temp)))
1143 gnat_temp = Full_View (gnat_temp);
1144
1145 gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
1146 }
1147 else
1148 gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, false);
1149
1150 /* Some objects (such as parameters passed by reference, globals of
1151 variable size, and renamed objects) actually represent the address
1152 of the object. In that case, we must do the dereference. Likewise,
1153 deal with parameters to foreign convention subprograms. */
1154 if (DECL_P (gnu_result)
1155 && (DECL_BY_REF_P (gnu_result)
1156 || (TREE_CODE (gnu_result) == PARM_DECL
1157 && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1158 {
1159 const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1160
1161 /* If it's a PARM_DECL to foreign convention subprogram, convert it. */
1162 if (TREE_CODE (gnu_result) == PARM_DECL
1163 && DECL_BY_COMPONENT_PTR_P (gnu_result))
1164 gnu_result
1165 = convert (build_pointer_type (gnu_result_type), gnu_result);
1166
1167 /* If it's a CONST_DECL, return the underlying constant like below. */
1168 else if (TREE_CODE (gnu_result) == CONST_DECL
1169 && !(DECL_CONST_ADDRESS_P (gnu_result)
1170 && lvalue_required_p (gnat_node, gnu_result_type, true,
1171 true)))
1172 gnu_result = DECL_INITIAL (gnu_result);
1173
1174 /* If it's a renaming pointer, get to the renamed object. */
1175 if (TREE_CODE (gnu_result) == VAR_DECL
1176 && !DECL_LOOP_PARM_P (gnu_result)
1177 && DECL_RENAMED_OBJECT (gnu_result))
1178 gnu_result = DECL_RENAMED_OBJECT (gnu_result);
1179
1180 /* Otherwise, do the final dereference. */
1181 else
1182 {
1183 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1184
1185 if ((TREE_CODE (gnu_result) == INDIRECT_REF
1186 || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1187 && No (Address_Clause (gnat_temp)))
1188 TREE_THIS_NOTRAP (gnu_result) = 1;
1189
1190 if (read_only)
1191 TREE_READONLY (gnu_result) = 1;
1192 }
1193 }
1194
1195 /* If we have a constant declaration and its initializer, try to return the
1196 latter to avoid the need to call fold in lots of places and the need for
1197 elaboration code if this identifier is used as an initializer itself. */
1198 if (constant_decl_with_initializer_p (gnu_result))
1199 {
1200 bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1201 && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1202 bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1203 && DECL_CONST_ADDRESS_P (gnu_result));
1204
1205 /* If there is a (corresponding) variable or this is the address of a
1206 constant, we only want to return the initializer if an lvalue isn't
1207 required. Evaluate this now if we have not already done so. */
1208 if ((!constant_only || address_of_constant) && require_lvalue < 0)
1209 require_lvalue
1210 = lvalue_required_p (gnat_node, gnu_result_type, true,
1211 address_of_constant);
1212
1213 /* Finally retrieve the initializer if this is deemed valid. */
1214 if ((constant_only && !address_of_constant) || !require_lvalue)
1215 gnu_result = DECL_INITIAL (gnu_result);
1216 }
1217
1218 /* But for a constant renaming we couldn't do that incrementally for its
1219 definition because of the need to return an lvalue so, if the present
1220 context doesn't itself require an lvalue, we try again here. */
1221 else if (Ekind (gnat_temp) == E_Constant
1222 && Is_Elementary_Type (gnat_temp_type)
1223 && Present (Renamed_Object (gnat_temp)))
1224 {
1225 if (require_lvalue < 0)
1226 require_lvalue
1227 = lvalue_required_p (gnat_node, gnu_result_type, true, false);
1228 if (!require_lvalue)
1229 gnu_result = fold_constant_decl_in_expr (gnu_result);
1230 }
1231
1232 /* The GNAT tree has the type of a function set to its result type, so we
1233 adjust here. Also use the type of the result if the Etype is a subtype
1234 that is nominally unconstrained. Likewise if this is a deferred constant
1235 of a discriminated type whose full view can be elaborated statically, to
1236 avoid problematic conversions to the nominal subtype. But remove any
1237 padding from the resulting type. */
1238 if (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_result))
1239 || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type)
1240 || (Ekind (gnat_temp) == E_Constant
1241 && Present (Full_View (gnat_temp))
1242 && Has_Discriminants (gnat_temp_type)
1243 && TREE_CODE (gnu_result) == CONSTRUCTOR))
1244 {
1245 gnu_result_type = TREE_TYPE (gnu_result);
1246 if (TYPE_IS_PADDING_P (gnu_result_type))
1247 gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1248 }
1249
1250 *gnu_result_type_p = gnu_result_type;
1251
1252 return gnu_result;
1253 }
1254 \f
1255 /* If GNAT_EXPR is an N_Identifier, N_Integer_Literal or N_Operator_Symbol,
1256 call FN on it. If GNAT_EXPR is an aggregate, call FN on each of its
1257 elements. In both cases, pass GNU_EXPR and DATA as additional arguments.
1258
1259 This function is used everywhere OpenAcc pragmas are processed if these
1260 pragmas can accept aggregates. */
1261
1262 static tree
1263 Iterate_Acc_Clause_Arg (Node_Id gnat_expr, tree gnu_expr,
1264 tree (*fn)(Node_Id, tree, void*),
1265 void* data)
1266 {
1267 switch (Nkind (gnat_expr))
1268 {
1269 case N_Aggregate:
1270 if (Present (Expressions (gnat_expr)))
1271 {
1272 for (Node_Id gnat_list_expr = First (Expressions (gnat_expr));
1273 Present (gnat_list_expr);
1274 gnat_list_expr = Next (gnat_list_expr))
1275 gnu_expr = fn (gnat_list_expr, gnu_expr, data);
1276 }
1277 else if (Present (Component_Associations (gnat_expr)))
1278 {
1279 for (Node_Id gnat_list_expr = First (Component_Associations
1280 (gnat_expr));
1281 Present (gnat_list_expr);
1282 gnat_list_expr = Next (gnat_list_expr))
1283 gnu_expr = fn (Expression (gnat_list_expr), gnu_expr, data);
1284 }
1285 else
1286 gcc_unreachable ();
1287 break;
1288
1289 case N_Identifier:
1290 case N_Integer_Literal:
1291 case N_Operator_Symbol:
1292 gnu_expr = fn (gnat_expr, gnu_expr, data);
1293 break;
1294
1295 default:
1296 gcc_unreachable ();
1297 }
1298
1299 return gnu_expr;
1300 }
1301
1302 /* Same as gnat_to_gnu for a GNAT_NODE referenced within an OpenAcc directive,
1303 undoing transformations that are inappropriate for such context. */
1304
1305 tree
1306 Acc_gnat_to_gnu (Node_Id gnat_node)
1307 {
1308 tree gnu_result = gnat_to_gnu (gnat_node);
1309
1310 /* If gnat_node is an identifier for a boolean, gnat_to_gnu might have
1311 turned it into `identifier != 0`. Since arguments to OpenAcc pragmas
1312 need to be writable, we need to return the identifier residing in such
1313 expressions rather than the expression itself. */
1314 if (Nkind (gnat_node) == N_Identifier
1315 && TREE_CODE (gnu_result) == NE_EXPR
1316 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_result, 0))) == BOOLEAN_TYPE
1317 && integer_zerop (TREE_OPERAND (gnu_result, 1)))
1318 gnu_result = TREE_OPERAND (gnu_result, 0);
1319
1320 return gnu_result;
1321 }
1322
1323 /* Turn GNAT_EXPR into a tree node representing an OMP data clause and chain
1324 it to GNU_CLAUSES, a list of pre-existing OMP clauses. GNAT_EXPR should be
1325 a N_Identifier, this is enforced by the frontend.
1326
1327 This function is called every time translation of an argument for an OpenAcc
1328 clause (e.g. Acc_Parallel(Copy => My_Identifier)) is needed. */
1329
1330 static tree
1331 Acc_Data_to_gnu (Node_Id gnat_expr, tree gnu_clauses, void* data)
1332 {
1333 const enum gomp_map_kind kind = *((enum gomp_map_kind*) data);
1334 tree gnu_clause
1335 = build_omp_clause (EXPR_LOCATION(gnu_loop_stack->last ()->stmt),
1336 OMP_CLAUSE_MAP);
1337
1338 gcc_assert (Nkind (gnat_expr) == N_Identifier);
1339 OMP_CLAUSE_DECL (gnu_clause)
1340 = gnat_to_gnu_entity (Entity (gnat_expr), NULL_TREE, false);
1341
1342 TREE_ADDRESSABLE (OMP_CLAUSE_DECL (gnu_clause)) = 1;
1343 OMP_CLAUSE_SET_MAP_KIND (gnu_clause, kind);
1344 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1345
1346 return gnu_clause;
1347 }
1348
1349 /* Turn GNAT_EXPR into a tree node representing an OMP clause and chain it to
1350 GNU_CLAUSES, a list of existing OMP clauses.
1351
1352 This function is used for parsing arguments of non-data clauses (e.g.
1353 Acc_Parallel(Wait => gnatexpr)). */
1354
1355 static tree
1356 Acc_Var_to_gnu (Node_Id gnat_expr, tree gnu_clauses, void* data)
1357 {
1358 const enum omp_clause_code kind = *((enum omp_clause_code*) data);
1359 tree gnu_clause
1360 = build_omp_clause (EXPR_LOCATION (gnu_loop_stack->last ()->stmt), kind);
1361
1362 OMP_CLAUSE_DECL (gnu_clause) = Acc_gnat_to_gnu (gnat_expr);
1363 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1364
1365 return gnu_clause;
1366 }
1367
1368 /* Turn GNAT_EXPR into a tree OMP clause representing a reduction clause.
1369 GNAT_EXPR has to be a N_Identifier, this is enforced by the frontend.
1370
1371 For example, GNAT_EXPR could be My_Identifier in the following pragma:
1372 Acc_Parallel(Reduction => ("+" => My_Identifier)). */
1373
1374 static tree
1375 Acc_Reduc_Var_to_gnu (Node_Id gnat_expr, tree gnu_clauses, void* data)
1376 {
1377 const tree_code code = *((tree_code*) data);
1378 tree gnu_clause
1379 = build_omp_clause (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1380 OMP_CLAUSE_REDUCTION);
1381
1382 OMP_CLAUSE_DECL (gnu_clause) = Acc_gnat_to_gnu (gnat_expr);
1383 OMP_CLAUSE_REDUCTION_CODE (gnu_clause) = code;
1384 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1385
1386 return gnu_clause;
1387 }
1388
1389 /* Turn GNAT_EXPR into a list of OMP reduction clauses. GNAT_EXPR has to
1390 follow the structure of a reduction clause, e.g. ("+" => Identifier). */
1391
1392 static tree
1393 Acc_Reduc_to_gnu (Node_Id gnat_expr)
1394 {
1395 tree gnu_clauses = NULL_TREE;
1396
1397 for (Node_Id gnat_op = First (Component_Associations (gnat_expr));
1398 Present (gnat_op);
1399 gnat_op = Next (gnat_op))
1400 {
1401 tree_code code = ERROR_MARK;
1402 String_Id str = Strval (First (Choices (gnat_op)));
1403 switch (Get_String_Char (str, 1))
1404 {
1405 case '+':
1406 code = PLUS_EXPR;
1407 break;
1408 case '*':
1409 code = MULT_EXPR;
1410 break;
1411 case 'm':
1412 if (Get_String_Char (str, 2) == 'i'
1413 && Get_String_Char (str, 3) == 'n')
1414 code = MIN_EXPR;
1415 else if (Get_String_Char (str, 2) == 'a'
1416 && Get_String_Char (str, 3) == 'x')
1417 code = MAX_EXPR;
1418 break;
1419 case 'a':
1420 if (Get_String_Char (str, 2) == 'n'
1421 && Get_String_Char (str, 3) == 'd')
1422 code = TRUTH_ANDIF_EXPR;
1423 break;
1424 case 'o':
1425 if (Get_String_Char (str, 2) == 'r')
1426 code = TRUTH_ORIF_EXPR;
1427 break;
1428 default:
1429 gcc_unreachable ();
1430 }
1431
1432 /* Unsupported reduction operation. This should have been
1433 caught in sem_prag.adb. */
1434 gcc_assert (code != ERROR_MARK);
1435
1436 gnu_clauses = Iterate_Acc_Clause_Arg (Expression (gnat_op),
1437 gnu_clauses,
1438 Acc_Reduc_Var_to_gnu,
1439 &code);
1440 }
1441
1442 return gnu_clauses;
1443 }
1444
1445 /* Turn GNAT_EXPR, either '*' or an integer literal, into a tree_cons. This is
1446 only used by Acc_Size_List_to_gnu. */
1447
1448 static tree
1449 Acc_Size_Expr_to_gnu (Node_Id gnat_expr, tree gnu_clauses, void *)
1450 {
1451 tree gnu_expr;
1452
1453 if (Nkind (gnat_expr) == N_Operator_Symbol
1454 && Get_String_Char (Strval (gnat_expr), 1) == '*')
1455 gnu_expr = integer_zero_node;
1456 else
1457 gnu_expr = Acc_gnat_to_gnu (gnat_expr);
1458
1459 return tree_cons (NULL_TREE, gnu_expr, gnu_clauses);
1460 }
1461
1462 /* Turn GNAT_EXPR, an aggregate of either '*' or integer literals, into an OMP
1463 clause node.
1464
1465 This function is used for the Tile clause of the Loop directive. This is
1466 what GNAT_EXPR might look like: (1, 1, '*'). */
1467
1468 static tree
1469 Acc_Size_List_to_gnu (Node_Id gnat_expr)
1470 {
1471 tree gnu_clause
1472 = build_omp_clause (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1473 OMP_CLAUSE_TILE);
1474 tree gnu_list = Iterate_Acc_Clause_Arg (gnat_expr, NULL_TREE,
1475 Acc_Size_Expr_to_gnu,
1476 NULL);
1477
1478 OMP_CLAUSE_TILE_LIST (gnu_clause) = nreverse (gnu_list);
1479
1480 return gnu_clause;
1481 }
1482
1483 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma. Return
1484 any statements we generate. */
1485
1486 static tree
1487 Pragma_to_gnu (Node_Id gnat_node)
1488 {
1489 tree gnu_result = alloc_stmt_list ();
1490 unsigned char pragma_id;
1491 Node_Id gnat_temp;
1492
1493 /* Do nothing if we are just annotating types and check for (and ignore)
1494 unrecognized pragmas. */
1495 if (type_annotate_only
1496 || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1497 return gnu_result;
1498
1499 pragma_id = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
1500 switch (pragma_id)
1501 {
1502 case Pragma_Inspection_Point:
1503 /* Do nothing at top level: all such variables are already viewable. */
1504 if (global_bindings_p ())
1505 break;
1506
1507 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1508 Present (gnat_temp);
1509 gnat_temp = Next (gnat_temp))
1510 {
1511 Node_Id gnat_expr = Expression (gnat_temp);
1512 tree gnu_expr = gnat_to_gnu (gnat_expr);
1513 tree asm_constraint = NULL_TREE;
1514 #ifdef ASM_COMMENT_START
1515 char *comment;
1516 #endif
1517 gnu_expr = maybe_unconstrained_array (gnu_expr);
1518 gnat_mark_addressable (gnu_expr);
1519
1520 #ifdef ASM_COMMENT_START
1521 comment = concat (ASM_COMMENT_START,
1522 " inspection point: ",
1523 Get_Name_String (Chars (gnat_expr)),
1524 " is at %0",
1525 NULL);
1526 asm_constraint = build_string (strlen (comment), comment);
1527 free (comment);
1528 #endif
1529 gnu_expr = build5 (ASM_EXPR, void_type_node,
1530 asm_constraint,
1531 NULL_TREE,
1532 tree_cons
1533 (build_tree_list (NULL_TREE,
1534 build_string (1, "m")),
1535 gnu_expr, NULL_TREE),
1536 NULL_TREE, NULL_TREE);
1537 ASM_VOLATILE_P (gnu_expr) = 1;
1538 set_expr_location_from_node (gnu_expr, gnat_node);
1539 append_to_statement_list (gnu_expr, &gnu_result);
1540 }
1541 break;
1542
1543 case Pragma_Acc_Loop:
1544 {
1545 if (!flag_openacc)
1546 break;
1547
1548 tree gnu_clauses = gnu_loop_stack->last ()->omp_loop_clauses;
1549
1550 if (!Present (Pragma_Argument_Associations (gnat_node)))
1551 break;
1552
1553 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1554 Present (gnat_temp);
1555 gnat_temp = Next (gnat_temp))
1556 {
1557 Node_Id gnat_expr = Expression (gnat_temp);
1558 tree gnu_clause = NULL_TREE;
1559 enum omp_clause_code kind;
1560
1561 if (Chars (gnat_temp) == No_Name)
1562 {
1563 /* The clause is an identifier without a parameter. */
1564 switch (Chars (gnat_expr))
1565 {
1566 case Name_Auto:
1567 kind = OMP_CLAUSE_AUTO;
1568 break;
1569 case Name_Gang:
1570 kind = OMP_CLAUSE_GANG;
1571 break;
1572 case Name_Independent:
1573 kind = OMP_CLAUSE_INDEPENDENT;
1574 break;
1575 case Name_Seq:
1576 kind = OMP_CLAUSE_SEQ;
1577 break;
1578 case Name_Vector:
1579 kind = OMP_CLAUSE_VECTOR;
1580 break;
1581 case Name_Worker:
1582 kind = OMP_CLAUSE_WORKER;
1583 break;
1584 default:
1585 gcc_unreachable ();
1586 }
1587 gnu_clause = build_omp_clause (EXPR_LOCATION
1588 (gnu_loop_stack->last ()->stmt),
1589 kind);
1590 }
1591 else
1592 {
1593 /* The clause is an identifier parameter(s). */
1594 switch (Chars (gnat_temp))
1595 {
1596 case Name_Collapse:
1597 gnu_clause = build_omp_clause
1598 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1599 OMP_CLAUSE_COLLAPSE);
1600 OMP_CLAUSE_COLLAPSE_EXPR (gnu_clause) =
1601 Acc_gnat_to_gnu (gnat_expr);
1602 break;
1603 case Name_Device_Type:
1604 /* Unimplemented by GCC yet. */
1605 gcc_unreachable ();
1606 break;
1607 case Name_Independent:
1608 gnu_clause = build_omp_clause
1609 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1610 OMP_CLAUSE_INDEPENDENT);
1611 break;
1612 case Name_Acc_Private:
1613 kind = OMP_CLAUSE_PRIVATE;
1614 gnu_clause = Iterate_Acc_Clause_Arg (gnat_expr, 0,
1615 Acc_Var_to_gnu,
1616 &kind);
1617 break;
1618 case Name_Reduction:
1619 gnu_clause = Acc_Reduc_to_gnu (gnat_expr);
1620 break;
1621 case Name_Tile:
1622 gnu_clause = Acc_Size_List_to_gnu (gnat_expr);
1623 break;
1624 case Name_Gang:
1625 case Name_Vector:
1626 case Name_Worker:
1627 /* These are for the Loop+Kernel combination, which is
1628 unimplemented by the frontend for now. */
1629 default:
1630 gcc_unreachable ();
1631 }
1632 }
1633 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1634 gnu_clauses = gnu_clause;
1635 }
1636 gnu_loop_stack->last ()->omp_loop_clauses = gnu_clauses;
1637 }
1638 break;
1639
1640 /* Grouping the transformation of these pragmas together makes sense
1641 because they are mutually exclusive, share most of their clauses and
1642 the verification that each clause can legally appear for the pragma has
1643 been done in the frontend. */
1644 case Pragma_Acc_Data:
1645 case Pragma_Acc_Kernels:
1646 case Pragma_Acc_Parallel:
1647 {
1648 if (!flag_openacc)
1649 break;
1650
1651 tree gnu_clauses = gnu_loop_stack->last ()->omp_construct_clauses;
1652 if (pragma_id == Pragma_Acc_Data)
1653 gnu_loop_stack->last ()->omp_code = OACC_DATA;
1654 else if (pragma_id == Pragma_Acc_Kernels)
1655 gnu_loop_stack->last ()->omp_code = OACC_KERNELS;
1656 else if (pragma_id == Pragma_Acc_Parallel)
1657 gnu_loop_stack->last ()->omp_code = OACC_PARALLEL;
1658 else
1659 gcc_unreachable ();
1660
1661 if (!Present (Pragma_Argument_Associations (gnat_node)))
1662 break;
1663
1664 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1665 Present (gnat_temp);
1666 gnat_temp = Next (gnat_temp))
1667 {
1668 Node_Id gnat_expr = Expression (gnat_temp);
1669 tree gnu_clause;
1670 enum omp_clause_code clause_code;
1671 enum gomp_map_kind map_kind;
1672
1673 switch (Chars (gnat_temp))
1674 {
1675 case Name_Async:
1676 gnu_clause = build_omp_clause
1677 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1678 OMP_CLAUSE_ASYNC);
1679 OMP_CLAUSE_ASYNC_EXPR (gnu_clause) =
1680 Acc_gnat_to_gnu (gnat_expr);
1681 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1682 gnu_clauses = gnu_clause;
1683 break;
1684
1685 case Name_Num_Gangs:
1686 gnu_clause = build_omp_clause
1687 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1688 OMP_CLAUSE_NUM_GANGS);
1689 OMP_CLAUSE_NUM_GANGS_EXPR (gnu_clause) =
1690 Acc_gnat_to_gnu (gnat_expr);
1691 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1692 gnu_clauses = gnu_clause;
1693 break;
1694
1695 case Name_Num_Workers:
1696 gnu_clause = build_omp_clause
1697 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1698 OMP_CLAUSE_NUM_WORKERS);
1699 OMP_CLAUSE_NUM_WORKERS_EXPR (gnu_clause) =
1700 Acc_gnat_to_gnu (gnat_expr);
1701 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1702 gnu_clauses = gnu_clause;
1703 break;
1704
1705 case Name_Vector_Length:
1706 gnu_clause = build_omp_clause
1707 (EXPR_LOCATION (gnu_loop_stack->last ()->stmt),
1708 OMP_CLAUSE_VECTOR_LENGTH);
1709 OMP_CLAUSE_VECTOR_LENGTH_EXPR (gnu_clause) =
1710 Acc_gnat_to_gnu (gnat_expr);
1711 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1712 gnu_clauses = gnu_clause;
1713 break;
1714
1715 case Name_Wait:
1716 clause_code = OMP_CLAUSE_WAIT;
1717 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1718 Acc_Var_to_gnu,
1719 &clause_code);
1720 break;
1721
1722 case Name_Acc_If:
1723 gnu_clause = build_omp_clause (EXPR_LOCATION
1724 (gnu_loop_stack->last ()->stmt),
1725 OMP_CLAUSE_IF);
1726 OMP_CLAUSE_IF_MODIFIER (gnu_clause) = ERROR_MARK;
1727 OMP_CLAUSE_IF_EXPR (gnu_clause) = Acc_gnat_to_gnu (gnat_expr);
1728 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1729 gnu_clauses = gnu_clause;
1730 break;
1731
1732 case Name_Copy:
1733 map_kind = GOMP_MAP_FORCE_TOFROM;
1734 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1735 Acc_Data_to_gnu,
1736 &map_kind);
1737 break;
1738
1739 case Name_Copy_In:
1740 map_kind = GOMP_MAP_FORCE_TO;
1741 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1742 Acc_Data_to_gnu,
1743 &map_kind);
1744 break;
1745
1746 case Name_Copy_Out:
1747 map_kind = GOMP_MAP_FORCE_FROM;
1748 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1749 Acc_Data_to_gnu,
1750 &map_kind);
1751 break;
1752
1753 case Name_Present:
1754 map_kind = GOMP_MAP_FORCE_PRESENT;
1755 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1756 Acc_Data_to_gnu,
1757 &map_kind);
1758 break;
1759
1760 case Name_Create:
1761 map_kind = GOMP_MAP_FORCE_ALLOC;
1762 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1763 Acc_Data_to_gnu,
1764 &map_kind);
1765 break;
1766
1767 case Name_Device_Ptr:
1768 map_kind = GOMP_MAP_FORCE_DEVICEPTR;
1769 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1770 Acc_Data_to_gnu,
1771 &map_kind);
1772 break;
1773
1774 case Name_Acc_Private:
1775 clause_code = OMP_CLAUSE_PRIVATE;
1776 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1777 Acc_Var_to_gnu,
1778 &clause_code);
1779 break;
1780
1781 case Name_First_Private:
1782 clause_code = OMP_CLAUSE_FIRSTPRIVATE;
1783 gnu_clauses = Iterate_Acc_Clause_Arg (gnat_expr, gnu_clauses,
1784 Acc_Var_to_gnu,
1785 &clause_code);
1786 break;
1787
1788 case Name_Default:
1789 gnu_clause = build_omp_clause (EXPR_LOCATION
1790 (gnu_loop_stack->last ()->stmt),
1791 OMP_CLAUSE_DEFAULT);
1792 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1793 /* The standard also accepts "present" but this isn't
1794 implemented in GCC yet. */
1795 OMP_CLAUSE_DEFAULT_KIND (gnu_clause) = OMP_CLAUSE_DEFAULT_NONE;
1796 OMP_CLAUSE_CHAIN (gnu_clause) = gnu_clauses;
1797 gnu_clauses = gnu_clause;
1798 break;
1799
1800 case Name_Reduction:
1801 gnu_clauses = Acc_Reduc_to_gnu(gnat_expr);
1802 break;
1803
1804 case Name_Detach:
1805 case Name_Attach:
1806 case Name_Device_Type:
1807 /* Unimplemented by GCC. */
1808 default:
1809 gcc_unreachable ();
1810 }
1811 }
1812 gnu_loop_stack->last ()->omp_construct_clauses = gnu_clauses;
1813 }
1814 break;
1815
1816 case Pragma_Loop_Optimize:
1817 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1818 Present (gnat_temp);
1819 gnat_temp = Next (gnat_temp))
1820 {
1821 tree gnu_loop_stmt = gnu_loop_stack->last ()->stmt;
1822
1823 switch (Chars (Expression (gnat_temp)))
1824 {
1825 case Name_Ivdep:
1826 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
1827 break;
1828
1829 case Name_No_Unroll:
1830 LOOP_STMT_NO_UNROLL (gnu_loop_stmt) = 1;
1831 break;
1832
1833 case Name_Unroll:
1834 LOOP_STMT_UNROLL (gnu_loop_stmt) = 1;
1835 break;
1836
1837 case Name_No_Vector:
1838 LOOP_STMT_NO_VECTOR (gnu_loop_stmt) = 1;
1839 break;
1840
1841 case Name_Vector:
1842 LOOP_STMT_VECTOR (gnu_loop_stmt) = 1;
1843 break;
1844
1845 default:
1846 gcc_unreachable ();
1847 }
1848 }
1849 break;
1850
1851 case Pragma_Optimize:
1852 switch (Chars (Expression
1853 (First (Pragma_Argument_Associations (gnat_node)))))
1854 {
1855 case Name_Off:
1856 if (optimize)
1857 post_error ("must specify -O0?", gnat_node);
1858 break;
1859
1860 case Name_Space:
1861 if (!optimize_size)
1862 post_error ("must specify -Os?", gnat_node);
1863 break;
1864
1865 case Name_Time:
1866 if (!optimize)
1867 post_error ("insufficient -O value?", gnat_node);
1868 break;
1869
1870 default:
1871 gcc_unreachable ();
1872 }
1873 break;
1874
1875 case Pragma_Reviewable:
1876 if (write_symbols == NO_DEBUG)
1877 post_error ("must specify -g?", gnat_node);
1878 break;
1879
1880 case Pragma_Warning_As_Error:
1881 case Pragma_Warnings:
1882 {
1883 Node_Id gnat_expr;
1884 /* Preserve the location of the pragma. */
1885 const location_t location = input_location;
1886 struct cl_option_handlers handlers;
1887 unsigned int option_index;
1888 diagnostic_t kind;
1889 bool imply;
1890
1891 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1892
1893 /* This is the String form: pragma Warning{s|_As_Error}(String). */
1894 if (Nkind (Expression (gnat_temp)) == N_String_Literal)
1895 {
1896 switch (pragma_id)
1897 {
1898 case Pragma_Warning_As_Error:
1899 kind = DK_ERROR;
1900 imply = false;
1901 break;
1902
1903 case Pragma_Warnings:
1904 kind = DK_WARNING;
1905 imply = true;
1906 break;
1907
1908 default:
1909 gcc_unreachable ();
1910 }
1911
1912 gnat_expr = Expression (gnat_temp);
1913 }
1914
1915 /* This is the On/Off form: pragma Warnings (On | Off [,String]). */
1916 else if (Nkind (Expression (gnat_temp)) == N_Identifier)
1917 {
1918 switch (Chars (Expression (gnat_temp)))
1919 {
1920 case Name_Off:
1921 kind = DK_IGNORED;
1922 break;
1923
1924 case Name_On:
1925 kind = DK_WARNING;
1926 break;
1927
1928 default:
1929 gcc_unreachable ();
1930 }
1931
1932 /* Deal with optional pattern (but ignore Reason => "..."). */
1933 if (Present (Next (gnat_temp))
1934 && Chars (Next (gnat_temp)) != Name_Reason)
1935 {
1936 /* pragma Warnings (On | Off, Name) is handled differently. */
1937 if (Nkind (Expression (Next (gnat_temp))) != N_String_Literal)
1938 break;
1939
1940 gnat_expr = Expression (Next (gnat_temp));
1941 }
1942 else
1943 gnat_expr = Empty;
1944
1945 imply = false;
1946 }
1947
1948 else
1949 gcc_unreachable ();
1950
1951 /* This is the same implementation as in the C family of compilers. */
1952 const unsigned int lang_mask = CL_Ada | CL_COMMON;
1953 const char *arg = NULL;
1954 if (Present (gnat_expr))
1955 {
1956 tree gnu_expr = gnat_to_gnu (gnat_expr);
1957 const char *option_string = TREE_STRING_POINTER (gnu_expr);
1958 const int len = TREE_STRING_LENGTH (gnu_expr);
1959 if (len < 3 || option_string[0] != '-' || option_string[1] != 'W')
1960 break;
1961 option_index = find_opt (option_string + 1, lang_mask);
1962 if (option_index == OPT_SPECIAL_unknown)
1963 {
1964 post_error ("?unknown -W switch", gnat_node);
1965 break;
1966 }
1967 else if (!(cl_options[option_index].flags & CL_WARNING))
1968 {
1969 post_error ("?-W switch does not control warning", gnat_node);
1970 break;
1971 }
1972 else if (!(cl_options[option_index].flags & lang_mask))
1973 {
1974 post_error ("?-W switch not valid for Ada", gnat_node);
1975 break;
1976 }
1977 if (cl_options[option_index].flags & CL_JOINED)
1978 arg = option_string + 1 + cl_options[option_index].opt_len;
1979 }
1980 else
1981 option_index = 0;
1982
1983 set_default_handlers (&handlers, NULL);
1984 control_warning_option (option_index, (int) kind, arg, imply, location,
1985 lang_mask, &handlers, &global_options,
1986 &global_options_set, global_dc);
1987 }
1988 break;
1989
1990 default:
1991 break;
1992 }
1993
1994 return gnu_result;
1995 }
1996 \f
1997 /* Check the inline status of nested function FNDECL wrt its parent function.
1998
1999 If a non-inline nested function is referenced from an inline external
2000 function, we cannot honor both requests at the same time without cloning
2001 the nested function in the current unit since it is private to its unit.
2002 We could inline it as well but it's probably better to err on the side
2003 of too little inlining.
2004
2005 This must be done only on nested functions present in the source code
2006 and not on nested functions generated by the compiler, e.g. finalizers,
2007 because they may be not marked inline and we don't want them to block
2008 the inlining of the parent function. */
2009
2010 static void
2011 check_inlining_for_nested_subprog (tree fndecl)
2012 {
2013 if (DECL_IGNORED_P (current_function_decl) || DECL_IGNORED_P (fndecl))
2014 return;
2015
2016 if (DECL_DECLARED_INLINE_P (fndecl))
2017 return;
2018
2019 tree parent_decl = decl_function_context (fndecl);
2020 if (DECL_EXTERNAL (parent_decl) && DECL_DECLARED_INLINE_P (parent_decl))
2021 {
2022 const location_t loc1 = DECL_SOURCE_LOCATION (fndecl);
2023 const location_t loc2 = DECL_SOURCE_LOCATION (parent_decl);
2024
2025 if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (parent_decl)))
2026 {
2027 error_at (loc1, "subprogram %q+F not marked Inline_Always", fndecl);
2028 error_at (loc2, "parent subprogram cannot be inlined");
2029 }
2030 else
2031 {
2032 warning_at (loc1, OPT_Winline, "subprogram %q+F not marked Inline",
2033 fndecl);
2034 warning_at (loc2, OPT_Winline, "parent subprogram cannot be inlined");
2035 }
2036
2037 DECL_DECLARED_INLINE_P (parent_decl) = 0;
2038 DECL_UNINLINABLE (parent_decl) = 1;
2039 }
2040 }
2041 \f
2042 /* Return an expression for the length of TYPE, an integral type, computed in
2043 RESULT_TYPE, another integral type.
2044
2045 We used to compute the length as MAX (hb - lb + 1, 0) which could overflow
2046 when lb == TYPE'First. We now compute it as (hb >= lb) ? hb - lb + 1 : 0
2047 which would only overflow in much rarer cases, for extremely large arrays
2048 we expect never to encounter in practice. Besides, the former computation
2049 required the use of potentially constraining signed arithmetics while the
2050 latter does not. Note that the comparison must be done in the original
2051 base index type in order to avoid any overflow during the conversion. */
2052
2053 static tree
2054 get_type_length (tree type, tree result_type)
2055 {
2056 tree comp_type = get_base_type (result_type);
2057 tree base_type = maybe_character_type (get_base_type (type));
2058 tree lb = convert (base_type, TYPE_MIN_VALUE (type));
2059 tree hb = convert (base_type, TYPE_MAX_VALUE (type));
2060 tree length
2061 = build_binary_op (PLUS_EXPR, comp_type,
2062 build_binary_op (MINUS_EXPR, comp_type,
2063 convert (comp_type, hb),
2064 convert (comp_type, lb)),
2065 build_int_cst (comp_type, 1));
2066 length
2067 = build_cond_expr (result_type,
2068 build_binary_op (GE_EXPR, boolean_type_node, hb, lb),
2069 convert (result_type, length),
2070 build_int_cst (result_type, 0));
2071 return length;
2072 }
2073
2074 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
2075 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to
2076 where we should place the result type. ATTRIBUTE is the attribute ID. */
2077
2078 static tree
2079 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
2080 {
2081 const Node_Id gnat_prefix = Prefix (gnat_node);
2082 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
2083 tree gnu_type = TREE_TYPE (gnu_prefix);
2084 tree gnu_expr, gnu_result_type, gnu_result = error_mark_node;
2085 bool prefix_unused = false;
2086
2087 /* If the input is a NULL_EXPR, make a new one. */
2088 if (TREE_CODE (gnu_prefix) == NULL_EXPR)
2089 {
2090 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2091 *gnu_result_type_p = gnu_result_type;
2092 return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
2093 }
2094
2095 switch (attribute)
2096 {
2097 case Attr_Pos:
2098 case Attr_Val:
2099 /* These are just conversions since representation clauses for
2100 enumeration types are handled in the front-end. */
2101 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2102 if (attribute == Attr_Pos)
2103 gnu_expr = maybe_character_value (gnu_expr);
2104 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2105 gnu_result = convert (gnu_result_type, gnu_expr);
2106 break;
2107
2108 case Attr_Pred:
2109 case Attr_Succ:
2110 /* These just add or subtract the constant 1 since representation
2111 clauses for enumeration types are handled in the front-end. */
2112 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2113 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2114 gnu_type = maybe_character_type (gnu_result_type);
2115 if (TREE_TYPE (gnu_expr) != gnu_type)
2116 gnu_expr = convert (gnu_type, gnu_expr);
2117 gnu_result
2118 = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
2119 gnu_type, gnu_expr, build_int_cst (gnu_type, 1));
2120 break;
2121
2122 case Attr_Address:
2123 case Attr_Unrestricted_Access:
2124 /* Conversions don't change the address of references but can cause
2125 build_unary_op to miss the references below, so strip them off.
2126 On the contrary, if the address-of operation causes a temporary
2127 to be created, then it must be created with the proper type. */
2128 gnu_expr = remove_conversions (gnu_prefix,
2129 !Must_Be_Byte_Aligned (gnat_node));
2130 if (REFERENCE_CLASS_P (gnu_expr))
2131 gnu_prefix = gnu_expr;
2132
2133 /* If we are taking 'Address of an unconstrained object, this is the
2134 pointer to the underlying array. */
2135 if (attribute == Attr_Address)
2136 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
2137
2138 /* If we are building a static dispatch table, we have to honor
2139 TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
2140 with the C++ ABI. We do it in the non-static case as well,
2141 see gnat_to_gnu_entity, case E_Access_Subprogram_Type. */
2142 else if (TARGET_VTABLE_USES_DESCRIPTORS
2143 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
2144 {
2145 tree gnu_field, t;
2146 /* Descriptors can only be built here for top-level functions. */
2147 bool build_descriptor = (global_bindings_p () != 0);
2148 int i;
2149 vec<constructor_elt, va_gc> *gnu_vec = NULL;
2150 constructor_elt *elt;
2151
2152 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2153
2154 /* If we're not going to build the descriptor, we have to retrieve
2155 the one which will be built by the linker (or by the compiler
2156 later if a static chain is requested). */
2157 if (!build_descriptor)
2158 {
2159 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
2160 gnu_result = fold_convert (build_pointer_type (gnu_result_type),
2161 gnu_result);
2162 gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
2163 }
2164
2165 vec_safe_grow (gnu_vec, TARGET_VTABLE_USES_DESCRIPTORS);
2166 elt = (gnu_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
2167 for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
2168 i < TARGET_VTABLE_USES_DESCRIPTORS;
2169 gnu_field = DECL_CHAIN (gnu_field), i++)
2170 {
2171 if (build_descriptor)
2172 {
2173 t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
2174 build_int_cst (NULL_TREE, i));
2175 TREE_CONSTANT (t) = 1;
2176 }
2177 else
2178 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
2179 gnu_field, NULL_TREE);
2180
2181 elt->index = gnu_field;
2182 elt->value = t;
2183 elt--;
2184 }
2185
2186 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
2187 break;
2188 }
2189
2190 /* ... fall through ... */
2191
2192 case Attr_Access:
2193 case Attr_Unchecked_Access:
2194 case Attr_Code_Address:
2195 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2196 gnu_result
2197 = build_unary_op (((attribute == Attr_Address
2198 || attribute == Attr_Unrestricted_Access)
2199 && !Must_Be_Byte_Aligned (gnat_node))
2200 ? ATTR_ADDR_EXPR : ADDR_EXPR,
2201 gnu_result_type, gnu_prefix);
2202
2203 /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
2204 don't try to build a trampoline. */
2205 if (attribute == Attr_Code_Address)
2206 {
2207 gnu_expr = remove_conversions (gnu_result, false);
2208
2209 if (TREE_CODE (gnu_expr) == ADDR_EXPR)
2210 TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
2211
2212 /* On targets for which function symbols denote a descriptor, the
2213 code address is stored within the first slot of the descriptor
2214 so we do an additional dereference:
2215 result = *((result_type *) result)
2216 where we expect result to be of some pointer type already. */
2217 if (targetm.calls.custom_function_descriptors == 0)
2218 gnu_result
2219 = build_unary_op (INDIRECT_REF, NULL_TREE,
2220 convert (build_pointer_type (gnu_result_type),
2221 gnu_result));
2222 }
2223
2224 /* For 'Access, issue an error message if the prefix is a C++ method
2225 since it can use a special calling convention on some platforms,
2226 which cannot be propagated to the access type. */
2227 else if (attribute == Attr_Access
2228 && TREE_CODE (TREE_TYPE (gnu_prefix)) == METHOD_TYPE)
2229 post_error ("access to C++ constructor or member function not allowed",
2230 gnat_node);
2231
2232 /* For other address attributes applied to a nested function,
2233 find an inner ADDR_EXPR and annotate it so that we can issue
2234 a useful warning with -Wtrampolines. */
2235 else if (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_prefix)))
2236 {
2237 gnu_expr = remove_conversions (gnu_result, false);
2238
2239 if (TREE_CODE (gnu_expr) == ADDR_EXPR
2240 && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
2241 {
2242 set_expr_location_from_node (gnu_expr, gnat_node);
2243
2244 /* Also check the inlining status. */
2245 check_inlining_for_nested_subprog (TREE_OPERAND (gnu_expr, 0));
2246
2247 /* Moreover, for 'Access or 'Unrestricted_Access with non-
2248 foreign-compatible representation, mark the ADDR_EXPR so
2249 that we can build a descriptor instead of a trampoline. */
2250 if ((attribute == Attr_Access
2251 || attribute == Attr_Unrestricted_Access)
2252 && targetm.calls.custom_function_descriptors > 0
2253 && Can_Use_Internal_Rep (Etype (gnat_node)))
2254 FUNC_ADDR_BY_DESCRIPTOR (gnu_expr) = 1;
2255
2256 /* Otherwise, we need to check that we are not violating the
2257 No_Implicit_Dynamic_Code restriction. */
2258 else if (targetm.calls.custom_function_descriptors != 0)
2259 Check_Implicit_Dynamic_Code_Allowed (gnat_node);
2260 }
2261 }
2262 break;
2263
2264 case Attr_Pool_Address:
2265 {
2266 tree gnu_ptr = gnu_prefix;
2267 tree gnu_obj_type;
2268
2269 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2270
2271 /* If this is fat pointer, the object must have been allocated with the
2272 template in front of the array. So compute the template address; do
2273 it by converting to a thin pointer. */
2274 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
2275 gnu_ptr
2276 = convert (build_pointer_type
2277 (TYPE_OBJECT_RECORD_TYPE
2278 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
2279 gnu_ptr);
2280
2281 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
2282
2283 /* If this is a thin pointer, the object must have been allocated with
2284 the template in front of the array. So compute the template address
2285 and return it. */
2286 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
2287 gnu_ptr
2288 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
2289 gnu_ptr,
2290 fold_build1 (NEGATE_EXPR, sizetype,
2291 byte_position
2292 (DECL_CHAIN
2293 TYPE_FIELDS ((gnu_obj_type)))));
2294
2295 gnu_result = convert (gnu_result_type, gnu_ptr);
2296 }
2297 break;
2298
2299 case Attr_Size:
2300 case Attr_Object_Size:
2301 case Attr_Value_Size:
2302 case Attr_Max_Size_In_Storage_Elements:
2303 gnu_expr = gnu_prefix;
2304
2305 /* Remove NOPs and conversions between original and packable version
2306 from GNU_EXPR, and conversions from GNU_PREFIX. We use GNU_EXPR
2307 to see if a COMPONENT_REF was involved. */
2308 while (TREE_CODE (gnu_expr) == NOP_EXPR
2309 || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
2310 && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
2311 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
2312 == RECORD_TYPE
2313 && TYPE_NAME (TREE_TYPE (gnu_expr))
2314 == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
2315 gnu_expr = TREE_OPERAND (gnu_expr, 0);
2316
2317 gnu_prefix = remove_conversions (gnu_prefix, true);
2318 prefix_unused = true;
2319 gnu_type = TREE_TYPE (gnu_prefix);
2320
2321 /* Replace an unconstrained array type with the type of the underlying
2322 array, except for 'Max_Size_In_Storage_Elements because we need to
2323 return the (maximum) size requested for an allocator. */
2324 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2325 {
2326 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2327 if (attribute != Attr_Max_Size_In_Storage_Elements)
2328 gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2329 }
2330
2331 /* If we're looking for the size of a field, return the field size. */
2332 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2333 gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
2334
2335 /* Otherwise, if the prefix is an object, or if we are looking for
2336 'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
2337 GCC size of the type. We make an exception for padded objects,
2338 as we do not take into account alignment promotions for the size.
2339 This is in keeping with the object case of gnat_to_gnu_entity. */
2340 else if ((TREE_CODE (gnu_prefix) != TYPE_DECL
2341 && !(TYPE_IS_PADDING_P (gnu_type)
2342 && TREE_CODE (gnu_expr) == COMPONENT_REF
2343 && pad_type_has_rm_size (gnu_type)))
2344 || attribute == Attr_Object_Size
2345 || attribute == Attr_Max_Size_In_Storage_Elements)
2346 {
2347 /* If this is a dereference and we have a special dynamic constrained
2348 subtype on the prefix, use it to compute the size; otherwise, use
2349 the designated subtype. */
2350 if (Nkind (gnat_prefix) == N_Explicit_Dereference)
2351 {
2352 Node_Id gnat_actual_subtype
2353 = Actual_Designated_Subtype (gnat_prefix);
2354 tree gnu_ptr_type
2355 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_prefix)));
2356
2357 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
2358 && Present (gnat_actual_subtype))
2359 {
2360 tree gnu_actual_obj_type
2361 = gnat_to_gnu_type (gnat_actual_subtype);
2362 gnu_type
2363 = build_unc_object_type_from_ptr (gnu_ptr_type,
2364 gnu_actual_obj_type,
2365 get_identifier ("SIZE"),
2366 false);
2367 }
2368 }
2369
2370 gnu_result = TYPE_SIZE (gnu_type);
2371 }
2372
2373 /* Otherwise, the result is the RM size of the type. */
2374 else
2375 gnu_result = rm_size (gnu_type);
2376
2377 /* Deal with a self-referential size by qualifying the size with the
2378 object or returning the maximum size for a type. */
2379 if (TREE_CODE (gnu_prefix) != TYPE_DECL)
2380 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_expr);
2381 else if (CONTAINS_PLACEHOLDER_P (gnu_result))
2382 gnu_result = max_size (gnu_result, true);
2383
2384 /* If the type contains a template, subtract the padded size of the
2385 template, except for 'Max_Size_In_Storage_Elements because we need
2386 to return the (maximum) size requested for an allocator. */
2387 if (TREE_CODE (gnu_type) == RECORD_TYPE
2388 && TYPE_CONTAINS_TEMPLATE_P (gnu_type)
2389 && attribute != Attr_Max_Size_In_Storage_Elements)
2390 gnu_result
2391 = size_binop (MINUS_EXPR, gnu_result,
2392 bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type))));
2393
2394 /* For 'Max_Size_In_Storage_Elements, adjust the unit. */
2395 if (attribute == Attr_Max_Size_In_Storage_Elements)
2396 gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
2397
2398 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2399 break;
2400
2401 case Attr_Alignment:
2402 {
2403 unsigned int align;
2404
2405 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2406 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2407 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2408
2409 gnu_type = TREE_TYPE (gnu_prefix);
2410 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2411 prefix_unused = true;
2412
2413 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2414 align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
2415 else
2416 {
2417 Entity_Id gnat_type = Etype (gnat_prefix);
2418 unsigned int double_align;
2419 bool is_capped_double, align_clause;
2420
2421 /* If the default alignment of "double" or larger scalar types is
2422 specifically capped and there is an alignment clause neither
2423 on the type nor on the prefix itself, return the cap. */
2424 if ((double_align = double_float_alignment) > 0)
2425 is_capped_double
2426 = is_double_float_or_array (gnat_type, &align_clause);
2427 else if ((double_align = double_scalar_alignment) > 0)
2428 is_capped_double
2429 = is_double_scalar_or_array (gnat_type, &align_clause);
2430 else
2431 is_capped_double = align_clause = false;
2432
2433 if (is_capped_double
2434 && Nkind (gnat_prefix) == N_Identifier
2435 && Present (Alignment_Clause (Entity (gnat_prefix))))
2436 align_clause = true;
2437
2438 if (is_capped_double && !align_clause)
2439 align = double_align;
2440 else
2441 align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
2442 }
2443
2444 gnu_result = size_int (align);
2445 }
2446 break;
2447
2448 case Attr_First:
2449 case Attr_Last:
2450 case Attr_Range_Length:
2451 prefix_unused = true;
2452
2453 if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
2454 {
2455 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2456
2457 if (attribute == Attr_First)
2458 gnu_result = TYPE_MIN_VALUE (gnu_type);
2459 else if (attribute == Attr_Last)
2460 gnu_result = TYPE_MAX_VALUE (gnu_type);
2461 else
2462 gnu_result = get_type_length (gnu_type, gnu_result_type);
2463 break;
2464 }
2465
2466 /* ... fall through ... */
2467
2468 case Attr_Length:
2469 {
2470 int Dimension = (Present (Expressions (gnat_node))
2471 ? UI_To_Int (Intval (First (Expressions (gnat_node))))
2472 : 1), i;
2473 struct parm_attr_d *pa = NULL;
2474 Entity_Id gnat_param = Empty;
2475 bool unconstrained_ptr_deref = false;
2476
2477 /* Make sure any implicit dereference gets done. */
2478 gnu_prefix = maybe_implicit_deref (gnu_prefix);
2479 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
2480
2481 /* We treat unconstrained array In parameters specially. We also note
2482 whether we are dereferencing a pointer to unconstrained array. */
2483 if (!Is_Constrained (Etype (gnat_prefix)))
2484 switch (Nkind (gnat_prefix))
2485 {
2486 case N_Identifier:
2487 /* This is the direct case. */
2488 if (Ekind (Entity (gnat_prefix)) == E_In_Parameter)
2489 gnat_param = Entity (gnat_prefix);
2490 break;
2491
2492 case N_Explicit_Dereference:
2493 /* This is the indirect case. Note that we need to be sure that
2494 the access value cannot be null as we'll hoist the load. */
2495 if (Nkind (Prefix (gnat_prefix)) == N_Identifier
2496 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter)
2497 {
2498 if (Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
2499 gnat_param = Entity (Prefix (gnat_prefix));
2500 }
2501 else
2502 unconstrained_ptr_deref = true;
2503 break;
2504
2505 default:
2506 break;
2507 }
2508
2509 /* If the prefix is the view conversion of a constrained array to an
2510 unconstrained form, we retrieve the constrained array because we
2511 might not be able to substitute the PLACEHOLDER_EXPR coming from
2512 the conversion. This can occur with the 'Old attribute applied
2513 to a parameter with an unconstrained type, which gets rewritten
2514 into a constrained local variable very late in the game. */
2515 if (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
2516 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (gnu_prefix)))
2517 && !CONTAINS_PLACEHOLDER_P
2518 (TYPE_SIZE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
2519 gnu_type = TREE_TYPE (TREE_OPERAND (gnu_prefix, 0));
2520 else
2521 gnu_type = TREE_TYPE (gnu_prefix);
2522
2523 prefix_unused = true;
2524 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2525
2526 if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
2527 {
2528 int ndim;
2529 tree gnu_type_temp;
2530
2531 for (ndim = 1, gnu_type_temp = gnu_type;
2532 TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
2533 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
2534 ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
2535 ;
2536
2537 Dimension = ndim + 1 - Dimension;
2538 }
2539
2540 for (i = 1; i < Dimension; i++)
2541 gnu_type = TREE_TYPE (gnu_type);
2542
2543 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2544
2545 /* When not optimizing, look up the slot associated with the parameter
2546 and the dimension in the cache and create a new one on failure.
2547 Don't do this when the actual subtype needs debug info (this happens
2548 with -gnatD): in elaborate_expression_1, we create variables that
2549 hold the bounds, so caching attributes isn't very interesting and
2550 causes dependency issues between these variables and cached
2551 expressions. */
2552 if (!optimize
2553 && Present (gnat_param)
2554 && !(Present (Actual_Subtype (gnat_param))
2555 && Needs_Debug_Info (Actual_Subtype (gnat_param))))
2556 {
2557 FOR_EACH_VEC_SAFE_ELT (f_parm_attr_cache, i, pa)
2558 if (pa->id == gnat_param && pa->dim == Dimension)
2559 break;
2560
2561 if (!pa)
2562 {
2563 pa = ggc_cleared_alloc<parm_attr_d> ();
2564 pa->id = gnat_param;
2565 pa->dim = Dimension;
2566 vec_safe_push (f_parm_attr_cache, pa);
2567 }
2568 }
2569
2570 /* Return the cached expression or build a new one. */
2571 if (attribute == Attr_First)
2572 {
2573 if (pa && pa->first)
2574 {
2575 gnu_result = pa->first;
2576 break;
2577 }
2578
2579 gnu_result
2580 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2581 }
2582
2583 else if (attribute == Attr_Last)
2584 {
2585 if (pa && pa->last)
2586 {
2587 gnu_result = pa->last;
2588 break;
2589 }
2590
2591 gnu_result
2592 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2593 }
2594
2595 else /* attribute == Attr_Range_Length || attribute == Attr_Length */
2596 {
2597 if (pa && pa->length)
2598 {
2599 gnu_result = pa->length;
2600 break;
2601 }
2602
2603 gnu_result
2604 = get_type_length (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)),
2605 gnu_result_type);
2606 }
2607
2608 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2609 handling. Note that these attributes could not have been used on
2610 an unconstrained array type. */
2611 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2612
2613 /* Cache the expression we have just computed. Since we want to do it
2614 at run time, we force the use of a SAVE_EXPR and let the gimplifier
2615 create the temporary in the outermost binding level. We will make
2616 sure in Subprogram_Body_to_gnu that it is evaluated on all possible
2617 paths by forcing its evaluation on entry of the function. */
2618 if (pa)
2619 {
2620 gnu_result
2621 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2622 switch (attribute)
2623 {
2624 case Attr_First:
2625 pa->first = gnu_result;
2626 break;
2627
2628 case Attr_Last:
2629 pa->last = gnu_result;
2630 break;
2631
2632 case Attr_Length:
2633 case Attr_Range_Length:
2634 pa->length = gnu_result;
2635 break;
2636
2637 default:
2638 gcc_unreachable ();
2639 }
2640 }
2641
2642 /* Otherwise, evaluate it each time it is referenced. */
2643 else
2644 switch (attribute)
2645 {
2646 case Attr_First:
2647 case Attr_Last:
2648 /* If we are dereferencing a pointer to unconstrained array, we
2649 need to capture the value because the pointed-to bounds may
2650 subsequently be released. */
2651 if (unconstrained_ptr_deref)
2652 gnu_result
2653 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2654 break;
2655
2656 case Attr_Length:
2657 case Attr_Range_Length:
2658 /* Set the source location onto the predicate of the condition
2659 but not if the expression is cached to avoid messing up the
2660 debug info. */
2661 if (TREE_CODE (gnu_result) == COND_EXPR
2662 && EXPR_P (TREE_OPERAND (gnu_result, 0)))
2663 set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
2664 gnat_node);
2665 break;
2666
2667 default:
2668 gcc_unreachable ();
2669 }
2670
2671 break;
2672 }
2673
2674 case Attr_Bit_Position:
2675 case Attr_Position:
2676 case Attr_First_Bit:
2677 case Attr_Last_Bit:
2678 case Attr_Bit:
2679 {
2680 poly_int64 bitsize;
2681 poly_int64 bitpos;
2682 tree gnu_offset;
2683 tree gnu_field_bitpos;
2684 tree gnu_field_offset;
2685 tree gnu_inner;
2686 machine_mode mode;
2687 int unsignedp, reversep, volatilep;
2688
2689 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2690 gnu_prefix = remove_conversions (gnu_prefix, true);
2691 prefix_unused = true;
2692
2693 /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
2694 the result is 0. Don't allow 'Bit on a bare component, though. */
2695 if (attribute == Attr_Bit
2696 && TREE_CODE (gnu_prefix) != COMPONENT_REF
2697 && TREE_CODE (gnu_prefix) != FIELD_DECL)
2698 {
2699 gnu_result = integer_zero_node;
2700 break;
2701 }
2702
2703 else
2704 gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
2705 || (attribute == Attr_Bit_Position
2706 && TREE_CODE (gnu_prefix) == FIELD_DECL));
2707
2708 get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
2709 &mode, &unsignedp, &reversep, &volatilep);
2710
2711 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2712 {
2713 gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
2714 gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
2715
2716 for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
2717 TREE_CODE (gnu_inner) == COMPONENT_REF
2718 && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
2719 gnu_inner = TREE_OPERAND (gnu_inner, 0))
2720 {
2721 gnu_field_bitpos
2722 = size_binop (PLUS_EXPR, gnu_field_bitpos,
2723 bit_position (TREE_OPERAND (gnu_inner, 1)));
2724 gnu_field_offset
2725 = size_binop (PLUS_EXPR, gnu_field_offset,
2726 byte_position (TREE_OPERAND (gnu_inner, 1)));
2727 }
2728 }
2729 else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
2730 {
2731 gnu_field_bitpos = bit_position (gnu_prefix);
2732 gnu_field_offset = byte_position (gnu_prefix);
2733 }
2734 else
2735 {
2736 gnu_field_bitpos = bitsize_zero_node;
2737 gnu_field_offset = size_zero_node;
2738 }
2739
2740 switch (attribute)
2741 {
2742 case Attr_Position:
2743 gnu_result = gnu_field_offset;
2744 break;
2745
2746 case Attr_First_Bit:
2747 case Attr_Bit:
2748 gnu_result = size_int (num_trailing_bits (bitpos));
2749 break;
2750
2751 case Attr_Last_Bit:
2752 gnu_result = bitsize_int (num_trailing_bits (bitpos));
2753 gnu_result = size_binop (PLUS_EXPR, gnu_result,
2754 TYPE_SIZE (TREE_TYPE (gnu_prefix)));
2755 /* ??? Avoid a large unsigned result that will overflow when
2756 converted to the signed universal_integer. */
2757 if (integer_zerop (gnu_result))
2758 gnu_result = integer_minus_one_node;
2759 else
2760 gnu_result
2761 = size_binop (MINUS_EXPR, gnu_result, bitsize_one_node);
2762 break;
2763
2764 case Attr_Bit_Position:
2765 gnu_result = gnu_field_bitpos;
2766 break;
2767 }
2768
2769 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2770 handling. */
2771 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2772 break;
2773 }
2774
2775 case Attr_Min:
2776 case Attr_Max:
2777 {
2778 tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
2779 tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
2780
2781 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2782
2783 /* The result of {MIN,MAX}_EXPR is unspecified if either operand is
2784 a NaN so we implement the semantics of C99 f{min,max} to make it
2785 predictable in this case: if either operand is a NaN, the other
2786 is returned; if both operands are NaN's, a NaN is returned. */
2787 if (SCALAR_FLOAT_TYPE_P (gnu_result_type)
2788 && !Machine_Overflows_On_Target)
2789 {
2790 const bool lhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_lhs);
2791 const bool rhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_rhs);
2792 tree t = builtin_decl_explicit (BUILT_IN_ISNAN);
2793 tree lhs_is_nan, rhs_is_nan;
2794
2795 /* If the operands have side-effects, they need to be evaluated
2796 only once in spite of the multiple references in the result. */
2797 if (lhs_side_effects_p)
2798 gnu_lhs = gnat_protect_expr (gnu_lhs);
2799 if (rhs_side_effects_p)
2800 gnu_rhs = gnat_protect_expr (gnu_rhs);
2801
2802 lhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2803 build_call_expr (t, 1, gnu_lhs),
2804 integer_zero_node);
2805
2806 rhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2807 build_call_expr (t, 1, gnu_rhs),
2808 integer_zero_node);
2809
2810 gnu_result = build_binary_op (attribute == Attr_Min
2811 ? MIN_EXPR : MAX_EXPR,
2812 gnu_result_type, gnu_lhs, gnu_rhs);
2813 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2814 rhs_is_nan, gnu_lhs, gnu_result);
2815 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2816 lhs_is_nan, gnu_rhs, gnu_result);
2817
2818 /* If the operands have side-effects, they need to be evaluated
2819 before doing the tests above since the place they otherwise
2820 would end up being evaluated at run time could be wrong. */
2821 if (lhs_side_effects_p)
2822 gnu_result
2823 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_lhs, gnu_result);
2824
2825 if (rhs_side_effects_p)
2826 gnu_result
2827 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_rhs, gnu_result);
2828 }
2829 else
2830 gnu_result = build_binary_op (attribute == Attr_Min
2831 ? MIN_EXPR : MAX_EXPR,
2832 gnu_result_type, gnu_lhs, gnu_rhs);
2833 }
2834 break;
2835
2836 case Attr_Passed_By_Reference:
2837 gnu_result = size_int (default_pass_by_ref (gnu_type)
2838 || must_pass_by_ref (gnu_type));
2839 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2840 break;
2841
2842 case Attr_Component_Size:
2843 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2844 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2845 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2846
2847 gnu_prefix = maybe_implicit_deref (gnu_prefix);
2848 gnu_type = TREE_TYPE (gnu_prefix);
2849
2850 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2851 gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
2852
2853 while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
2854 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
2855 gnu_type = TREE_TYPE (gnu_type);
2856
2857 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2858
2859 /* Note this size cannot be self-referential. */
2860 gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
2861 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2862 prefix_unused = true;
2863 break;
2864
2865 case Attr_Descriptor_Size:
2866 gnu_type = TREE_TYPE (gnu_prefix);
2867 gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
2868
2869 /* Return the padded size of the template in the object record type. */
2870 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2871 gnu_result = bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2872 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2873 prefix_unused = true;
2874 break;
2875
2876 case Attr_Null_Parameter:
2877 /* This is just a zero cast to the pointer type for our prefix and
2878 dereferenced. */
2879 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2880 gnu_result
2881 = build_unary_op (INDIRECT_REF, NULL_TREE,
2882 convert (build_pointer_type (gnu_result_type),
2883 integer_zero_node));
2884 TREE_PRIVATE (gnu_result) = 1;
2885 break;
2886
2887 case Attr_Mechanism_Code:
2888 {
2889 Entity_Id gnat_obj = Entity (gnat_prefix);
2890 int code;
2891
2892 prefix_unused = true;
2893 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2894 if (Present (Expressions (gnat_node)))
2895 {
2896 int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
2897
2898 for (gnat_obj = First_Formal (gnat_obj); i > 1;
2899 i--, gnat_obj = Next_Formal (gnat_obj))
2900 ;
2901 }
2902
2903 code = Mechanism (gnat_obj);
2904 if (code == Default)
2905 code = ((present_gnu_tree (gnat_obj)
2906 && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
2907 || ((TREE_CODE (get_gnu_tree (gnat_obj))
2908 == PARM_DECL)
2909 && (DECL_BY_COMPONENT_PTR_P
2910 (get_gnu_tree (gnat_obj))))))
2911 ? By_Reference : By_Copy);
2912 gnu_result = convert (gnu_result_type, size_int (- code));
2913 }
2914 break;
2915
2916 case Attr_Model:
2917 /* We treat Model as identical to Machine. This is true for at least
2918 IEEE and some other nice floating-point systems. */
2919
2920 /* ... fall through ... */
2921
2922 case Attr_Machine:
2923 /* The trick is to force the compiler to store the result in memory so
2924 that we do not have extra precision used. But do this only when this
2925 is necessary, i.e. if FP_ARITH_MAY_WIDEN is true and the precision of
2926 the type is lower than that of the longest floating-point type. */
2927 prefix_unused = true;
2928 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2929 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2930 gnu_result = convert (gnu_result_type, gnu_expr);
2931
2932 if (TREE_CODE (gnu_result) != REAL_CST
2933 && fp_arith_may_widen
2934 && TYPE_PRECISION (gnu_result_type)
2935 < TYPE_PRECISION (longest_float_type_node))
2936 {
2937 tree rec_type = make_node (RECORD_TYPE);
2938 tree field
2939 = create_field_decl (get_identifier ("OBJ"), gnu_result_type,
2940 rec_type, NULL_TREE, NULL_TREE, 0, 0);
2941 tree rec_val, asm_expr;
2942
2943 finish_record_type (rec_type, field, 0, false);
2944
2945 rec_val = build_constructor_single (rec_type, field, gnu_result);
2946 rec_val = build1 (SAVE_EXPR, rec_type, rec_val);
2947
2948 asm_expr
2949 = build5 (ASM_EXPR, void_type_node,
2950 build_string (0, ""),
2951 tree_cons (build_tree_list (NULL_TREE,
2952 build_string (2, "=m")),
2953 rec_val, NULL_TREE),
2954 tree_cons (build_tree_list (NULL_TREE,
2955 build_string (1, "m")),
2956 rec_val, NULL_TREE),
2957 NULL_TREE, NULL_TREE);
2958 ASM_VOLATILE_P (asm_expr) = 1;
2959
2960 gnu_result
2961 = build_compound_expr (gnu_result_type, asm_expr,
2962 build_component_ref (rec_val, field,
2963 false));
2964 }
2965 break;
2966
2967 case Attr_Deref:
2968 prefix_unused = true;
2969 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2970 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2971 /* This can be a random address so build an alias-all pointer type. */
2972 gnu_expr
2973 = convert (build_pointer_type_for_mode (gnu_result_type, ptr_mode,
2974 true),
2975 gnu_expr);
2976 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_expr);
2977 break;
2978
2979 default:
2980 /* This abort means that we have an unimplemented attribute. */
2981 gcc_unreachable ();
2982 }
2983
2984 /* If this is an attribute where the prefix was unused, force a use of it if
2985 it has a side-effect. But don't do it if the prefix is just an entity
2986 name. However, if an access check is needed, we must do it. See second
2987 example in AARM 11.6(5.e). */
2988 if (prefix_unused
2989 && TREE_SIDE_EFFECTS (gnu_prefix)
2990 && !Is_Entity_Name (gnat_prefix))
2991 gnu_result
2992 = build_compound_expr (TREE_TYPE (gnu_result), gnu_prefix, gnu_result);
2993
2994 *gnu_result_type_p = gnu_result_type;
2995 return gnu_result;
2996 }
2997 \f
2998 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
2999 to a GCC tree, which is returned. */
3000
3001 static tree
3002 Case_Statement_to_gnu (Node_Id gnat_node)
3003 {
3004 tree gnu_result, gnu_expr, gnu_type, gnu_label;
3005 Node_Id gnat_when;
3006 location_t end_locus;
3007 bool may_fallthru = false;
3008
3009 gnu_expr = gnat_to_gnu (Expression (gnat_node));
3010 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
3011 gnu_expr = maybe_character_value (gnu_expr);
3012 gnu_type = TREE_TYPE (gnu_expr);
3013
3014 /* We build a SWITCH_EXPR that contains the code with interspersed
3015 CASE_LABEL_EXPRs for each label. */
3016 if (!Sloc_to_locus (End_Location (gnat_node), &end_locus))
3017 end_locus = input_location;
3018 gnu_label = create_artificial_label (end_locus);
3019 start_stmt_group ();
3020
3021 for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
3022 Present (gnat_when);
3023 gnat_when = Next_Non_Pragma (gnat_when))
3024 {
3025 bool choices_added_p = false;
3026 Node_Id gnat_choice;
3027
3028 /* First compile all the different case choices for the current WHEN
3029 alternative. */
3030 for (gnat_choice = First (Discrete_Choices (gnat_when));
3031 Present (gnat_choice);
3032 gnat_choice = Next (gnat_choice))
3033 {
3034 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
3035 tree label = create_artificial_label (input_location);
3036
3037 switch (Nkind (gnat_choice))
3038 {
3039 case N_Range:
3040 gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
3041 gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
3042 break;
3043
3044 case N_Subtype_Indication:
3045 gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
3046 (Constraint (gnat_choice))));
3047 gnu_high = gnat_to_gnu (High_Bound (Range_Expression
3048 (Constraint (gnat_choice))));
3049 break;
3050
3051 case N_Identifier:
3052 case N_Expanded_Name:
3053 /* This represents either a subtype range or a static value of
3054 some kind; Ekind says which. */
3055 if (Is_Type (Entity (gnat_choice)))
3056 {
3057 tree gnu_type = get_unpadded_type (Entity (gnat_choice));
3058
3059 gnu_low = TYPE_MIN_VALUE (gnu_type);
3060 gnu_high = TYPE_MAX_VALUE (gnu_type);
3061 break;
3062 }
3063
3064 /* ... fall through ... */
3065
3066 case N_Character_Literal:
3067 case N_Integer_Literal:
3068 gnu_low = gnat_to_gnu (gnat_choice);
3069 break;
3070
3071 case N_Others_Choice:
3072 break;
3073
3074 default:
3075 gcc_unreachable ();
3076 }
3077
3078 /* Everything should be folded into constants at this point. */
3079 gcc_assert (!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST);
3080 gcc_assert (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST);
3081
3082 if (gnu_low && TREE_TYPE (gnu_low) != gnu_type)
3083 gnu_low = convert (gnu_type, gnu_low);
3084 if (gnu_high && TREE_TYPE (gnu_high) != gnu_type)
3085 gnu_high = convert (gnu_type, gnu_high);
3086
3087 add_stmt_with_node (build_case_label (gnu_low, gnu_high, label),
3088 gnat_choice);
3089 choices_added_p = true;
3090 }
3091
3092 /* This construct doesn't define a scope so we shouldn't push a binding
3093 level around the statement list. Except that we have always done so
3094 historically and this makes it possible to reduce stack usage. As a
3095 compromise, we keep doing it for case statements, for which this has
3096 never been problematic, but not for case expressions in Ada 2012. */
3097 if (choices_added_p)
3098 {
3099 const bool is_case_expression
3100 = (Nkind (Parent (gnat_node)) == N_Expression_With_Actions);
3101 tree group
3102 = build_stmt_group (Statements (gnat_when), !is_case_expression);
3103 bool group_may_fallthru = block_may_fallthru (group);
3104 add_stmt (group);
3105 if (group_may_fallthru)
3106 {
3107 tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
3108 SET_EXPR_LOCATION (stmt, end_locus);
3109 add_stmt (stmt);
3110 may_fallthru = true;
3111 }
3112 }
3113 }
3114
3115 /* Now emit a definition of the label the cases branch to, if any. */
3116 if (may_fallthru)
3117 add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
3118 gnu_result = build2 (SWITCH_EXPR, gnu_type, gnu_expr, end_stmt_group ());
3119
3120 return gnu_result;
3121 }
3122 \f
3123 /* Return true if we are in the body of a loop. */
3124
3125 static inline bool
3126 inside_loop_p (void)
3127 {
3128 return !vec_safe_is_empty (gnu_loop_stack);
3129 }
3130
3131 /* Find out whether EXPR is a simple additive expression based on the iteration
3132 variable of some enclosing loop in the current function. If so, return the
3133 loop and set *DISP to the displacement and *NEG_P to true if this is for a
3134 subtraction; otherwise, return NULL. */
3135
3136 static struct loop_info_d *
3137 find_loop_for (tree expr, tree *disp, bool *neg_p)
3138 {
3139 tree var, add, cst;
3140 bool minus_p;
3141 struct loop_info_d *iter = NULL;
3142 unsigned int i;
3143
3144 if (is_simple_additive_expression (expr, &add, &cst, &minus_p))
3145 {
3146 var = add;
3147 if (disp)
3148 *disp = cst;
3149 if (neg_p)
3150 *neg_p = minus_p;
3151 }
3152 else
3153 {
3154 var = expr;
3155 if (disp)
3156 *disp = NULL_TREE;
3157 if (neg_p)
3158 *neg_p = false;
3159 }
3160
3161 var = remove_conversions (var, false);
3162
3163 if (TREE_CODE (var) != VAR_DECL)
3164 return NULL;
3165
3166 if (decl_function_context (var) != current_function_decl)
3167 return NULL;
3168
3169 gcc_assert (vec_safe_length (gnu_loop_stack) > 0);
3170
3171 FOR_EACH_VEC_ELT_REVERSE (*gnu_loop_stack, i, iter)
3172 if (var == iter->loop_var)
3173 break;
3174
3175 return iter;
3176 }
3177
3178 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
3179 false, or the maximum value if MAX is true, of TYPE. */
3180
3181 static bool
3182 can_equal_min_or_max_val_p (tree val, tree type, bool max)
3183 {
3184 tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
3185
3186 if (TREE_CODE (min_or_max_val) != INTEGER_CST)
3187 return true;
3188
3189 if (TREE_CODE (val) == NOP_EXPR)
3190 val = (max
3191 ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
3192 : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
3193
3194 if (TREE_CODE (val) != INTEGER_CST)
3195 return true;
3196
3197 if (max)
3198 return tree_int_cst_lt (val, min_or_max_val) == 0;
3199 else
3200 return tree_int_cst_lt (min_or_max_val, val) == 0;
3201 }
3202
3203 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
3204 If REVERSE is true, minimum value is taken as maximum value. */
3205
3206 static inline bool
3207 can_equal_min_val_p (tree val, tree type, bool reverse)
3208 {
3209 return can_equal_min_or_max_val_p (val, type, reverse);
3210 }
3211
3212 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
3213 If REVERSE is true, maximum value is taken as minimum value. */
3214
3215 static inline bool
3216 can_equal_max_val_p (tree val, tree type, bool reverse)
3217 {
3218 return can_equal_min_or_max_val_p (val, type, !reverse);
3219 }
3220
3221 /* Return true if VAL1 can be lower than VAL2. */
3222
3223 static bool
3224 can_be_lower_p (tree val1, tree val2)
3225 {
3226 if (TREE_CODE (val1) == NOP_EXPR)
3227 {
3228 tree type = TREE_TYPE (TREE_OPERAND (val1, 0));
3229 if (can_be_lower_p (TYPE_MAX_VALUE (type), TYPE_MIN_VALUE (type)))
3230 return true;
3231
3232 val1 = TYPE_MIN_VALUE (type);
3233 }
3234
3235 if (TREE_CODE (val1) != INTEGER_CST)
3236 return true;
3237
3238 if (TREE_CODE (val2) == NOP_EXPR)
3239 {
3240 tree type = TREE_TYPE (TREE_OPERAND (val2, 0));
3241 if (can_be_lower_p (TYPE_MAX_VALUE (type), TYPE_MIN_VALUE (type)))
3242 return true;
3243
3244 val2 = TYPE_MAX_VALUE (type);
3245 }
3246
3247 if (TREE_CODE (val2) != INTEGER_CST)
3248 return true;
3249
3250 return tree_int_cst_lt (val1, val2);
3251 }
3252
3253 /* Replace EXPR1 and EXPR2 by invariant expressions if possible. Return
3254 true if both expressions have been replaced and false otherwise. */
3255
3256 static bool
3257 make_invariant (tree *expr1, tree *expr2)
3258 {
3259 tree inv_expr1 = gnat_invariant_expr (*expr1);
3260 tree inv_expr2 = gnat_invariant_expr (*expr2);
3261
3262 if (inv_expr1)
3263 *expr1 = inv_expr1;
3264
3265 if (inv_expr2)
3266 *expr2 = inv_expr2;
3267
3268 return inv_expr1 && inv_expr2;
3269 }
3270
3271 /* Helper function for walk_tree, used by independent_iterations_p below. */
3272
3273 static tree
3274 scan_rhs_r (tree *tp, int *walk_subtrees, void *data)
3275 {
3276 bitmap *params = (bitmap *)data;
3277 tree t = *tp;
3278
3279 /* No need to walk into types or decls. */
3280 if (IS_TYPE_OR_DECL_P (t))
3281 *walk_subtrees = 0;
3282
3283 if (TREE_CODE (t) == PARM_DECL && bitmap_bit_p (*params, DECL_UID (t)))
3284 return t;
3285
3286 return NULL_TREE;
3287 }
3288
3289 /* Return true if STMT_LIST generates independent iterations in a loop. */
3290
3291 static bool
3292 independent_iterations_p (tree stmt_list)
3293 {
3294 tree_stmt_iterator tsi;
3295 bitmap params = BITMAP_GGC_ALLOC();
3296 auto_vec<tree> rhs;
3297 tree iter;
3298 int i;
3299
3300 if (TREE_CODE (stmt_list) == BIND_EXPR)
3301 stmt_list = BIND_EXPR_BODY (stmt_list);
3302
3303 /* Scan the list and return false on anything that is not either a check
3304 or an assignment to a parameter with restricted aliasing. */
3305 for (tsi = tsi_start (stmt_list); !tsi_end_p (tsi); tsi_next (&tsi))
3306 {
3307 tree stmt = tsi_stmt (tsi);
3308
3309 switch (TREE_CODE (stmt))
3310 {
3311 case COND_EXPR:
3312 {
3313 if (COND_EXPR_ELSE (stmt))
3314 return false;
3315 if (TREE_CODE (COND_EXPR_THEN (stmt)) != CALL_EXPR)
3316 return false;
3317 tree func = get_callee_fndecl (COND_EXPR_THEN (stmt));
3318 if (!(func && TREE_THIS_VOLATILE (func)))
3319 return false;
3320 break;
3321 }
3322
3323 case MODIFY_EXPR:
3324 {
3325 tree lhs = TREE_OPERAND (stmt, 0);
3326 while (handled_component_p (lhs))
3327 lhs = TREE_OPERAND (lhs, 0);
3328 if (TREE_CODE (lhs) != INDIRECT_REF)
3329 return false;
3330 lhs = TREE_OPERAND (lhs, 0);
3331 if (!(TREE_CODE (lhs) == PARM_DECL
3332 && DECL_RESTRICTED_ALIASING_P (lhs)))
3333 return false;
3334 bitmap_set_bit (params, DECL_UID (lhs));
3335 rhs.safe_push (TREE_OPERAND (stmt, 1));
3336 break;
3337 }
3338
3339 default:
3340 return false;
3341 }
3342 }
3343
3344 /* At this point we know that the list contains only statements that will
3345 modify parameters with restricted aliasing. Check that the statements
3346 don't at the time read from these parameters. */
3347 FOR_EACH_VEC_ELT (rhs, i, iter)
3348 if (walk_tree_without_duplicates (&iter, scan_rhs_r, &params))
3349 return false;
3350
3351 return true;
3352 }
3353
3354 /* Helper for Loop_Statement_to_gnu to translate the body of a loop,
3355 designated by GNAT_LOOP, to which an Acc_Loop pragma applies. The pragma
3356 arguments might instruct us to collapse a nest of loops, where computation
3357 statements are expected only within the innermost loop, as in:
3358
3359 for I in 1 .. 5 loop
3360 pragma Acc_Parallel;
3361 pragma Acc_Loop(Collapse => 3);
3362 for J in 1 .. 8 loop
3363 for K in 1 .. 4 loop
3364 X (I, J, K) := Y (I, J, K) + 2;
3365 end loop;
3366 end loop;
3367 end loop;
3368
3369 We expect the top of gnu_loop_stack to hold a pointer to the loop info
3370 setup for the translation of GNAT_LOOP, which holds a pointer to the
3371 initial gnu loop stmt node. We return the new gnu loop statement to
3372 use. */
3373
3374 static tree
3375 Acc_Loop_to_gnu (Node_Id gnat_loop)
3376 {
3377 const struct loop_info_d * const gnu_loop_info = gnu_loop_stack->last ();
3378 tree gnu_loop_stmt = gnu_loop_info->stmt;
3379
3380 tree acc_loop = make_node (OACC_LOOP);
3381 tree acc_bind_expr = NULL_TREE;
3382 Node_Id cur_loop = gnat_loop;
3383 int collapse_count = 1;
3384 tree initv;
3385 tree condv;
3386 tree incrv;
3387
3388 /* Parse the pragmas, adding clauses to the current gnu_loop_stack through
3389 side effects. */
3390 for (Node_Id tmp = First (Statements (gnat_loop));
3391 Present (tmp) && Nkind (tmp) == N_Pragma;
3392 tmp = Next (tmp))
3393 Pragma_to_gnu(tmp);
3394
3395 /* Find the number of loops that should be collapsed. */
3396 for (tree tmp = gnu_loop_stack->last ()->omp_loop_clauses; tmp ;
3397 tmp = OMP_CLAUSE_CHAIN (tmp))
3398 if (OMP_CLAUSE_CODE (tmp) == OMP_CLAUSE_COLLAPSE)
3399 collapse_count = tree_to_shwi (OMP_CLAUSE_COLLAPSE_EXPR (tmp));
3400 else if (OMP_CLAUSE_CODE (tmp) == OMP_CLAUSE_TILE)
3401 collapse_count = list_length (OMP_CLAUSE_TILE_LIST (tmp));
3402
3403 initv = make_tree_vec (collapse_count);
3404 condv = make_tree_vec (collapse_count);
3405 incrv = make_tree_vec (collapse_count);
3406
3407 start_stmt_group ();
3408 gnat_pushlevel ();
3409
3410 /* For each nested loop that should be collapsed ... */
3411 for (int count = 0; count < collapse_count; ++count)
3412 {
3413 Node_Id lps =
3414 Loop_Parameter_Specification (Iteration_Scheme (cur_loop));
3415 tree low =
3416 Acc_gnat_to_gnu (Low_Bound (Discrete_Subtype_Definition (lps)));
3417 tree high =
3418 Acc_gnat_to_gnu (High_Bound (Discrete_Subtype_Definition (lps)));
3419 tree variable =
3420 gnat_to_gnu_entity (Defining_Identifier (lps), NULL_TREE, true);
3421
3422 /* Build the initial value of the variable of the invariant. */
3423 TREE_VEC_ELT (initv, count) = build2 (MODIFY_EXPR,
3424 TREE_TYPE (variable),
3425 variable,
3426 low);
3427 add_stmt (TREE_VEC_ELT (initv, count));
3428
3429 /* Build the invariant of the loop. */
3430 TREE_VEC_ELT (condv, count) = build2 (LE_EXPR,
3431 boolean_type_node,
3432 variable,
3433 high);
3434
3435 /* Build the incrementation expression of the loop. */
3436 TREE_VEC_ELT (incrv, count) =
3437 build2 (MODIFY_EXPR,
3438 TREE_TYPE (variable),
3439 variable,
3440 build2 (PLUS_EXPR,
3441 TREE_TYPE (variable),
3442 variable,
3443 build_int_cst (TREE_TYPE (variable), 1)));
3444
3445 /* Don't process the innermost loop because its statements belong to
3446 another statement group. */
3447 if (count < collapse_count - 1)
3448 /* Process the current loop's body. */
3449 for (Node_Id stmt = First (Statements (cur_loop));
3450 Present (stmt); stmt = Next (stmt))
3451 {
3452 /* If we are processsing the outermost loop, it is ok for it to
3453 contain pragmas. */
3454 if (Nkind (stmt) == N_Pragma && count == 0)
3455 ;
3456 /* The frontend might have inserted a N_Object_Declaration in the
3457 loop's body to declare the iteration variable of the next loop.
3458 It will need to be hoisted before the collapsed loops. */
3459 else if (Nkind (stmt) == N_Object_Declaration)
3460 Acc_gnat_to_gnu (stmt);
3461 else if (Nkind (stmt) == N_Loop_Statement)
3462 cur_loop = stmt;
3463 /* Every other kind of statement is prohibited in collapsed
3464 loops. */
3465 else if (count < collapse_count - 1)
3466 gcc_unreachable();
3467 }
3468 }
3469 gnat_poplevel ();
3470 acc_bind_expr = end_stmt_group ();
3471
3472 /* Parse the innermost loop. */
3473 start_stmt_group();
3474 for (Node_Id stmt = First (Statements (cur_loop));
3475 Present (stmt);
3476 stmt = Next (stmt))
3477 {
3478 /* When the innermost loop is the only loop, do not parse the pragmas
3479 again. */
3480 if (Nkind (stmt) == N_Pragma && collapse_count == 1)
3481 continue;
3482 add_stmt (Acc_gnat_to_gnu (stmt));
3483 }
3484
3485 TREE_TYPE (acc_loop) = void_type_node;
3486 OMP_FOR_INIT (acc_loop) = initv;
3487 OMP_FOR_COND (acc_loop) = condv;
3488 OMP_FOR_INCR (acc_loop) = incrv;
3489 OMP_FOR_BODY (acc_loop) = end_stmt_group ();
3490 OMP_FOR_PRE_BODY (acc_loop) = NULL;
3491 OMP_FOR_ORIG_DECLS (acc_loop) = NULL;
3492 OMP_FOR_CLAUSES (acc_loop) = gnu_loop_stack->last ()->omp_loop_clauses;
3493
3494 BIND_EXPR_BODY (acc_bind_expr) = acc_loop;
3495
3496 return gnu_loop_stmt;
3497 }
3498
3499 /* Helper for Loop_Statement_to_gnu, to translate the body of a loop not
3500 subject to any sort of parallelization directive or restriction, designated
3501 by GNAT_NODE.
3502
3503 We expect the top of gnu_loop_stack to hold a pointer to the loop info
3504 setup for the translation, which holds a pointer to the initial gnu loop
3505 stmt node. We return the new gnu loop statement to use.
3506
3507 We might also set *GNU_COND_EXPR_P to request a variant of the translation
3508 scheme in Loop_Statement_to_gnu. */
3509
3510 static tree
3511 Regular_Loop_to_gnu (Node_Id gnat_node, tree *gnu_cond_expr_p)
3512 {
3513 const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
3514 struct loop_info_d *const gnu_loop_info = gnu_loop_stack->last ();
3515 tree gnu_loop_stmt = gnu_loop_info->stmt;
3516 tree gnu_loop_label = LOOP_STMT_LABEL (gnu_loop_stmt);
3517 tree gnu_cond_expr = *gnu_cond_expr_p;
3518 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
3519
3520 /* Set the condition under which the loop must keep going. If we have an
3521 explicit condition, use it to set the location information throughout
3522 the translation of the loop statement to avoid having multiple SLOCs.
3523
3524 For the case "LOOP .... END LOOP;" the condition is always true. */
3525 if (No (gnat_iter_scheme))
3526 ;
3527
3528 /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate. */
3529 else if (Present (Condition (gnat_iter_scheme)))
3530 {
3531 LOOP_STMT_COND (gnu_loop_stmt)
3532 = gnat_to_gnu (Condition (gnat_iter_scheme));
3533
3534 set_expr_location_from_node (gnu_loop_stmt, gnat_iter_scheme);
3535 }
3536
3537 /* Otherwise we have an iteration scheme and the condition is given by the
3538 bounds of the subtype of the iteration variable. */
3539 else
3540 {
3541 Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
3542 Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
3543 Entity_Id gnat_type = Etype (gnat_loop_var);
3544 tree gnu_type = get_unpadded_type (gnat_type);
3545 tree gnu_base_type = maybe_character_type (get_base_type (gnu_type));
3546 tree gnu_one_node = build_int_cst (gnu_base_type, 1);
3547 tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
3548 enum tree_code update_code, test_code, shift_code;
3549 bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
3550
3551 gnu_low = convert (gnu_base_type, TYPE_MIN_VALUE (gnu_type));
3552 gnu_high = convert (gnu_base_type, TYPE_MAX_VALUE (gnu_type));
3553
3554 /* We must disable modulo reduction for the iteration variable, if any,
3555 in order for the loop comparison to be effective. */
3556 if (reverse)
3557 {
3558 gnu_first = gnu_high;
3559 gnu_last = gnu_low;
3560 update_code = MINUS_NOMOD_EXPR;
3561 test_code = GE_EXPR;
3562 shift_code = PLUS_NOMOD_EXPR;
3563 }
3564 else
3565 {
3566 gnu_first = gnu_low;
3567 gnu_last = gnu_high;
3568 update_code = PLUS_NOMOD_EXPR;
3569 test_code = LE_EXPR;
3570 shift_code = MINUS_NOMOD_EXPR;
3571 }
3572
3573 /* We use two different strategies to translate the loop, depending on
3574 whether optimization is enabled.
3575
3576 If it is, we generate the canonical loop form expected by the loop
3577 optimizer and the loop vectorizer, which is the do-while form:
3578
3579 ENTRY_COND
3580 loop:
3581 TOP_UPDATE
3582 BODY
3583 BOTTOM_COND
3584 GOTO loop
3585
3586 This avoids an implicit dependency on loop header copying and makes
3587 it possible to turn BOTTOM_COND into an inequality test.
3588
3589 If optimization is disabled, loop header copying doesn't come into
3590 play and we try to generate the loop form with the fewer conditional
3591 branches. First, the default form, which is:
3592
3593 loop:
3594 TOP_COND
3595 BODY
3596 BOTTOM_UPDATE
3597 GOTO loop
3598
3599 It should catch most loops with constant ending point. Then, if we
3600 cannot, we try to generate the shifted form:
3601
3602 loop:
3603 TOP_COND
3604 TOP_UPDATE
3605 BODY
3606 GOTO loop
3607
3608 which should catch loops with constant starting point. Otherwise, if
3609 we cannot, we generate the fallback form:
3610
3611 ENTRY_COND
3612 loop:
3613 BODY
3614 BOTTOM_COND
3615 BOTTOM_UPDATE
3616 GOTO loop
3617
3618 which works in all cases. */
3619
3620 if (optimize)
3621 {
3622 /* We can use the do-while form directly if GNU_FIRST-1 doesn't
3623 overflow. */
3624 if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
3625 ;
3626
3627 /* Otherwise, use the do-while form with the help of a special
3628 induction variable in the unsigned version of the base type
3629 or the unsigned version of the size type, whichever is the
3630 largest, in order to have wrap-around arithmetics for it. */
3631 else
3632 {
3633 if (TYPE_PRECISION (gnu_base_type)
3634 > TYPE_PRECISION (size_type_node))
3635 gnu_base_type
3636 = gnat_type_for_size (TYPE_PRECISION (gnu_base_type), 1);
3637 else
3638 gnu_base_type = size_type_node;
3639
3640 gnu_first = convert (gnu_base_type, gnu_first);
3641 gnu_last = convert (gnu_base_type, gnu_last);
3642 gnu_one_node = build_int_cst (gnu_base_type, 1);
3643 use_iv = true;
3644 }
3645
3646 gnu_first
3647 = build_binary_op (shift_code, gnu_base_type, gnu_first,
3648 gnu_one_node);
3649 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
3650 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
3651 }
3652 else
3653 {
3654 /* We can use the default form if GNU_LAST+1 doesn't overflow. */
3655 if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
3656 ;
3657
3658 /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
3659 GNU_LAST-1 does. */
3660 else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
3661 && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
3662 {
3663 gnu_first
3664 = build_binary_op (shift_code, gnu_base_type, gnu_first,
3665 gnu_one_node);
3666 gnu_last
3667 = build_binary_op (shift_code, gnu_base_type, gnu_last,
3668 gnu_one_node);
3669 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
3670 }
3671
3672 /* Otherwise, use the fallback form. */
3673 else
3674 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
3675 }
3676
3677 /* If we use the BOTTOM_COND, we can turn the test into an inequality
3678 test but we may have to add ENTRY_COND to protect the empty loop. */
3679 if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
3680 {
3681 test_code = NE_EXPR;
3682 if (can_be_lower_p (gnu_high, gnu_low))
3683 {
3684 gnu_cond_expr
3685 = build3 (COND_EXPR, void_type_node,
3686 build_binary_op (LE_EXPR, boolean_type_node,
3687 gnu_low, gnu_high),
3688 NULL_TREE, alloc_stmt_list ());
3689 set_expr_location_from_node (gnu_cond_expr, gnat_iter_scheme);
3690 }
3691 }
3692
3693 /* Open a new nesting level that will surround the loop to declare the
3694 iteration variable. */
3695 start_stmt_group ();
3696 gnat_pushlevel ();
3697
3698 /* If we use the special induction variable, create it and set it to
3699 its initial value. Morever, the regular iteration variable cannot
3700 itself be initialized, lest the initial value wrapped around. */
3701 if (use_iv)
3702 {
3703 gnu_loop_iv
3704 = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
3705 add_stmt (gnu_stmt);
3706 gnu_first = NULL_TREE;
3707 }
3708 else
3709 gnu_loop_iv = NULL_TREE;
3710
3711 /* Declare the iteration variable and set it to its initial value. */
3712 gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, true);
3713 if (DECL_BY_REF_P (gnu_loop_var))
3714 gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
3715 else if (use_iv)
3716 {
3717 gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
3718 SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
3719 }
3720 gnu_loop_info->loop_var = gnu_loop_var;
3721 gnu_loop_info->low_bound = gnu_low;
3722 gnu_loop_info->high_bound = gnu_high;
3723
3724 /* Do all the arithmetics in the base type. */
3725 gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
3726
3727 /* Set either the top or bottom exit condition. */
3728 if (use_iv)
3729 LOOP_STMT_COND (gnu_loop_stmt)
3730 = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
3731 gnu_last);
3732 else
3733 LOOP_STMT_COND (gnu_loop_stmt)
3734 = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
3735 gnu_last);
3736
3737 /* Set either the top or bottom update statement and give it the source
3738 location of the iteration for better coverage info. */
3739 if (use_iv)
3740 {
3741 gnu_stmt
3742 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
3743 build_binary_op (update_code, gnu_base_type,
3744 gnu_loop_iv, gnu_one_node));
3745 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3746 append_to_statement_list (gnu_stmt,
3747 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3748 gnu_stmt
3749 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3750 gnu_loop_iv);
3751 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3752 append_to_statement_list (gnu_stmt,
3753 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3754 }
3755 else
3756 {
3757 gnu_stmt
3758 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3759 build_binary_op (update_code, gnu_base_type,
3760 gnu_loop_var, gnu_one_node));
3761 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3762 LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
3763 }
3764
3765 set_expr_location_from_node (gnu_loop_stmt, gnat_iter_scheme);
3766 }
3767
3768 /* If the loop was named, have the name point to this loop. In this case,
3769 the association is not a DECL node, but the end label of the loop. */
3770 if (Present (Identifier (gnat_node)))
3771 save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
3772
3773 /* Make the loop body into its own block, so any allocated storage will be
3774 released every iteration. This is needed for stack allocation. */
3775 LOOP_STMT_BODY (gnu_loop_stmt)
3776 = build_stmt_group (Statements (gnat_node), true);
3777 TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
3778
3779 /* If we have an iteration scheme, then we are in a statement group. Add
3780 the LOOP_STMT to it, finish it and make it the "loop". */
3781 if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
3782 {
3783 /* First, if we have computed invariant conditions for range (or index)
3784 checks applied to the iteration variable, find out whether they can
3785 be evaluated to false at compile time; otherwise, if there are not
3786 too many of them, combine them with the original checks. If loop
3787 unswitching is enabled, do not require the loop bounds to be also
3788 invariant, as their evaluation will still be ahead of the loop. */
3789 if (vec_safe_length (gnu_loop_info->checks) > 0
3790 && (make_invariant (&gnu_low, &gnu_high) || optimize >= 3))
3791 {
3792 struct range_check_info_d *rci;
3793 unsigned int i, n_remaining_checks = 0;
3794
3795 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3796 {
3797 tree low_ok, high_ok;
3798
3799 if (rci->low_bound)
3800 {
3801 tree gnu_adjusted_low = convert (rci->type, gnu_low);
3802 if (rci->disp)
3803 gnu_adjusted_low
3804 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3805 rci->type, gnu_adjusted_low, rci->disp);
3806 low_ok
3807 = build_binary_op (GE_EXPR, boolean_type_node,
3808 gnu_adjusted_low, rci->low_bound);
3809 }
3810 else
3811 low_ok = boolean_true_node;
3812
3813 if (rci->high_bound)
3814 {
3815 tree gnu_adjusted_high = convert (rci->type, gnu_high);
3816 if (rci->disp)
3817 gnu_adjusted_high
3818 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3819 rci->type, gnu_adjusted_high, rci->disp);
3820 high_ok
3821 = build_binary_op (LE_EXPR, boolean_type_node,
3822 gnu_adjusted_high, rci->high_bound);
3823 }
3824 else
3825 high_ok = boolean_true_node;
3826
3827 tree range_ok
3828 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
3829 low_ok, high_ok);
3830
3831 rci->invariant_cond
3832 = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
3833
3834 if (rci->invariant_cond == boolean_false_node)
3835 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3836 else
3837 n_remaining_checks++;
3838 }
3839
3840 /* Note that loop unswitching can only be applied a small number of
3841 times to a given loop (PARAM_MAX_UNSWITCH_LEVEL default to 3). */
3842 if (IN_RANGE (n_remaining_checks, 1, 3)
3843 && optimize >= 2
3844 && !optimize_size)
3845 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3846 if (rci->invariant_cond != boolean_false_node)
3847 {
3848 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3849
3850 if (optimize >= 3)
3851 add_stmt_with_node_force (rci->inserted_cond, gnat_node);
3852 }
3853 }
3854
3855 /* Second, if loop vectorization is enabled and the iterations of the
3856 loop can easily be proved as independent, mark the loop. */
3857 if (optimize >= 3
3858 && independent_iterations_p (LOOP_STMT_BODY (gnu_loop_stmt)))
3859 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
3860
3861 add_stmt (gnu_loop_stmt);
3862 gnat_poplevel ();
3863 gnu_loop_stmt = end_stmt_group ();
3864 }
3865
3866 *gnu_cond_expr_p = gnu_cond_expr;
3867
3868 return gnu_loop_stmt;
3869 }
3870
3871 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
3872 to a GCC tree, which is returned. */
3873
3874 static tree
3875 Loop_Statement_to_gnu (Node_Id gnat_node)
3876 {
3877 struct loop_info_d *gnu_loop_info = ggc_cleared_alloc<loop_info_d> ();
3878
3879 tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
3880 NULL_TREE, NULL_TREE, NULL_TREE);
3881 tree gnu_cond_expr = NULL_TREE;
3882 tree gnu_loop_label = create_artificial_label (input_location);
3883 tree gnu_result;
3884
3885 /* Push the loop_info structure associated with the LOOP_STMT. */
3886 vec_safe_push (gnu_loop_stack, gnu_loop_info);
3887
3888 /* Set location information for statement and end label. */
3889 set_expr_location_from_node (gnu_loop_stmt, gnat_node);
3890 Sloc_to_locus (Sloc (End_Label (gnat_node)),
3891 &DECL_SOURCE_LOCATION (gnu_loop_label));
3892 LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
3893
3894 /* Save the statement for later reuse. */
3895 gnu_loop_info->stmt = gnu_loop_stmt;
3896
3897 /* Perform the core loop body translation. */
3898 if (Is_OpenAcc_Loop (gnat_node))
3899 gnu_loop_stmt = Acc_Loop_to_gnu (gnat_node);
3900 else
3901 gnu_loop_stmt = Regular_Loop_to_gnu (gnat_node, &gnu_cond_expr);
3902
3903 /* A gnat_node that has its OpenAcc_Environment flag set needs to be
3904 offloaded. Note that the OpenAcc_Loop flag is not necessarily set. */
3905 if (Is_OpenAcc_Environment (gnat_node))
3906 {
3907 tree_code code = gnu_loop_stack->last ()->omp_code;
3908 tree tmp = make_node (code);
3909 TREE_TYPE (tmp) = void_type_node;
3910 if (code == OACC_PARALLEL || code == OACC_KERNELS)
3911 {
3912 OMP_BODY (tmp) = gnu_loop_stmt;
3913 OMP_CLAUSES (tmp) = gnu_loop_stack->last ()->omp_construct_clauses;
3914 }
3915 else if (code == OACC_DATA)
3916 {
3917 OACC_DATA_BODY (tmp) = gnu_loop_stmt;
3918 OACC_DATA_CLAUSES (tmp) =
3919 gnu_loop_stack->last ()->omp_construct_clauses;
3920 }
3921 else
3922 gcc_unreachable();
3923 set_expr_location_from_node (tmp, gnat_node);
3924 gnu_loop_stmt = tmp;
3925 }
3926
3927 /* If we have an outer COND_EXPR, that's our result and this loop is its
3928 "true" statement. Otherwise, the result is the LOOP_STMT. */
3929 if (gnu_cond_expr)
3930 {
3931 COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
3932 TREE_SIDE_EFFECTS (gnu_cond_expr) = 1;
3933 gnu_result = gnu_cond_expr;
3934 }
3935 else
3936 gnu_result = gnu_loop_stmt;
3937
3938 gnu_loop_stack->pop ();
3939
3940 return gnu_result;
3941 }
3942 \f
3943 /* This page implements a form of Named Return Value optimization modelled
3944 on the C++ optimization of the same name. The main difference is that
3945 we disregard any semantical considerations when applying it here, the
3946 counterpart being that we don't try to apply it to semantically loaded
3947 return types, i.e. types with the TYPE_BY_REFERENCE_P flag set.
3948
3949 We consider a function body of the following GENERIC form:
3950
3951 return_type R1;
3952 [...]
3953 RETURN_EXPR [<retval> = ...]
3954 [...]
3955 RETURN_EXPR [<retval> = R1]
3956 [...]
3957 return_type Ri;
3958 [...]
3959 RETURN_EXPR [<retval> = ...]
3960 [...]
3961 RETURN_EXPR [<retval> = Ri]
3962 [...]
3963
3964 where the Ri are not addressable and we try to fulfill a simple criterion
3965 that would make it possible to replace one or several Ri variables by the
3966 single RESULT_DECL of the function.
3967
3968 The first observation is that RETURN_EXPRs that don't directly reference
3969 any of the Ri variables on the RHS of their assignment are transparent wrt
3970 the optimization. This is because the Ri variables aren't addressable so
3971 any transformation applied to them doesn't affect the RHS; moreover, the
3972 assignment writes the full <retval> object so existing values are entirely
3973 discarded.
3974
3975 This property can be extended to some forms of RETURN_EXPRs that reference
3976 the Ri variables, for example CONSTRUCTORs, but isn't true in the general
3977 case, in particular when function calls are involved.
3978
3979 Therefore the algorithm is as follows:
3980
3981 1. Collect the list of candidates for a Named Return Value (Ri variables
3982 on the RHS of assignments of RETURN_EXPRs) as well as the list of the
3983 other expressions on the RHS of such assignments.
3984
3985 2. Prune the members of the first list (candidates) that are referenced
3986 by a member of the second list (expressions).
3987
3988 3. Extract a set of candidates with non-overlapping live ranges from the
3989 first list. These are the Named Return Values.
3990
3991 4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
3992 Named Return Values in the function with the RESULT_DECL.
3993
3994 If the function returns an unconstrained type, things are a bit different
3995 because the anonymous return object is allocated on the secondary stack
3996 and RESULT_DECL is only a pointer to it. Each return object can be of a
3997 different size and is allocated separately so we need not care about the
3998 addressability and the aforementioned overlapping issues. Therefore, we
3999 don't collect the other expressions and skip step #2 in the algorithm. */
4000
4001 struct nrv_data
4002 {
4003 bitmap nrv;
4004 tree result;
4005 Node_Id gnat_ret;
4006 hash_set<tree> *visited;
4007 };
4008
4009 /* Return true if T is a Named Return Value. */
4010
4011 static inline bool
4012 is_nrv_p (bitmap nrv, tree t)
4013 {
4014 return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
4015 }
4016
4017 /* Helper function for walk_tree, used by finalize_nrv below. */
4018
4019 static tree
4020 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
4021 {
4022 struct nrv_data *dp = (struct nrv_data *)data;
4023 tree t = *tp;
4024
4025 /* No need to walk into types or decls. */
4026 if (IS_TYPE_OR_DECL_P (t))
4027 *walk_subtrees = 0;
4028
4029 if (is_nrv_p (dp->nrv, t))
4030 bitmap_clear_bit (dp->nrv, DECL_UID (t));
4031
4032 return NULL_TREE;
4033 }
4034
4035 /* Prune Named Return Values in BLOCK and return true if there is still a
4036 Named Return Value in BLOCK or one of its sub-blocks. */
4037
4038 static bool
4039 prune_nrv_in_block (bitmap nrv, tree block)
4040 {
4041 bool has_nrv = false;
4042 tree t;
4043
4044 /* First recurse on the sub-blocks. */
4045 for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
4046 has_nrv |= prune_nrv_in_block (nrv, t);
4047
4048 /* Then make sure to keep at most one NRV per block. */
4049 for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
4050 if (is_nrv_p (nrv, t))
4051 {
4052 if (has_nrv)
4053 bitmap_clear_bit (nrv, DECL_UID (t));
4054 else
4055 has_nrv = true;
4056 }
4057
4058 return has_nrv;
4059 }
4060
4061 /* Helper function for walk_tree, used by finalize_nrv below. */
4062
4063 static tree
4064 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
4065 {
4066 struct nrv_data *dp = (struct nrv_data *)data;
4067 tree t = *tp;
4068
4069 /* No need to walk into types. */
4070 if (TYPE_P (t))
4071 *walk_subtrees = 0;
4072
4073 /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
4074 nop, but differs from using NULL_TREE in that it indicates that we care
4075 about the value of the RESULT_DECL. */
4076 else if (TREE_CODE (t) == RETURN_EXPR
4077 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
4078 {
4079 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
4080
4081 /* Strip useless conversions around the return value. */
4082 if (gnat_useless_type_conversion (ret_val))
4083 ret_val = TREE_OPERAND (ret_val, 0);
4084
4085 if (is_nrv_p (dp->nrv, ret_val))
4086 TREE_OPERAND (t, 0) = dp->result;
4087 }
4088
4089 /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
4090 if needed. */
4091 else if (TREE_CODE (t) == DECL_EXPR
4092 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
4093 {
4094 tree var = DECL_EXPR_DECL (t), init;
4095
4096 if (DECL_INITIAL (var))
4097 {
4098 init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
4099 DECL_INITIAL (var));
4100 SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
4101 DECL_INITIAL (var) = NULL_TREE;
4102 }
4103 else
4104 init = build_empty_stmt (EXPR_LOCATION (t));
4105 *tp = init;
4106
4107 /* Identify the NRV to the RESULT_DECL for debugging purposes. */
4108 SET_DECL_VALUE_EXPR (var, dp->result);
4109 DECL_HAS_VALUE_EXPR_P (var) = 1;
4110 /* ??? Kludge to avoid an assertion failure during inlining. */
4111 DECL_SIZE (var) = bitsize_unit_node;
4112 DECL_SIZE_UNIT (var) = size_one_node;
4113 }
4114
4115 /* And replace all uses of NRVs with the RESULT_DECL. */
4116 else if (is_nrv_p (dp->nrv, t))
4117 *tp = convert (TREE_TYPE (t), dp->result);
4118
4119 /* Avoid walking into the same tree more than once. Unfortunately, we
4120 can't just use walk_tree_without_duplicates because it would only
4121 call us for the first occurrence of NRVs in the function body. */
4122 if (dp->visited->add (*tp))
4123 *walk_subtrees = 0;
4124
4125 return NULL_TREE;
4126 }
4127
4128 /* Likewise, but used when the function returns an unconstrained type. */
4129
4130 static tree
4131 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
4132 {
4133 struct nrv_data *dp = (struct nrv_data *)data;
4134 tree t = *tp;
4135
4136 /* No need to walk into types. */
4137 if (TYPE_P (t))
4138 *walk_subtrees = 0;
4139
4140 /* We need to see the DECL_EXPR of NRVs before any other references so we
4141 walk the body of BIND_EXPR before walking its variables. */
4142 else if (TREE_CODE (t) == BIND_EXPR)
4143 walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
4144
4145 /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
4146 return value built by the allocator instead of the whole construct. */
4147 else if (TREE_CODE (t) == RETURN_EXPR
4148 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
4149 {
4150 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
4151
4152 /* This is the construct returned by the allocator. */
4153 if (TREE_CODE (ret_val) == COMPOUND_EXPR
4154 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
4155 {
4156 tree rhs = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
4157
4158 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
4159 ret_val = CONSTRUCTOR_ELT (rhs, 1)->value;
4160 else
4161 ret_val = rhs;
4162 }
4163
4164 /* Strip useless conversions around the return value. */
4165 if (gnat_useless_type_conversion (ret_val)
4166 || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
4167 ret_val = TREE_OPERAND (ret_val, 0);
4168
4169 /* Strip unpadding around the return value. */
4170 if (TREE_CODE (ret_val) == COMPONENT_REF
4171 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
4172 ret_val = TREE_OPERAND (ret_val, 0);
4173
4174 /* Assign the new return value to the RESULT_DECL. */
4175 if (is_nrv_p (dp->nrv, ret_val))
4176 TREE_OPERAND (TREE_OPERAND (t, 0), 1)
4177 = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
4178 }
4179
4180 /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
4181 into a new variable. */
4182 else if (TREE_CODE (t) == DECL_EXPR
4183 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
4184 {
4185 tree saved_current_function_decl = current_function_decl;
4186 tree var = DECL_EXPR_DECL (t);
4187 tree alloc, p_array, new_var, new_ret;
4188 vec<constructor_elt, va_gc> *v;
4189 vec_alloc (v, 2);
4190
4191 /* Create an artificial context to build the allocation. */
4192 current_function_decl = decl_function_context (var);
4193 start_stmt_group ();
4194 gnat_pushlevel ();
4195
4196 /* This will return a COMPOUND_EXPR with the allocation in the first
4197 arm and the final return value in the second arm. */
4198 alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
4199 TREE_TYPE (dp->result),
4200 Procedure_To_Call (dp->gnat_ret),
4201 Storage_Pool (dp->gnat_ret),
4202 Empty, false);
4203
4204 /* The new variable is built as a reference to the allocated space. */
4205 new_var
4206 = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
4207 build_reference_type (TREE_TYPE (var)));
4208 DECL_BY_REFERENCE (new_var) = 1;
4209
4210 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
4211 {
4212 tree cst = TREE_OPERAND (alloc, 1);
4213
4214 /* The new initial value is a COMPOUND_EXPR with the allocation in
4215 the first arm and the value of P_ARRAY in the second arm. */
4216 DECL_INITIAL (new_var)
4217 = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
4218 TREE_OPERAND (alloc, 0),
4219 CONSTRUCTOR_ELT (cst, 0)->value);
4220
4221 /* Build a modified CONSTRUCTOR that references NEW_VAR. */
4222 p_array = TYPE_FIELDS (TREE_TYPE (alloc));
4223 CONSTRUCTOR_APPEND_ELT (v, p_array,
4224 fold_convert (TREE_TYPE (p_array), new_var));
4225 CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
4226 CONSTRUCTOR_ELT (cst, 1)->value);
4227 new_ret = build_constructor (TREE_TYPE (alloc), v);
4228 }
4229 else
4230 {
4231 /* The new initial value is just the allocation. */
4232 DECL_INITIAL (new_var) = alloc;
4233 new_ret = fold_convert (TREE_TYPE (alloc), new_var);
4234 }
4235
4236 gnat_pushdecl (new_var, Empty);
4237
4238 /* Destroy the artificial context and insert the new statements. */
4239 gnat_zaplevel ();
4240 *tp = end_stmt_group ();
4241 current_function_decl = saved_current_function_decl;
4242
4243 /* Chain NEW_VAR immediately after VAR and ignore the latter. */
4244 DECL_CHAIN (new_var) = DECL_CHAIN (var);
4245 DECL_CHAIN (var) = new_var;
4246 DECL_IGNORED_P (var) = 1;
4247
4248 /* Save the new return value and the dereference of NEW_VAR. */
4249 DECL_INITIAL (var)
4250 = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
4251 build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
4252 /* ??? Kludge to avoid messing up during inlining. */
4253 DECL_CONTEXT (var) = NULL_TREE;
4254 }
4255
4256 /* And replace all uses of NRVs with the dereference of NEW_VAR. */
4257 else if (is_nrv_p (dp->nrv, t))
4258 *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
4259
4260 /* Avoid walking into the same tree more than once. Unfortunately, we
4261 can't just use walk_tree_without_duplicates because it would only
4262 call us for the first occurrence of NRVs in the function body. */
4263 if (dp->visited->add (*tp))
4264 *walk_subtrees = 0;
4265
4266 return NULL_TREE;
4267 }
4268
4269 /* Finalize the Named Return Value optimization for FNDECL. The NRV bitmap
4270 contains the candidates for Named Return Value and OTHER is a list of
4271 the other return values. GNAT_RET is a representative return node. */
4272
4273 static void
4274 finalize_nrv (tree fndecl, bitmap nrv, vec<tree, va_gc> *other, Node_Id gnat_ret)
4275 {
4276 struct cgraph_node *node;
4277 struct nrv_data data;
4278 walk_tree_fn func;
4279 unsigned int i;
4280 tree iter;
4281
4282 /* We shouldn't be applying the optimization to return types that we aren't
4283 allowed to manipulate freely. */
4284 gcc_assert (!TYPE_IS_BY_REFERENCE_P (TREE_TYPE (TREE_TYPE (fndecl))));
4285
4286 /* Prune the candidates that are referenced by other return values. */
4287 data.nrv = nrv;
4288 data.result = NULL_TREE;
4289 data.gnat_ret = Empty;
4290 data.visited = NULL;
4291 FOR_EACH_VEC_SAFE_ELT (other, i, iter)
4292 walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
4293 if (bitmap_empty_p (nrv))
4294 return;
4295
4296 /* Prune also the candidates that are referenced by nested functions. */
4297 node = cgraph_node::get_create (fndecl);
4298 for (node = node->nested; node; node = node->next_nested)
4299 walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), prune_nrv_r,
4300 &data);
4301 if (bitmap_empty_p (nrv))
4302 return;
4303
4304 /* Extract a set of NRVs with non-overlapping live ranges. */
4305 if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
4306 return;
4307
4308 /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs. */
4309 data.nrv = nrv;
4310 data.result = DECL_RESULT (fndecl);
4311 data.gnat_ret = gnat_ret;
4312 data.visited = new hash_set<tree>;
4313 if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
4314 func = finalize_nrv_unc_r;
4315 else
4316 func = finalize_nrv_r;
4317 walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
4318 delete data.visited;
4319 }
4320
4321 /* Return true if RET_VAL can be used as a Named Return Value for the
4322 anonymous return object RET_OBJ. */
4323
4324 static bool
4325 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
4326 {
4327 if (TREE_CODE (ret_val) != VAR_DECL)
4328 return false;
4329
4330 if (TREE_THIS_VOLATILE (ret_val))
4331 return false;
4332
4333 if (DECL_CONTEXT (ret_val) != current_function_decl)
4334 return false;
4335
4336 if (TREE_STATIC (ret_val))
4337 return false;
4338
4339 /* For the constrained case, test for addressability. */
4340 if (ret_obj && TREE_ADDRESSABLE (ret_val))
4341 return false;
4342
4343 /* For the constrained case, test for overalignment. */
4344 if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
4345 return false;
4346
4347 /* For the unconstrained case, test for bogus initialization. */
4348 if (!ret_obj
4349 && DECL_INITIAL (ret_val)
4350 && TREE_CODE (DECL_INITIAL (ret_val)) == NULL_EXPR)
4351 return false;
4352
4353 return true;
4354 }
4355
4356 /* Build a RETURN_EXPR. If RET_VAL is non-null, build a RETURN_EXPR around
4357 the assignment of RET_VAL to RET_OBJ. Otherwise build a bare RETURN_EXPR
4358 around RESULT_OBJ, which may be null in this case. */
4359
4360 static tree
4361 build_return_expr (tree ret_obj, tree ret_val)
4362 {
4363 tree result_expr;
4364
4365 if (ret_val)
4366 {
4367 /* The gimplifier explicitly enforces the following invariant:
4368
4369 RETURN_EXPR
4370 |
4371 INIT_EXPR
4372 / \
4373 / \
4374 RET_OBJ ...
4375
4376 As a consequence, type consistency dictates that we use the type
4377 of the RET_OBJ as the operation type. */
4378 tree operation_type = TREE_TYPE (ret_obj);
4379
4380 /* Convert the right operand to the operation type. Note that this is
4381 the transformation applied in the INIT_EXPR case of build_binary_op,
4382 with the assumption that the type cannot involve a placeholder. */
4383 if (operation_type != TREE_TYPE (ret_val))
4384 ret_val = convert (operation_type, ret_val);
4385
4386 /* We always can use an INIT_EXPR for the return object. */
4387 result_expr = build2 (INIT_EXPR, void_type_node, ret_obj, ret_val);
4388
4389 /* If the function returns an aggregate type, find out whether this is
4390 a candidate for Named Return Value. If so, record it. Otherwise,
4391 if this is an expression of some kind, record it elsewhere. */
4392 if (optimize
4393 && AGGREGATE_TYPE_P (operation_type)
4394 && !TYPE_IS_FAT_POINTER_P (operation_type)
4395 && TYPE_MODE (operation_type) == BLKmode
4396 && aggregate_value_p (operation_type, current_function_decl))
4397 {
4398 /* Strip useless conversions around the return value. */
4399 if (gnat_useless_type_conversion (ret_val))
4400 ret_val = TREE_OPERAND (ret_val, 0);
4401
4402 /* Now apply the test to the return value. */
4403 if (return_value_ok_for_nrv_p (ret_obj, ret_val))
4404 {
4405 if (!f_named_ret_val)
4406 f_named_ret_val = BITMAP_GGC_ALLOC ();
4407 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
4408 }
4409
4410 /* Note that we need not care about CONSTRUCTORs here, as they are
4411 totally transparent given the read-compose-write semantics of
4412 assignments from CONSTRUCTORs. */
4413 else if (EXPR_P (ret_val))
4414 vec_safe_push (f_other_ret_val, ret_val);
4415 }
4416 }
4417 else
4418 result_expr = ret_obj;
4419
4420 return build1 (RETURN_EXPR, void_type_node, result_expr);
4421 }
4422 \f
4423 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body. We
4424 don't return anything. */
4425
4426 static void
4427 Subprogram_Body_to_gnu (Node_Id gnat_node)
4428 {
4429 /* Defining identifier of a parameter to the subprogram. */
4430 Entity_Id gnat_param;
4431 /* The defining identifier for the subprogram body. Note that if a
4432 specification has appeared before for this body, then the identifier
4433 occurring in that specification will also be a defining identifier and all
4434 the calls to this subprogram will point to that specification. */
4435 Entity_Id gnat_subprog_id
4436 = (Present (Corresponding_Spec (gnat_node))
4437 ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
4438 /* The FUNCTION_DECL node corresponding to the subprogram spec. */
4439 tree gnu_subprog_decl;
4440 /* Its RESULT_DECL node. */
4441 tree gnu_result_decl;
4442 /* Its FUNCTION_TYPE node. */
4443 tree gnu_subprog_type;
4444 /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any. */
4445 tree gnu_cico_list;
4446 /* The entry in the CI_CO_LIST that represents a function return, if any. */
4447 tree gnu_return_var_elmt = NULL_TREE;
4448 tree gnu_result;
4449 location_t locus;
4450 struct language_function *gnu_subprog_language;
4451 vec<parm_attr, va_gc> *cache;
4452
4453 /* If this is a generic object or if it has been eliminated,
4454 ignore it. */
4455 if (Ekind (gnat_subprog_id) == E_Generic_Procedure
4456 || Ekind (gnat_subprog_id) == E_Generic_Function
4457 || Is_Eliminated (gnat_subprog_id))
4458 return;
4459
4460 /* If this subprogram acts as its own spec, define it. Otherwise, just get
4461 the already-elaborated tree node. However, if this subprogram had its
4462 elaboration deferred, we will already have made a tree node for it. So
4463 treat it as not being defined in that case. Such a subprogram cannot
4464 have an address clause or a freeze node, so this test is safe, though it
4465 does disable some otherwise-useful error checking. */
4466 gnu_subprog_decl
4467 = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
4468 Acts_As_Spec (gnat_node)
4469 && !present_gnu_tree (gnat_subprog_id));
4470 DECL_FUNCTION_IS_DEF (gnu_subprog_decl) = true;
4471 gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
4472 gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
4473 gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
4474 if (gnu_cico_list && TREE_VALUE (gnu_cico_list) == void_type_node)
4475 gnu_return_var_elmt = gnu_cico_list;
4476
4477 /* If the function returns by invisible reference, make it explicit in the
4478 function body. See gnat_to_gnu_entity, E_Subprogram_Type case. */
4479 if (TREE_ADDRESSABLE (gnu_subprog_type))
4480 {
4481 TREE_TYPE (gnu_result_decl)
4482 = build_reference_type (TREE_TYPE (gnu_result_decl));
4483 relayout_decl (gnu_result_decl);
4484 }
4485
4486 /* Set the line number in the decl to correspond to that of the body. */
4487 if (!Sloc_to_locus (Sloc (gnat_node), &locus, false, gnu_subprog_decl))
4488 locus = input_location;
4489 DECL_SOURCE_LOCATION (gnu_subprog_decl) = locus;
4490
4491 /* If the body comes from an expression function, arrange it to be inlined
4492 in almost all cases. */
4493 if (Was_Expression_Function (gnat_node))
4494 DECL_DISREGARD_INLINE_LIMITS (gnu_subprog_decl) = 1;
4495
4496 /* Try to create a bona-fide thunk and hand it over to the middle-end. */
4497 if (Is_Thunk (gnat_subprog_id)
4498 && maybe_make_gnu_thunk (gnat_subprog_id, gnu_subprog_decl))
4499 return;
4500
4501 /* Initialize the information structure for the function. */
4502 allocate_struct_function (gnu_subprog_decl, false);
4503 gnu_subprog_language = ggc_cleared_alloc<language_function> ();
4504 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language = gnu_subprog_language;
4505 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_start_locus = locus;
4506 set_cfun (NULL);
4507
4508 begin_subprog_body (gnu_subprog_decl);
4509
4510 /* If there are copy-in/copy-out parameters, we need to ensure that they are
4511 properly copied out by the return statement. We do this by making a new
4512 block and converting any return into a goto to a label at the end of the
4513 block. */
4514 if (gnu_cico_list)
4515 {
4516 tree gnu_return_var = NULL_TREE;
4517
4518 vec_safe_push (gnu_return_label_stack,
4519 create_artificial_label (input_location));
4520
4521 start_stmt_group ();
4522 gnat_pushlevel ();
4523
4524 /* If this is a function with copy-in/copy-out parameters and which does
4525 not return by invisible reference, we also need a variable for the
4526 return value to be placed. */
4527 if (gnu_return_var_elmt && !TREE_ADDRESSABLE (gnu_subprog_type))
4528 {
4529 tree gnu_return_type
4530 = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
4531
4532 gnu_return_var
4533 = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
4534 gnu_return_type, NULL_TREE,
4535 false, false, false, false, false,
4536 true, false, NULL, gnat_subprog_id);
4537 TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
4538 }
4539
4540 vec_safe_push (gnu_return_var_stack, gnu_return_var);
4541
4542 /* See whether there are parameters for which we don't have a GCC tree
4543 yet. These must be Out parameters. Make a VAR_DECL for them and
4544 put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
4545 We can match up the entries because TYPE_CI_CO_LIST is in the order
4546 of the parameters. */
4547 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
4548 Present (gnat_param);
4549 gnat_param = Next_Formal_With_Extras (gnat_param))
4550 if (!present_gnu_tree (gnat_param))
4551 {
4552 tree gnu_cico_entry = gnu_cico_list;
4553 tree gnu_decl;
4554
4555 /* Skip any entries that have been already filled in; they must
4556 correspond to In Out parameters. */
4557 while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
4558 gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
4559
4560 /* Do any needed dereferences for by-ref objects. */
4561 gnu_decl = gnat_to_gnu_entity (gnat_param, NULL_TREE, true);
4562 gcc_assert (DECL_P (gnu_decl));
4563 if (DECL_BY_REF_P (gnu_decl))
4564 gnu_decl = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_decl);
4565
4566 /* Do any needed references for padded types. */
4567 TREE_VALUE (gnu_cico_entry)
4568 = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)), gnu_decl);
4569 }
4570 }
4571 else
4572 vec_safe_push (gnu_return_label_stack, NULL_TREE);
4573
4574 /* Get a tree corresponding to the code for the subprogram. */
4575 start_stmt_group ();
4576 gnat_pushlevel ();
4577
4578 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
4579
4580 /* Generate the code of the subprogram itself. A return statement will be
4581 present and any Out parameters will be handled there. */
4582 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
4583 gnat_poplevel ();
4584 gnu_result = end_stmt_group ();
4585
4586 /* If we populated the parameter attributes cache, we need to make sure that
4587 the cached expressions are evaluated on all the possible paths leading to
4588 their uses. So we force their evaluation on entry of the function. */
4589 cache = gnu_subprog_language->parm_attr_cache;
4590 if (cache)
4591 {
4592 struct parm_attr_d *pa;
4593 int i;
4594
4595 start_stmt_group ();
4596
4597 FOR_EACH_VEC_ELT (*cache, i, pa)
4598 {
4599 if (pa->first)
4600 add_stmt_with_node_force (pa->first, gnat_node);
4601 if (pa->last)
4602 add_stmt_with_node_force (pa->last, gnat_node);
4603 if (pa->length)
4604 add_stmt_with_node_force (pa->length, gnat_node);
4605 }
4606
4607 add_stmt (gnu_result);
4608 gnu_result = end_stmt_group ();
4609
4610 gnu_subprog_language->parm_attr_cache = NULL;
4611 }
4612
4613 /* If we are dealing with a return from an Ada procedure with parameters
4614 passed by copy-in/copy-out, we need to return a record containing the
4615 final values of these parameters. If the list contains only one entry,
4616 return just that entry though.
4617
4618 For a full description of the copy-in/copy-out parameter mechanism, see
4619 the part of the gnat_to_gnu_entity routine dealing with the translation
4620 of subprograms.
4621
4622 We need to make a block that contains the definition of that label and
4623 the copying of the return value. It first contains the function, then
4624 the label and copy statement. */
4625 if (gnu_cico_list)
4626 {
4627 const Node_Id gnat_end_label
4628 = End_Label (Handled_Statement_Sequence (gnat_node));
4629
4630 gnu_return_var_stack->pop ();
4631
4632 add_stmt (gnu_result);
4633 add_stmt (build1 (LABEL_EXPR, void_type_node,
4634 gnu_return_label_stack->last ()));
4635
4636 /* If this is a function which returns by invisible reference, the
4637 return value has already been dealt with at the return statements,
4638 so we only need to indirectly copy out the parameters. */
4639 if (TREE_ADDRESSABLE (gnu_subprog_type))
4640 {
4641 tree gnu_ret_deref
4642 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result_decl);
4643 tree t;
4644
4645 gcc_assert (TREE_VALUE (gnu_cico_list) == void_type_node);
4646
4647 for (t = TREE_CHAIN (gnu_cico_list); t; t = TREE_CHAIN (t))
4648 {
4649 tree gnu_field_deref
4650 = build_component_ref (gnu_ret_deref, TREE_PURPOSE (t), true);
4651 gnu_result = build2 (MODIFY_EXPR, void_type_node,
4652 gnu_field_deref, TREE_VALUE (t));
4653 add_stmt_with_node (gnu_result, gnat_end_label);
4654 }
4655 }
4656
4657 /* Otherwise, if this is a procedure or a function which does not return
4658 by invisible reference, we can do a direct block-copy out. */
4659 else
4660 {
4661 tree gnu_retval;
4662
4663 if (list_length (gnu_cico_list) == 1)
4664 gnu_retval = TREE_VALUE (gnu_cico_list);
4665 else
4666 gnu_retval
4667 = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
4668 gnu_cico_list);
4669
4670 gnu_result = build_return_expr (gnu_result_decl, gnu_retval);
4671 add_stmt_with_node (gnu_result, gnat_end_label);
4672 }
4673
4674 gnat_poplevel ();
4675 gnu_result = end_stmt_group ();
4676 }
4677
4678 gnu_return_label_stack->pop ();
4679
4680 /* Attempt setting the end_locus of our GCC body tree, typically a
4681 BIND_EXPR or STATEMENT_LIST, then the end_locus of our GCC subprogram
4682 declaration tree. */
4683 set_end_locus_from_node (gnu_result, gnat_node);
4684 set_end_locus_from_node (gnu_subprog_decl, gnat_node);
4685
4686 /* On SEH targets, install an exception handler around the main entry
4687 point to catch unhandled exceptions. */
4688 if (DECL_NAME (gnu_subprog_decl) == main_identifier_node
4689 && targetm_common.except_unwind_info (&global_options) == UI_SEH)
4690 {
4691 tree t;
4692 tree etype;
4693
4694 t = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
4695 1, integer_zero_node);
4696 t = build_call_n_expr (unhandled_except_decl, 1, t);
4697
4698 etype = build_unary_op (ADDR_EXPR, NULL_TREE, unhandled_others_decl);
4699 etype = tree_cons (NULL_TREE, etype, NULL_TREE);
4700
4701 t = build2 (CATCH_EXPR, void_type_node, etype, t);
4702 gnu_result = build2 (TRY_CATCH_EXPR, TREE_TYPE (gnu_result),
4703 gnu_result, t);
4704 }
4705
4706 end_subprog_body (gnu_result);
4707
4708 /* Finally annotate the parameters and disconnect the trees for parameters
4709 that we have turned into variables since they are now unusable. */
4710 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
4711 Present (gnat_param);
4712 gnat_param = Next_Formal_With_Extras (gnat_param))
4713 {
4714 tree gnu_param = get_gnu_tree (gnat_param);
4715 bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
4716
4717 annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
4718 DECL_BY_REF_P (gnu_param));
4719
4720 if (is_var_decl)
4721 save_gnu_tree (gnat_param, NULL_TREE, false);
4722 }
4723
4724 /* Disconnect the variable created for the return value. */
4725 if (gnu_return_var_elmt)
4726 TREE_VALUE (gnu_return_var_elmt) = void_type_node;
4727
4728 /* If the function returns an aggregate type and we have candidates for
4729 a Named Return Value, finalize the optimization. */
4730 if (optimize && gnu_subprog_language->named_ret_val)
4731 {
4732 finalize_nrv (gnu_subprog_decl,
4733 gnu_subprog_language->named_ret_val,
4734 gnu_subprog_language->other_ret_val,
4735 gnu_subprog_language->gnat_ret);
4736 gnu_subprog_language->named_ret_val = NULL;
4737 gnu_subprog_language->other_ret_val = NULL;
4738 }
4739
4740 /* If this is an inlined external function that has been marked uninlinable,
4741 drop the body and stop there. Otherwise compile the body. */
4742 if (DECL_EXTERNAL (gnu_subprog_decl) && DECL_UNINLINABLE (gnu_subprog_decl))
4743 DECL_SAVED_TREE (gnu_subprog_decl) = NULL_TREE;
4744 else
4745 rest_of_subprog_body_compilation (gnu_subprog_decl);
4746 }
4747 \f
4748 /* Return true if GNAT_NODE references an Atomic entity. */
4749
4750 static bool
4751 node_is_atomic (Node_Id gnat_node)
4752 {
4753 Entity_Id gnat_entity;
4754
4755 switch (Nkind (gnat_node))
4756 {
4757 case N_Identifier:
4758 case N_Expanded_Name:
4759 gnat_entity = Entity (gnat_node);
4760 if (Ekind (gnat_entity) != E_Variable)
4761 break;
4762 return Is_Atomic (gnat_entity) || Is_Atomic (Etype (gnat_entity));
4763
4764 case N_Selected_Component:
4765 gnat_entity = Entity (Selector_Name (gnat_node));
4766 return Is_Atomic (gnat_entity) || Is_Atomic (Etype (gnat_entity));
4767
4768 case N_Indexed_Component:
4769 if (Has_Atomic_Components (Etype (Prefix (gnat_node))))
4770 return true;
4771 if (Is_Entity_Name (Prefix (gnat_node))
4772 && Has_Atomic_Components (Entity (Prefix (gnat_node))))
4773 return true;
4774
4775 /* ... fall through ... */
4776
4777 case N_Explicit_Dereference:
4778 return Is_Atomic (Etype (gnat_node));
4779
4780 default:
4781 break;
4782 }
4783
4784 return false;
4785 }
4786
4787 /* Return true if GNAT_NODE references a Volatile_Full_Access entity. */
4788
4789 static bool
4790 node_has_volatile_full_access (Node_Id gnat_node)
4791 {
4792 Entity_Id gnat_entity;
4793
4794 switch (Nkind (gnat_node))
4795 {
4796 case N_Identifier:
4797 case N_Expanded_Name:
4798 gnat_entity = Entity (gnat_node);
4799 if (!Is_Object (gnat_entity))
4800 break;
4801 return Is_Volatile_Full_Access (gnat_entity)
4802 || Is_Volatile_Full_Access (Etype (gnat_entity));
4803
4804 case N_Selected_Component:
4805 gnat_entity = Entity (Selector_Name (gnat_node));
4806 return Is_Volatile_Full_Access (gnat_entity)
4807 || Is_Volatile_Full_Access (Etype (gnat_entity));
4808
4809 case N_Indexed_Component:
4810 case N_Explicit_Dereference:
4811 return Is_Volatile_Full_Access (Etype (gnat_node));
4812
4813 default:
4814 break;
4815 }
4816
4817 return false;
4818 }
4819
4820 /* Strip any type conversion on GNAT_NODE and return the result. */
4821
4822 static Node_Id
4823 gnat_strip_type_conversion (Node_Id gnat_node)
4824 {
4825 Node_Kind kind = Nkind (gnat_node);
4826
4827 if (kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
4828 gnat_node = Expression (gnat_node);
4829
4830 return gnat_node;
4831 }
4832
4833 /* Return true if GNAT_NODE requires outer atomic access, i.e. atomic access
4834 of an object of which GNAT_NODE is a component. */
4835
4836 static bool
4837 outer_atomic_access_required_p (Node_Id gnat_node)
4838 {
4839 gnat_node = gnat_strip_type_conversion (gnat_node);
4840
4841 while (true)
4842 {
4843 switch (Nkind (gnat_node))
4844 {
4845 case N_Identifier:
4846 case N_Expanded_Name:
4847 if (No (Renamed_Object (Entity (gnat_node))))
4848 return false;
4849 gnat_node
4850 = gnat_strip_type_conversion (Renamed_Object (Entity (gnat_node)));
4851 break;
4852
4853 case N_Indexed_Component:
4854 case N_Selected_Component:
4855 case N_Slice:
4856 gnat_node = gnat_strip_type_conversion (Prefix (gnat_node));
4857 if (node_has_volatile_full_access (gnat_node))
4858 return true;
4859 break;
4860
4861 default:
4862 return false;
4863 }
4864 }
4865
4866 gcc_unreachable ();
4867 }
4868
4869 /* Return true if GNAT_NODE requires atomic access and set SYNC according to
4870 the associated synchronization setting. */
4871
4872 static bool
4873 atomic_access_required_p (Node_Id gnat_node, bool *sync)
4874 {
4875 const Node_Id gnat_parent = Parent (gnat_node);
4876 unsigned char attr_id;
4877 bool as_a_whole = true;
4878
4879 /* First, scan the parent to find out cases where the flag is irrelevant. */
4880 switch (Nkind (gnat_parent))
4881 {
4882 case N_Attribute_Reference:
4883 attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
4884 /* Do not mess up machine code insertions. */
4885 if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
4886 return false;
4887
4888 /* Nothing to do if we are the prefix of an attribute, since we do not
4889 want an atomic access for things like 'Size. */
4890
4891 /* ... fall through ... */
4892
4893 case N_Reference:
4894 /* The N_Reference node is like an attribute. */
4895 if (Prefix (gnat_parent) == gnat_node)
4896 return false;
4897 break;
4898
4899 case N_Indexed_Component:
4900 case N_Selected_Component:
4901 case N_Slice:
4902 /* If we are the prefix, then the access is only partial. */
4903 if (Prefix (gnat_parent) == gnat_node)
4904 as_a_whole = false;
4905 break;
4906
4907 case N_Object_Renaming_Declaration:
4908 /* Nothing to do for the identifier in an object renaming declaration,
4909 the renaming itself does not need atomic access. */
4910 return false;
4911
4912 default:
4913 break;
4914 }
4915
4916 /* Then, scan the node to find the atomic object. */
4917 gnat_node = gnat_strip_type_conversion (gnat_node);
4918
4919 /* For Atomic itself, only reads and updates of the object as a whole require
4920 atomic access (RM C.6 (15)). But for Volatile_Full_Access, all reads and
4921 updates require atomic access. */
4922 if (!(as_a_whole && node_is_atomic (gnat_node))
4923 && !node_has_volatile_full_access (gnat_node))
4924 return false;
4925
4926 /* If an outer atomic access will also be required, it cancels this one. */
4927 if (outer_atomic_access_required_p (gnat_node))
4928 return false;
4929
4930 *sync = Atomic_Sync_Required (gnat_node);
4931
4932 return true;
4933 }
4934 \f
4935 /* Create a temporary variable with PREFIX and TYPE, and return it. */
4936
4937 static tree
4938 create_temporary (const char *prefix, tree type)
4939 {
4940 tree gnu_temp
4941 = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
4942 type, NULL_TREE,
4943 false, false, false, false, false,
4944 true, false, NULL, Empty);
4945 return gnu_temp;
4946 }
4947
4948 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
4949 Put the initialization statement into GNU_INIT_STMT and annotate it with
4950 the SLOC of GNAT_NODE. Return the temporary variable. */
4951
4952 static tree
4953 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
4954 Node_Id gnat_node)
4955 {
4956 tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
4957
4958 *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
4959 set_expr_location_from_node (*gnu_init_stmt, gnat_node);
4960
4961 return gnu_temp;
4962 }
4963
4964 /* Return whether ACTUAL parameter corresponding to FORMAL_TYPE must be passed
4965 by copy in a call as per RM C.6(19). Note that we use the same predicates
4966 as in the front-end for RM C.6(12) because it's purely a legality issue. */
4967
4968 static bool
4969 atomic_or_volatile_copy_required_p (Node_Id actual, Entity_Id formal_type)
4970 {
4971 /* We should not have a scalar type here because such a type is passed
4972 by copy. But the Interlocked routines in System.Aux_DEC force some
4973 of the their scalar parameters to be passed by reference so we need
4974 to preserve that if we do not want to break the interface. */
4975 if (Is_Scalar_Type (formal_type))
4976 return false;
4977
4978 if (Is_Atomic_Object (actual) && !Is_Atomic (formal_type))
4979 {
4980 post_error ("?atomic actual passed by copy (RM C.6(19))", actual);
4981 return true;
4982 }
4983
4984 if (Is_Volatile_Object (actual) && !Is_Volatile (formal_type))
4985 {
4986 post_error ("?volatile actual passed by copy (RM C.6(19))", actual);
4987 return true;
4988 }
4989
4990 return false;
4991 }
4992
4993 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
4994 or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
4995 GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
4996 If GNU_TARGET is non-null, this must be a function call on the RHS of a
4997 N_Assignment_Statement and the result is to be placed into that object.
4998 If OUTER_ATOMIC_ACCESS is true, then the assignment to GNU_TARGET must be a
4999 load-modify-store sequence. Otherwise, if ATOMIC_ACCESS is true, then the
5000 assignment to GNU_TARGET must be atomic. If, in addition, ATOMIC_SYNC is
5001 true, then the assignment to GNU_TARGET requires atomic synchronization. */
5002
5003 static tree
5004 Call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
5005 bool outer_atomic_access, bool atomic_access, bool atomic_sync)
5006 {
5007 const bool function_call = (Nkind (gnat_node) == N_Function_Call);
5008 const bool returning_value = (function_call && !gnu_target);
5009 /* The GCC node corresponding to the GNAT subprogram name. This can either
5010 be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
5011 or an indirect reference expression (an INDIRECT_REF node) pointing to a
5012 subprogram. */
5013 tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
5014 /* The FUNCTION_TYPE node giving the GCC type of the subprogram. */
5015 tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
5016 /* The return type of the FUNCTION_TYPE. */
5017 tree gnu_result_type = TREE_TYPE (gnu_subprog_type);
5018 tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
5019 vec<tree, va_gc> *gnu_actual_vec = NULL;
5020 tree gnu_name_list = NULL_TREE;
5021 tree gnu_stmt_list = NULL_TREE;
5022 tree gnu_after_list = NULL_TREE;
5023 tree gnu_retval = NULL_TREE;
5024 tree gnu_call, gnu_result;
5025 bool by_descriptor = false;
5026 bool went_into_elab_proc = false;
5027 bool pushed_binding_level = false;
5028 Entity_Id gnat_formal;
5029 Node_Id gnat_actual;
5030 bool sync;
5031
5032 gcc_assert (FUNC_OR_METHOD_TYPE_P (gnu_subprog_type));
5033
5034 /* If we are calling a stubbed function, raise Program_Error, but Elaborate
5035 all our args first. */
5036 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
5037 {
5038 tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
5039 gnat_node, N_Raise_Program_Error);
5040
5041 for (gnat_actual = First_Actual (gnat_node);
5042 Present (gnat_actual);
5043 gnat_actual = Next_Actual (gnat_actual))
5044 add_stmt (gnat_to_gnu (gnat_actual));
5045
5046 if (returning_value)
5047 {
5048 *gnu_result_type_p = gnu_result_type;
5049 return build1 (NULL_EXPR, gnu_result_type, call_expr);
5050 }
5051
5052 return call_expr;
5053 }
5054
5055 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL)
5056 {
5057 /* For a call to a nested function, check the inlining status. */
5058 if (decl_function_context (gnu_subprog))
5059 check_inlining_for_nested_subprog (gnu_subprog);
5060
5061 /* For a recursive call, avoid explosion due to recursive inlining. */
5062 if (gnu_subprog == current_function_decl)
5063 DECL_DISREGARD_INLINE_LIMITS (gnu_subprog) = 0;
5064 }
5065
5066 /* The only way we can be making a call via an access type is if Name is an
5067 explicit dereference. In that case, get the list of formal args from the
5068 type the access type is pointing to. Otherwise, get the formals from the
5069 entity being called. */
5070 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
5071 {
5072 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
5073
5074 /* If the access type doesn't require foreign-compatible representation,
5075 be prepared for descriptors. */
5076 if (targetm.calls.custom_function_descriptors > 0
5077 && Can_Use_Internal_Rep (Etype (Prefix (Name (gnat_node)))))
5078 by_descriptor = true;
5079 }
5080 else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
5081 /* Assume here that this must be 'Elab_Body or 'Elab_Spec. */
5082 gnat_formal = Empty;
5083 else
5084 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
5085
5086 /* The lifetime of the temporaries created for the call ends right after the
5087 return value is copied, so we can give them the scope of the elaboration
5088 routine at top level. */
5089 if (!current_function_decl)
5090 {
5091 current_function_decl = get_elaboration_procedure ();
5092 went_into_elab_proc = true;
5093 }
5094
5095 /* First, create the temporary for the return value when:
5096
5097 1. There is no target and the function has copy-in/copy-out parameters,
5098 because we need to preserve the return value before copying back the
5099 parameters.
5100
5101 2. There is no target and the call is made for neither an object, nor a
5102 renaming declaration, nor a return statement, nor an allocator, and
5103 the return type has variable size because in this case the gimplifier
5104 cannot create the temporary, or more generally is an aggregate type,
5105 because the gimplifier would create the temporary in the outermost
5106 scope instead of locally. But there is an exception for an allocator
5107 of an unconstrained record type with default discriminant because we
5108 allocate the actual size in this case, unlike the other 3 cases, so
5109 we need a temporary to fetch the discriminant and we create it here.
5110
5111 3. There is a target and it is a slice or an array with fixed size,
5112 and the return type has variable size, because the gimplifier
5113 doesn't handle these cases.
5114
5115 4. There is no target and we have misaligned In Out or Out parameters
5116 passed by reference, because we need to preserve the return value
5117 before copying back the parameters. However, in this case, we'll
5118 defer creating the temporary, see below.
5119
5120 This must be done before we push a binding level around the call, since
5121 we will pop it before copying the return value. */
5122 if (function_call
5123 && ((!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))
5124 || (!gnu_target
5125 && Nkind (Parent (gnat_node)) != N_Object_Declaration
5126 && Nkind (Parent (gnat_node)) != N_Object_Renaming_Declaration
5127 && Nkind (Parent (gnat_node)) != N_Simple_Return_Statement
5128 && (!(Nkind (Parent (gnat_node)) == N_Qualified_Expression
5129 && Nkind (Parent (Parent (gnat_node))) == N_Allocator)
5130 || type_is_padding_self_referential (gnu_result_type))
5131 && AGGREGATE_TYPE_P (gnu_result_type)
5132 && !TYPE_IS_FAT_POINTER_P (gnu_result_type))
5133 || (gnu_target
5134 && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
5135 || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
5136 && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
5137 == INTEGER_CST))
5138 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)))
5139 {
5140 gnu_retval = create_temporary ("R", gnu_result_type);
5141 DECL_RETURN_VALUE_P (gnu_retval) = 1;
5142 }
5143
5144 /* If we don't need a value or have already created it, push a binding level
5145 around the call. This will narrow the lifetime of the temporaries we may
5146 need to make when translating the parameters as much as possible. */
5147 if (!returning_value || gnu_retval)
5148 {
5149 start_stmt_group ();
5150 gnat_pushlevel ();
5151 pushed_binding_level = true;
5152 }
5153
5154 /* Create the list of the actual parameters as GCC expects it, namely a
5155 chain of TREE_LIST nodes in which the TREE_VALUE field of each node
5156 is an expression and the TREE_PURPOSE field is null. But skip Out
5157 parameters not passed by reference and that need not be copied in. */
5158 for (gnat_actual = First_Actual (gnat_node);
5159 Present (gnat_actual);
5160 gnat_formal = Next_Formal_With_Extras (gnat_formal),
5161 gnat_actual = Next_Actual (gnat_actual))
5162 {
5163 Entity_Id gnat_formal_type = Etype (gnat_formal);
5164 tree gnu_formal_type = gnat_to_gnu_type (gnat_formal_type);
5165 tree gnu_formal = present_gnu_tree (gnat_formal)
5166 ? get_gnu_tree (gnat_formal) : NULL_TREE;
5167 const bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
5168 const bool is_true_formal_parm
5169 = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
5170 const bool is_by_ref_formal_parm
5171 = is_true_formal_parm
5172 && (DECL_BY_REF_P (gnu_formal)
5173 || DECL_BY_COMPONENT_PTR_P (gnu_formal));
5174 /* In the In Out or Out case, we must suppress conversions that yield
5175 an lvalue but can nevertheless cause the creation of a temporary,
5176 because we need the real object in this case, either to pass its
5177 address if it's passed by reference or as target of the back copy
5178 done after the call if it uses the copy-in/copy-out mechanism.
5179 We do it in the In case too, except for an unchecked conversion
5180 to an elementary type or a constrained composite type because it
5181 alone can cause the actual to be misaligned and the addressability
5182 test is applied to the real object. */
5183 const bool suppress_type_conversion
5184 = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
5185 && (!in_param
5186 || !is_by_ref_formal_parm
5187 || (Is_Composite_Type (Underlying_Type (gnat_formal_type))
5188 && !Is_Constrained (Underlying_Type (gnat_formal_type)))))
5189 || (Nkind (gnat_actual) == N_Type_Conversion
5190 && Is_Composite_Type (Underlying_Type (gnat_formal_type))));
5191 Node_Id gnat_name = suppress_type_conversion
5192 ? Expression (gnat_actual) : gnat_actual;
5193 tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
5194
5195 /* If it's possible we may need to use this expression twice, make sure
5196 that any side-effects are handled via SAVE_EXPRs; likewise if we need
5197 to force side-effects before the call. */
5198 if (!in_param && !is_by_ref_formal_parm)
5199 {
5200 tree init = NULL_TREE;
5201 gnu_name = gnat_stabilize_reference (gnu_name, true, &init);
5202 if (init)
5203 gnu_name
5204 = build_compound_expr (TREE_TYPE (gnu_name), init, gnu_name);
5205 }
5206
5207 /* If we are passing a non-addressable actual parameter by reference,
5208 pass the address of a copy and, in the In Out or Out case, set up
5209 to copy back after the call. We also need to do that if the actual
5210 parameter is atomic or volatile but the formal parameter is not. */
5211 if (is_by_ref_formal_parm
5212 && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
5213 && (!addressable_p (gnu_name, gnu_name_type)
5214 || (Comes_From_Source (gnat_node)
5215 && atomic_or_volatile_copy_required_p (gnat_actual,
5216 gnat_formal_type))))
5217 {
5218 const bool atomic_p = atomic_access_required_p (gnat_actual, &sync);
5219 tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
5220
5221 /* Do not issue warnings for CONSTRUCTORs since this is not a copy
5222 but sort of an instantiation for them. */
5223 if (TREE_CODE (gnu_name) == CONSTRUCTOR)
5224 ;
5225
5226 /* If the type is passed by reference, a copy is not allowed. */
5227 else if (TYPE_IS_BY_REFERENCE_P (gnu_formal_type))
5228 post_error ("misaligned actual cannot be passed by reference",
5229 gnat_actual);
5230
5231 /* For users of Starlet we issue a warning because the interface
5232 apparently assumes that by-ref parameters outlive the procedure
5233 invocation. The code still will not work as intended, but we
5234 cannot do much better since low-level parts of the back-end
5235 would allocate temporaries at will because of the misalignment
5236 if we did not do so here. */
5237 else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
5238 {
5239 post_error
5240 ("?possible violation of implicit assumption", gnat_actual);
5241 post_error_ne
5242 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
5243 Entity (Name (gnat_node)));
5244 post_error_ne ("?because of misalignment of &", gnat_actual,
5245 gnat_formal);
5246 }
5247
5248 /* If the actual type of the object is already the nominal type,
5249 we have nothing to do, except if the size is self-referential
5250 in which case we'll remove the unpadding below. */
5251 if (TREE_TYPE (gnu_name) == gnu_name_type
5252 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
5253 ;
5254
5255 /* Otherwise remove the unpadding from all the objects. */
5256 else if (TREE_CODE (gnu_name) == COMPONENT_REF
5257 && TYPE_IS_PADDING_P
5258 (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
5259 gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
5260
5261 /* Otherwise convert to the nominal type of the object if needed.
5262 There are several cases in which we need to make the temporary
5263 using this type instead of the actual type of the object when
5264 they are distinct, because the expectations of the callee would
5265 otherwise not be met:
5266 - if it's a justified modular type,
5267 - if the actual type is a smaller form of it,
5268 - if it's a smaller form of the actual type. */
5269 else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
5270 && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
5271 || smaller_form_type_p (TREE_TYPE (gnu_name),
5272 gnu_name_type)))
5273 || (INTEGRAL_TYPE_P (gnu_name_type)
5274 && smaller_form_type_p (gnu_name_type,
5275 TREE_TYPE (gnu_name))))
5276 gnu_name = convert (gnu_name_type, gnu_name);
5277
5278 /* If this is an In Out or Out parameter and we're returning a value,
5279 we need to create a temporary for the return value because we must
5280 preserve it before copying back at the very end. */
5281 if (!in_param && returning_value && !gnu_retval)
5282 {
5283 gnu_retval = create_temporary ("R", gnu_result_type);
5284 DECL_RETURN_VALUE_P (gnu_retval) = 1;
5285 }
5286
5287 /* If we haven't pushed a binding level, push it now. This will
5288 narrow the lifetime of the temporary we are about to make as
5289 much as possible. */
5290 if (!pushed_binding_level && (!returning_value || gnu_retval))
5291 {
5292 start_stmt_group ();
5293 gnat_pushlevel ();
5294 pushed_binding_level = true;
5295 }
5296
5297 /* Create an explicit temporary holding the copy. */
5298 if (atomic_p)
5299 gnu_name = build_atomic_load (gnu_name, sync);
5300 gnu_temp
5301 = create_init_temporary ("A", gnu_name, &gnu_stmt, gnat_actual);
5302
5303 /* But initialize it on the fly like for an implicit temporary as
5304 we aren't necessarily having a statement list. */
5305 gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
5306 gnu_temp);
5307
5308 /* Set up to move the copy back to the original if needed. */
5309 if (!in_param)
5310 {
5311 /* If the original is a COND_EXPR whose first arm isn't meant to
5312 be further used, just deal with the second arm. This is very
5313 likely the conditional expression built for a check. */
5314 if (TREE_CODE (gnu_orig) == COND_EXPR
5315 && TREE_CODE (TREE_OPERAND (gnu_orig, 1)) == COMPOUND_EXPR
5316 && integer_zerop
5317 (TREE_OPERAND (TREE_OPERAND (gnu_orig, 1), 1)))
5318 gnu_orig = TREE_OPERAND (gnu_orig, 2);
5319
5320 if (atomic_p)
5321 gnu_stmt
5322 = build_atomic_store (gnu_orig, gnu_temp, sync);
5323 else
5324 gnu_stmt
5325 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig,
5326 gnu_temp);
5327 set_expr_location_from_node (gnu_stmt, gnat_node);
5328
5329 append_to_statement_list (gnu_stmt, &gnu_after_list);
5330 }
5331 }
5332
5333 /* Start from the real object and build the actual. */
5334 tree gnu_actual = gnu_name;
5335
5336 /* If atomic access is required for an In or In Out actual parameter,
5337 build the atomic load. */
5338 if (is_true_formal_parm
5339 && !is_by_ref_formal_parm
5340 && Ekind (gnat_formal) != E_Out_Parameter
5341 && atomic_access_required_p (gnat_actual, &sync))
5342 gnu_actual = build_atomic_load (gnu_actual, sync);
5343
5344 /* If this was a procedure call, we may not have removed any padding.
5345 So do it here for the part we will use as an input, if any. */
5346 if (Ekind (gnat_formal) != E_Out_Parameter
5347 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
5348 gnu_actual
5349 = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
5350
5351 /* Put back the conversion we suppressed above in the computation of the
5352 real object. And even if we didn't suppress any conversion there, we
5353 may have suppressed a conversion to the Etype of the actual earlier,
5354 since the parent is a procedure call, so put it back here. Note that
5355 we might have a dummy type here if the actual is the dereference of a
5356 pointer to it, but that's OK if the formal is passed by reference. */
5357 tree gnu_actual_type = gnat_to_gnu_type (Etype (gnat_actual));
5358 if (TYPE_IS_DUMMY_P (gnu_actual_type))
5359 gcc_assert (is_true_formal_parm && DECL_BY_REF_P (gnu_formal));
5360 else if (suppress_type_conversion
5361 && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
5362 gnu_actual = unchecked_convert (gnu_actual_type, gnu_actual,
5363 No_Truncation (gnat_actual));
5364 else
5365 gnu_actual = convert (gnu_actual_type, gnu_actual);
5366
5367 /* Make sure that the actual is in range of the formal's type. */
5368 if (Ekind (gnat_formal) != E_Out_Parameter
5369 && Do_Range_Check (gnat_actual))
5370 gnu_actual
5371 = emit_range_check (gnu_actual, gnat_formal_type, gnat_actual);
5372
5373 /* First see if the parameter is passed by reference. */
5374 if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
5375 {
5376 if (!in_param)
5377 {
5378 /* In Out or Out parameters passed by reference don't use the
5379 copy-in/copy-out mechanism so the address of the real object
5380 must be passed to the function. */
5381 gnu_actual = gnu_name;
5382
5383 /* If we have a padded type, be sure we've removed padding. */
5384 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
5385 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
5386 gnu_actual);
5387
5388 /* If we have the constructed subtype of an aliased object
5389 with an unconstrained nominal subtype, the type of the
5390 actual includes the template, although it is formally
5391 constrained. So we need to convert it back to the real
5392 constructed subtype to retrieve the constrained part
5393 and takes its address. */
5394 if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
5395 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
5396 && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
5397 && Is_Array_Type (Underlying_Type (Etype (gnat_actual))))
5398 gnu_actual = convert (gnu_actual_type, gnu_actual);
5399 }
5400
5401 /* There is no need to convert the actual to the formal's type before
5402 taking its address. The only exception is for unconstrained array
5403 types because of the way we build fat pointers. */
5404 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
5405 {
5406 /* Put back the conversion we suppressed above for In Out or Out
5407 parameters, since it may set the bounds of the actual. */
5408 if (!in_param && suppress_type_conversion)
5409 gnu_actual = convert (gnu_actual_type, gnu_actual);
5410 gnu_actual = convert (gnu_formal_type, gnu_actual);
5411 }
5412
5413 /* Take the address of the object and convert to the proper pointer
5414 type. */
5415 gnu_formal_type = TREE_TYPE (gnu_formal);
5416 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
5417 }
5418
5419 /* Then see if the parameter is an array passed to a foreign convention
5420 subprogram. */
5421 else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
5422 {
5423 gnu_actual = maybe_implicit_deref (gnu_actual);
5424 gnu_actual = maybe_unconstrained_array (gnu_actual);
5425
5426 /* Take the address of the object and convert to the proper pointer
5427 type. We'd like to actually compute the address of the beginning
5428 of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
5429 possibility that the ARRAY_REF might return a constant and we'd be
5430 getting the wrong address. Neither approach is exactly correct,
5431 but this is the most likely to work in all cases. */
5432 gnu_formal_type = TREE_TYPE (gnu_formal);
5433 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
5434 }
5435
5436 /* Otherwise the parameter is passed by copy. */
5437 else
5438 {
5439 tree gnu_size;
5440
5441 if (!in_param)
5442 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
5443
5444 /* If we didn't create a PARM_DECL for the formal, this means that
5445 it is an Out parameter not passed by reference and that need not
5446 be copied in. In this case, the value of the actual need not be
5447 read. However, we still need to make sure that its side-effects
5448 are evaluated before the call, so we evaluate its address. */
5449 if (!is_true_formal_parm)
5450 {
5451 if (TREE_SIDE_EFFECTS (gnu_name))
5452 {
5453 tree addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_name);
5454 append_to_statement_list (addr, &gnu_stmt_list);
5455 }
5456 continue;
5457 }
5458
5459 gnu_actual = convert (gnu_formal_type, gnu_actual);
5460
5461 /* If this is 'Null_Parameter, pass a zero even though we are
5462 dereferencing it. */
5463 if (TREE_CODE (gnu_actual) == INDIRECT_REF
5464 && TREE_PRIVATE (gnu_actual)
5465 && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
5466 && TREE_CODE (gnu_size) == INTEGER_CST
5467 && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
5468 {
5469 tree type_for_size
5470 = gnat_type_for_size (TREE_INT_CST_LOW (gnu_size), 1);
5471 gnu_actual
5472 = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
5473 build_int_cst (type_for_size, 0),
5474 false);
5475 }
5476 else
5477 gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
5478 }
5479
5480 vec_safe_push (gnu_actual_vec, gnu_actual);
5481 }
5482
5483 gnu_call
5484 = build_call_vec (gnu_result_type, gnu_subprog_addr, gnu_actual_vec);
5485 CALL_EXPR_BY_DESCRIPTOR (gnu_call) = by_descriptor;
5486 set_expr_location_from_node (gnu_call, gnat_node);
5487
5488 /* If we have created a temporary for the return value, initialize it. */
5489 if (gnu_retval)
5490 {
5491 tree gnu_stmt
5492 = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
5493 set_expr_location_from_node (gnu_stmt, gnat_node);
5494 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
5495 gnu_call = gnu_retval;
5496 }
5497
5498 /* If this is a subprogram with copy-in/copy-out parameters, we need to
5499 unpack the valued returned from the function into the In Out or Out
5500 parameters. We deal with the function return (if this is an Ada
5501 function) below. */
5502 if (TYPE_CI_CO_LIST (gnu_subprog_type))
5503 {
5504 /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
5505 copy-out parameters. */
5506 tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
5507 const int length = list_length (gnu_cico_list);
5508
5509 /* The call sequence must contain one and only one call, even though the
5510 function is pure. Save the result into a temporary if needed. */
5511 if (length > 1)
5512 {
5513 if (!gnu_retval)
5514 {
5515 tree gnu_stmt;
5516 gnu_call
5517 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
5518 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
5519 }
5520
5521 gnu_name_list = nreverse (gnu_name_list);
5522 }
5523
5524 /* The first entry is for the actual return value if this is a
5525 function, so skip it. */
5526 if (function_call)
5527 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
5528
5529 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
5530 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
5531 else
5532 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
5533
5534 for (gnat_actual = First_Actual (gnat_node);
5535 Present (gnat_actual);
5536 gnat_formal = Next_Formal_With_Extras (gnat_formal),
5537 gnat_actual = Next_Actual (gnat_actual))
5538 /* If we are dealing with a copy-in/copy-out parameter, we must
5539 retrieve its value from the record returned in the call. */
5540 if (!(present_gnu_tree (gnat_formal)
5541 && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
5542 && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
5543 || DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))))
5544 && Ekind (gnat_formal) != E_In_Parameter)
5545 {
5546 /* Get the value to assign to this In Out or Out parameter. It is
5547 either the result of the function if there is only a single such
5548 parameter or the appropriate field from the record returned. */
5549 tree gnu_result
5550 = length == 1
5551 ? gnu_call
5552 : build_component_ref (gnu_call, TREE_PURPOSE (gnu_cico_list),
5553 false);
5554
5555 /* If the actual is a conversion, get the inner expression, which
5556 will be the real destination, and convert the result to the
5557 type of the actual parameter. */
5558 tree gnu_actual
5559 = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
5560
5561 /* If the result is a padded type, remove the padding. */
5562 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
5563 gnu_result
5564 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
5565 gnu_result);
5566
5567 /* If the actual is a type conversion, the real target object is
5568 denoted by the inner Expression and we need to convert the
5569 result to the associated type.
5570 We also need to convert our gnu assignment target to this type
5571 if the corresponding GNU_NAME was constructed from the GNAT
5572 conversion node and not from the inner Expression. */
5573 if (Nkind (gnat_actual) == N_Type_Conversion)
5574 {
5575 gnu_result
5576 = convert_with_check
5577 (Etype (Expression (gnat_actual)), gnu_result,
5578 Do_Overflow_Check (gnat_actual),
5579 Do_Range_Check (Expression (gnat_actual)),
5580 Float_Truncate (gnat_actual), gnat_actual);
5581
5582 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
5583 gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
5584 }
5585
5586 /* Unchecked conversions as actuals for Out parameters are not
5587 allowed in user code because they are not variables, but do
5588 occur in front-end expansions. The associated GNU_NAME is
5589 always obtained from the inner expression in such cases. */
5590 else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
5591 gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
5592 gnu_result,
5593 No_Truncation (gnat_actual));
5594 else
5595 {
5596 if (Do_Range_Check (gnat_actual))
5597 gnu_result
5598 = emit_range_check (gnu_result, Etype (gnat_actual),
5599 gnat_actual);
5600
5601 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
5602 && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
5603 gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
5604 }
5605
5606 /* If an outer atomic access is required for an actual parameter,
5607 build the load-modify-store sequence. */
5608 if (outer_atomic_access_required_p (gnat_actual))
5609 gnu_result
5610 = build_load_modify_store (gnu_actual, gnu_result, gnat_node);
5611
5612 /* Or else, if simple atomic access is required, build the atomic
5613 store. */
5614 else if (atomic_access_required_p (gnat_actual, &sync))
5615 gnu_result = build_atomic_store (gnu_actual, gnu_result, sync);
5616
5617 /* Otherwise build a regular assignment. */
5618 else
5619 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
5620 gnu_actual, gnu_result);
5621
5622 if (EXPR_P (gnu_result))
5623 set_expr_location_from_node (gnu_result, gnat_node);
5624 append_to_statement_list (gnu_result, &gnu_stmt_list);
5625 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
5626 gnu_name_list = TREE_CHAIN (gnu_name_list);
5627 }
5628 }
5629
5630 /* If this is a function call, the result is the call expression unless a
5631 target is specified, in which case we copy the result into the target
5632 and return the assignment statement. */
5633 if (function_call)
5634 {
5635 /* If this is a function with copy-in/copy-out parameters, extract the
5636 return value from it and update the return type. */
5637 if (TYPE_CI_CO_LIST (gnu_subprog_type))
5638 {
5639 tree gnu_elmt = TYPE_CI_CO_LIST (gnu_subprog_type);
5640 gnu_call
5641 = build_component_ref (gnu_call, TREE_PURPOSE (gnu_elmt), false);
5642 gnu_result_type = TREE_TYPE (gnu_call);
5643 }
5644
5645 /* If the function returns an unconstrained array or by direct reference,
5646 we have to dereference the pointer. */
5647 if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
5648 || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
5649 gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
5650
5651 if (gnu_target)
5652 {
5653 Node_Id gnat_parent = Parent (gnat_node);
5654 enum tree_code op_code;
5655
5656 /* If range check is needed, emit code to generate it. */
5657 if (Do_Range_Check (gnat_node))
5658 gnu_call
5659 = emit_range_check (gnu_call, Etype (Name (gnat_parent)),
5660 gnat_parent);
5661
5662 /* ??? If the return type has variable size, then force the return
5663 slot optimization as we would not be able to create a temporary.
5664 That's what has been done historically. */
5665 if (return_type_with_variable_size_p (gnu_result_type))
5666 op_code = INIT_EXPR;
5667 else
5668 op_code = MODIFY_EXPR;
5669
5670 /* Use the required method to move the result to the target. */
5671 if (outer_atomic_access)
5672 gnu_call
5673 = build_load_modify_store (gnu_target, gnu_call, gnat_node);
5674 else if (atomic_access)
5675 gnu_call = build_atomic_store (gnu_target, gnu_call, atomic_sync);
5676 else
5677 gnu_call
5678 = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
5679
5680 if (EXPR_P (gnu_call))
5681 set_expr_location_from_node (gnu_call, gnat_parent);
5682 append_to_statement_list (gnu_call, &gnu_stmt_list);
5683 }
5684 else
5685 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5686 }
5687
5688 /* Otherwise, if this is a procedure call statement without copy-in/copy-out
5689 parameters, the result is just the call statement. */
5690 else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
5691 append_to_statement_list (gnu_call, &gnu_stmt_list);
5692
5693 /* Finally, add the copy back statements, if any. */
5694 append_to_statement_list (gnu_after_list, &gnu_stmt_list);
5695
5696 if (went_into_elab_proc)
5697 current_function_decl = NULL_TREE;
5698
5699 /* If we have pushed a binding level, pop it and finish up the enclosing
5700 statement group. */
5701 if (pushed_binding_level)
5702 {
5703 add_stmt (gnu_stmt_list);
5704 gnat_poplevel ();
5705 gnu_result = end_stmt_group ();
5706 }
5707
5708 /* Otherwise, retrieve the statement list, if any. */
5709 else if (gnu_stmt_list)
5710 gnu_result = gnu_stmt_list;
5711
5712 /* Otherwise, just return the call expression. */
5713 else
5714 return gnu_call;
5715
5716 /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
5717 But first simplify if we have only one statement in the list. */
5718 if (returning_value)
5719 {
5720 tree first = expr_first (gnu_result), last = expr_last (gnu_result);
5721 if (first == last)
5722 gnu_result = first;
5723 gnu_result
5724 = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
5725 }
5726
5727 return gnu_result;
5728 }
5729 \f
5730 /* Subroutine of gnat_to_gnu to translate gnat_node, an
5731 N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned. */
5732
5733 static tree
5734 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
5735 {
5736 /* If just annotating, ignore all EH and cleanups. */
5737 const bool gcc_eh
5738 = (!type_annotate_only
5739 && Present (Exception_Handlers (gnat_node))
5740 && Back_End_Exceptions ());
5741 const bool fe_sjlj_eh
5742 = (!type_annotate_only
5743 && Present (Exception_Handlers (gnat_node))
5744 && Exception_Mechanism == Front_End_SJLJ);
5745 const bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
5746 const bool binding_for_block = (at_end || gcc_eh || fe_sjlj_eh);
5747 tree gnu_jmpsave_decl = NULL_TREE;
5748 tree gnu_jmpbuf_decl = NULL_TREE;
5749 tree gnu_inner_block; /* The statement(s) for the block itself. */
5750 tree gnu_result;
5751 tree gnu_expr;
5752 Node_Id gnat_temp;
5753
5754 /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
5755 and the front-end has its own SJLJ mechanism. To call the GCC mechanism,
5756 we call add_cleanup, and when we leave the binding, end_stmt_group will
5757 create the TRY_FINALLY_EXPR construct.
5758
5759 ??? The region level calls down there have been specifically put in place
5760 for a ZCX context and currently the order in which things are emitted
5761 (region/handlers) is different from the SJLJ case. Instead of putting
5762 other calls with different conditions at other places for the SJLJ case,
5763 it seems cleaner to reorder things for the SJLJ case and generalize the
5764 condition to make it not ZCX specific.
5765
5766 If there are any exceptions or cleanup processing involved, we need an
5767 outer statement group (for front-end SJLJ) and binding level. */
5768 if (binding_for_block)
5769 {
5770 start_stmt_group ();
5771 gnat_pushlevel ();
5772 }
5773
5774 /* If using fe_sjlj_eh, make the variables for the setjmp buffer and save
5775 area for address of previous buffer. Do this first since we need to have
5776 the setjmp buf known for any decls in this block. */
5777 if (fe_sjlj_eh)
5778 {
5779 gnu_jmpsave_decl
5780 = create_var_decl (get_identifier ("JMPBUF_SAVE"), NULL_TREE,
5781 jmpbuf_ptr_type,
5782 build_call_n_expr (get_jmpbuf_decl, 0),
5783 false, false, false, false, false, true, false,
5784 NULL, gnat_node);
5785
5786 /* The __builtin_setjmp receivers will immediately reinstall it. Now
5787 because of the unstructured form of EH used by fe_sjlj_eh, there
5788 might be forward edges going to __builtin_setjmp receivers on which
5789 it is uninitialized, although they will never be actually taken. */
5790 TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
5791 gnu_jmpbuf_decl
5792 = create_var_decl (get_identifier ("JMP_BUF"), NULL_TREE,
5793 jmpbuf_type,
5794 NULL_TREE,
5795 false, false, false, false, false, true, false,
5796 NULL, gnat_node);
5797
5798 set_block_jmpbuf_decl (gnu_jmpbuf_decl);
5799
5800 /* When we exit this block, restore the saved value. */
5801 add_cleanup (build_call_n_expr (set_jmpbuf_decl, 1, gnu_jmpsave_decl),
5802 Present (End_Label (gnat_node))
5803 ? End_Label (gnat_node) : gnat_node);
5804 }
5805
5806 /* If we are to call a function when exiting this block, add a cleanup
5807 to the binding level we made above. Note that add_cleanup is FIFO
5808 so we must register this cleanup after the EH cleanup just above. */
5809 if (at_end)
5810 {
5811 tree proc_decl = gnat_to_gnu (At_End_Proc (gnat_node));
5812
5813 /* When not optimizing, disable inlining of finalizers as this can
5814 create a more complex CFG in the parent function. */
5815 if (!optimize)
5816 DECL_DECLARED_INLINE_P (proc_decl) = 0;
5817
5818 /* If there is no end label attached, we use the location of the At_End
5819 procedure because Expand_Cleanup_Actions might reset the location of
5820 the enclosing construct to that of an inner statement. */
5821 add_cleanup (build_call_n_expr (proc_decl, 0),
5822 Present (End_Label (gnat_node))
5823 ? End_Label (gnat_node) : At_End_Proc (gnat_node));
5824 }
5825
5826 /* Now build the tree for the declarations and statements inside this block.
5827 If this is SJLJ, set our jmp_buf as the current buffer. */
5828 start_stmt_group ();
5829
5830 if (fe_sjlj_eh)
5831 {
5832 gnu_expr = build_call_n_expr (set_jmpbuf_decl, 1,
5833 build_unary_op (ADDR_EXPR, NULL_TREE,
5834 gnu_jmpbuf_decl));
5835 set_expr_location_from_node (gnu_expr, gnat_node);
5836 add_stmt (gnu_expr);
5837 }
5838
5839 if (Present (First_Real_Statement (gnat_node)))
5840 process_decls (Statements (gnat_node), Empty,
5841 First_Real_Statement (gnat_node), true, true);
5842
5843 /* Generate code for each statement in the block. */
5844 for (gnat_temp = (Present (First_Real_Statement (gnat_node))
5845 ? First_Real_Statement (gnat_node)
5846 : First (Statements (gnat_node)));
5847 Present (gnat_temp); gnat_temp = Next (gnat_temp))
5848 add_stmt (gnat_to_gnu (gnat_temp));
5849
5850 gnu_inner_block = end_stmt_group ();
5851
5852 /* Now generate code for the two exception models, if either is relevant for
5853 this block. */
5854 if (fe_sjlj_eh)
5855 {
5856 tree *gnu_else_ptr = 0;
5857 tree gnu_handler;
5858
5859 /* Make a binding level for the exception handling declarations and code
5860 and set up gnu_except_ptr_stack for the handlers to use. */
5861 start_stmt_group ();
5862 gnat_pushlevel ();
5863
5864 vec_safe_push (gnu_except_ptr_stack,
5865 create_var_decl (get_identifier ("EXCEPT_PTR"), NULL_TREE,
5866 build_pointer_type (except_type_node),
5867 build_call_n_expr (get_excptr_decl, 0),
5868 false, false, false, false, false,
5869 true, false, NULL, gnat_node));
5870
5871 /* Generate code for each handler. The N_Exception_Handler case does the
5872 real work and returns a COND_EXPR for each handler, which we chain
5873 together here. */
5874 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
5875 Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
5876 {
5877 gnu_expr = gnat_to_gnu (gnat_temp);
5878
5879 /* If this is the first one, set it as the outer one. Otherwise,
5880 point the "else" part of the previous handler to us. Then point
5881 to our "else" part. */
5882 if (!gnu_else_ptr)
5883 add_stmt (gnu_expr);
5884 else
5885 *gnu_else_ptr = gnu_expr;
5886
5887 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
5888 }
5889
5890 /* If none of the exception handlers did anything, re-raise but do not
5891 defer abortion. */
5892 gnu_expr = build_call_n_expr (raise_nodefer_decl, 1,
5893 gnu_except_ptr_stack->last ());
5894 set_expr_location_from_node
5895 (gnu_expr,
5896 Present (End_Label (gnat_node)) ? End_Label (gnat_node) : gnat_node);
5897
5898 if (gnu_else_ptr)
5899 *gnu_else_ptr = gnu_expr;
5900 else
5901 add_stmt (gnu_expr);
5902
5903 /* End the binding level dedicated to the exception handlers and get the
5904 whole statement group. */
5905 gnu_except_ptr_stack->pop ();
5906 gnat_poplevel ();
5907 gnu_handler = end_stmt_group ();
5908
5909 /* If the setjmp returns 1, we restore our incoming longjmp value and
5910 then check the handlers. */
5911 start_stmt_group ();
5912 add_stmt_with_node (build_call_n_expr (set_jmpbuf_decl, 1,
5913 gnu_jmpsave_decl),
5914 gnat_node);
5915 add_stmt (gnu_handler);
5916 gnu_handler = end_stmt_group ();
5917
5918 /* This block is now "if (setjmp) ... <handlers> else <block>". */
5919 gnu_result = build3 (COND_EXPR, void_type_node,
5920 (build_call_n_expr
5921 (setjmp_decl, 1,
5922 build_unary_op (ADDR_EXPR, NULL_TREE,
5923 gnu_jmpbuf_decl))),
5924 gnu_handler, gnu_inner_block);
5925 }
5926 else if (gcc_eh)
5927 {
5928 tree gnu_handlers;
5929 location_t locus;
5930
5931 /* First make a block containing the handlers. */
5932 start_stmt_group ();
5933 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
5934 Present (gnat_temp);
5935 gnat_temp = Next_Non_Pragma (gnat_temp))
5936 add_stmt (gnat_to_gnu (gnat_temp));
5937 gnu_handlers = end_stmt_group ();
5938
5939 /* Now make the TRY_CATCH_EXPR for the block. */
5940 gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
5941 gnu_inner_block, gnu_handlers);
5942 /* Set a location. We need to find a unique location for the dispatching
5943 code, otherwise we can get coverage or debugging issues. Try with
5944 the location of the end label. */
5945 if (Present (End_Label (gnat_node))
5946 && Sloc_to_locus (Sloc (End_Label (gnat_node)), &locus))
5947 SET_EXPR_LOCATION (gnu_result, locus);
5948 else
5949 /* Clear column information so that the exception handler of an
5950 implicit transient block does not incorrectly inherit the slocs
5951 of a decision, which would otherwise confuse control flow based
5952 coverage analysis tools. */
5953 set_expr_location_from_node (gnu_result, gnat_node, true);
5954 }
5955 else
5956 gnu_result = gnu_inner_block;
5957
5958 /* Now close our outer block, if we had to make one. */
5959 if (binding_for_block)
5960 {
5961 add_stmt (gnu_result);
5962 gnat_poplevel ();
5963 gnu_result = end_stmt_group ();
5964 }
5965
5966 return gnu_result;
5967 }
5968 \f
5969 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
5970 to a GCC tree, which is returned. This is the variant for front-end sjlj
5971 exception handling. */
5972
5973 static tree
5974 Exception_Handler_to_gnu_fe_sjlj (Node_Id gnat_node)
5975 {
5976 /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
5977 an "if" statement to select the proper exceptions. For "Others", exclude
5978 exceptions where Handled_By_Others is nonzero unless the All_Others flag
5979 is set. For "Non-ada", accept an exception if "Lang" is 'V'. */
5980 tree gnu_choice = boolean_false_node;
5981 tree gnu_body = build_stmt_group (Statements (gnat_node), false);
5982 Node_Id gnat_temp;
5983
5984 for (gnat_temp = First (Exception_Choices (gnat_node));
5985 gnat_temp; gnat_temp = Next (gnat_temp))
5986 {
5987 tree this_choice;
5988
5989 if (Nkind (gnat_temp) == N_Others_Choice)
5990 {
5991 if (All_Others (gnat_temp))
5992 this_choice = boolean_true_node;
5993 else
5994 this_choice
5995 = build_binary_op
5996 (EQ_EXPR, boolean_type_node,
5997 convert
5998 (integer_type_node,
5999 build_component_ref
6000 (build_unary_op
6001 (INDIRECT_REF, NULL_TREE,
6002 gnu_except_ptr_stack->last ()),
6003 not_handled_by_others_decl,
6004 false)),
6005 integer_zero_node);
6006 }
6007
6008 else if (Nkind (gnat_temp) == N_Identifier
6009 || Nkind (gnat_temp) == N_Expanded_Name)
6010 {
6011 Entity_Id gnat_ex_id = Entity (gnat_temp);
6012 tree gnu_expr;
6013
6014 /* Exception may be a renaming. Recover original exception which is
6015 the one elaborated and registered. */
6016 if (Present (Renamed_Object (gnat_ex_id)))
6017 gnat_ex_id = Renamed_Object (gnat_ex_id);
6018
6019 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, false);
6020
6021 this_choice
6022 = build_binary_op
6023 (EQ_EXPR, boolean_type_node,
6024 gnu_except_ptr_stack->last (),
6025 convert (TREE_TYPE (gnu_except_ptr_stack->last ()),
6026 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
6027 }
6028 else
6029 gcc_unreachable ();
6030
6031 gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
6032 gnu_choice, this_choice);
6033 }
6034
6035 return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
6036 }
6037 \f
6038 /* Return true if no statement in GNAT_LIST can alter the control flow. */
6039
6040 static bool
6041 stmt_list_cannot_alter_control_flow_p (List_Id gnat_list)
6042 {
6043 if (No (gnat_list))
6044 return true;
6045
6046 /* This is very conservative, we reject everything except for simple
6047 assignments between identifiers or literals. */
6048 for (Node_Id gnat_node = First (gnat_list);
6049 Present (gnat_node);
6050 gnat_node = Next (gnat_node))
6051 {
6052 if (Nkind (gnat_node) != N_Assignment_Statement)
6053 return false;
6054
6055 if (Nkind (Name (gnat_node)) != N_Identifier)
6056 return false;
6057
6058 Node_Kind nkind = Nkind (Expression (gnat_node));
6059 if (nkind != N_Identifier
6060 && nkind != N_Integer_Literal
6061 && nkind != N_Real_Literal)
6062 return false;
6063 }
6064
6065 return true;
6066 }
6067
6068 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
6069 to a GCC tree, which is returned. This is the variant for GCC exception
6070 schemes. */
6071
6072 static tree
6073 Exception_Handler_to_gnu_gcc (Node_Id gnat_node)
6074 {
6075 tree gnu_etypes_list = NULL_TREE;
6076
6077 /* We build a TREE_LIST of nodes representing what exception types this
6078 handler can catch, with special cases for others and all others cases.
6079
6080 Each exception type is actually identified by a pointer to the exception
6081 id, or to a dummy object for "others" and "all others". */
6082 for (Node_Id gnat_temp = First (Exception_Choices (gnat_node));
6083 gnat_temp;
6084 gnat_temp = Next (gnat_temp))
6085 {
6086 tree gnu_expr, gnu_etype;
6087
6088 if (Nkind (gnat_temp) == N_Others_Choice)
6089 {
6090 gnu_expr = All_Others (gnat_temp) ? all_others_decl : others_decl;
6091 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
6092 }
6093 else if (Nkind (gnat_temp) == N_Identifier
6094 || Nkind (gnat_temp) == N_Expanded_Name)
6095 {
6096 Entity_Id gnat_ex_id = Entity (gnat_temp);
6097
6098 /* Exception may be a renaming. Recover original exception which is
6099 the one elaborated and registered. */
6100 if (Present (Renamed_Object (gnat_ex_id)))
6101 gnat_ex_id = Renamed_Object (gnat_ex_id);
6102
6103 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, false);
6104 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
6105 }
6106 else
6107 gcc_unreachable ();
6108
6109 /* The GCC interface expects NULL to be passed for catch all handlers, so
6110 it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
6111 is integer_zero_node. It would not work, however, because GCC's
6112 notion of "catch all" is stronger than our notion of "others". Until
6113 we correctly use the cleanup interface as well, doing that would
6114 prevent the "all others" handlers from being seen, because nothing
6115 can be caught beyond a catch all from GCC's point of view. */
6116 gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
6117 }
6118
6119 start_stmt_group ();
6120 gnat_pushlevel ();
6121
6122 /* Expand a call to the begin_handler hook at the beginning of the handler,
6123 and arrange for a call to the end_handler hook to occur on every possible
6124 exit path.
6125
6126 The hooks expect a pointer to the low level occurrence. This is required
6127 for our stack management scheme because a raise inside the handler pushes
6128 a new occurrence on top of the stack, which means that this top does not
6129 necessarily match the occurrence this handler was dealing with.
6130
6131 __builtin_eh_pointer references the exception occurrence being
6132 propagated. Upon handler entry, this is the exception for which the
6133 handler is triggered. This might not be the case upon handler exit,
6134 however, as we might have a new occurrence propagated by the handler's
6135 body, and the end_handler hook called as a cleanup in this context.
6136
6137 We use a local variable to retrieve the incoming value at handler entry
6138 time, and reuse it to feed the end_handler hook's argument at exit. */
6139
6140 tree gnu_current_exc_ptr
6141 = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
6142 1, integer_zero_node);
6143 tree prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
6144 gnu_incoming_exc_ptr
6145 = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
6146 ptr_type_node, gnu_current_exc_ptr,
6147 false, false, false, false, false, true, true,
6148 NULL, gnat_node);
6149
6150 add_stmt_with_node (build_call_n_expr (begin_handler_decl, 1,
6151 gnu_incoming_exc_ptr),
6152 gnat_node);
6153
6154 /* Declare and initialize the choice parameter, if present. */
6155 if (Present (Choice_Parameter (gnat_node)))
6156 {
6157 tree gnu_param
6158 = gnat_to_gnu_entity (Choice_Parameter (gnat_node), NULL_TREE, true);
6159
6160 add_stmt (build_call_n_expr
6161 (set_exception_parameter_decl, 2,
6162 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_param),
6163 gnu_incoming_exc_ptr));
6164 }
6165
6166 add_stmt_list (Statements (gnat_node));
6167
6168 /* We don't have an End_Label at hand to set the location of the cleanup
6169 actions, so we use that of the exception handler itself instead. */
6170 tree stmt = build_call_n_expr (end_handler_decl, 1, gnu_incoming_exc_ptr);
6171 if (stmt_list_cannot_alter_control_flow_p (Statements (gnat_node)))
6172 add_stmt_with_node (stmt, gnat_node);
6173 else
6174 add_cleanup (stmt, gnat_node);
6175
6176 gnat_poplevel ();
6177
6178 gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
6179
6180 return
6181 build2 (CATCH_EXPR, void_type_node, gnu_etypes_list, end_stmt_group ());
6182 }
6183 \f
6184 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit. */
6185
6186 static void
6187 Compilation_Unit_to_gnu (Node_Id gnat_node)
6188 {
6189 const Node_Id gnat_unit = Unit (gnat_node);
6190 const bool body_p = (Nkind (gnat_unit) == N_Package_Body
6191 || Nkind (gnat_unit) == N_Subprogram_Body);
6192 const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
6193 Entity_Id gnat_entity;
6194 Node_Id gnat_pragma;
6195 /* Make the decl for the elaboration procedure. Emit debug info for it, so
6196 that users can break into their elaboration code in debuggers. Kludge:
6197 don't consider it as a definition so that we have a line map for its body,
6198 but no subprogram description in debug info. */
6199 tree gnu_elab_proc_decl
6200 = create_subprog_decl
6201 (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
6202 NULL_TREE, void_ftype, NULL_TREE,
6203 is_default, true, false, true, true, false, NULL, gnat_unit);
6204 struct elab_info *info;
6205
6206 vec_safe_push (gnu_elab_proc_stack, gnu_elab_proc_decl);
6207 DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
6208
6209 /* Initialize the information structure for the function. */
6210 allocate_struct_function (gnu_elab_proc_decl, false);
6211 set_cfun (NULL);
6212
6213 current_function_decl = NULL_TREE;
6214
6215 start_stmt_group ();
6216 gnat_pushlevel ();
6217
6218 /* For a body, first process the spec if there is one. */
6219 if (Nkind (gnat_unit) == N_Package_Body
6220 || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
6221 add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
6222
6223 if (type_annotate_only && gnat_node == Cunit (Main_Unit))
6224 {
6225 elaborate_all_entities (gnat_node);
6226
6227 if (Nkind (gnat_unit) == N_Subprogram_Declaration
6228 || Nkind (gnat_unit) == N_Generic_Package_Declaration
6229 || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
6230 return;
6231 }
6232
6233 /* Then process any pragmas and declarations preceding the unit. */
6234 for (gnat_pragma = First (Context_Items (gnat_node));
6235 Present (gnat_pragma);
6236 gnat_pragma = Next (gnat_pragma))
6237 if (Nkind (gnat_pragma) == N_Pragma)
6238 add_stmt (gnat_to_gnu (gnat_pragma));
6239 process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
6240 true, true);
6241
6242 /* Process the unit itself. */
6243 add_stmt (gnat_to_gnu (gnat_unit));
6244
6245 /* Generate code for all the inlined subprograms. */
6246 for (gnat_entity = First_Inlined_Subprogram (gnat_node);
6247 Present (gnat_entity);
6248 gnat_entity = Next_Inlined_Subprogram (gnat_entity))
6249 {
6250 Node_Id gnat_body;
6251
6252 /* Without optimization, process only the required subprograms. */
6253 if (!optimize && !Has_Pragma_Inline_Always (gnat_entity))
6254 continue;
6255
6256 /* The set of inlined subprograms is computed from data recorded early
6257 during expansion and it can be a strict superset of the final set
6258 computed after semantic analysis, for example if a call to such a
6259 subprogram occurs in a pragma Assert and assertions are disabled.
6260 In that case, semantic analysis resets Is_Public to false but the
6261 entry for the subprogram in the inlining tables is stalled. */
6262 if (!Is_Public (gnat_entity))
6263 continue;
6264
6265 gnat_body = Parent (Declaration_Node (gnat_entity));
6266 if (Nkind (gnat_body) != N_Subprogram_Body)
6267 {
6268 /* ??? This happens when only the spec of a package is provided. */
6269 if (No (Corresponding_Body (gnat_body)))
6270 continue;
6271
6272 gnat_body
6273 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
6274 }
6275
6276 /* Define the entity first so we set DECL_EXTERNAL. */
6277 gnat_to_gnu_entity (gnat_entity, NULL_TREE, false);
6278 add_stmt (gnat_to_gnu (gnat_body));
6279 }
6280
6281 /* Process any pragmas and actions following the unit. */
6282 add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
6283 add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
6284 finalize_from_limited_with ();
6285
6286 /* Save away what we've made so far and finish it up. */
6287 set_current_block_context (gnu_elab_proc_decl);
6288 gnat_poplevel ();
6289 DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
6290 set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
6291 gnu_elab_proc_stack->pop ();
6292
6293 /* Record this potential elaboration procedure for later processing. */
6294 info = ggc_alloc<elab_info> ();
6295 info->next = elab_info_list;
6296 info->elab_proc = gnu_elab_proc_decl;
6297 info->gnat_node = gnat_node;
6298 elab_info_list = info;
6299
6300 /* Force the processing for all nodes that remain in the queue. */
6301 process_deferred_decl_context (true);
6302 }
6303 \f
6304 /* Mark COND, a boolean expression, as predicating a call to a noreturn
6305 function, i.e. predict that it is very likely false, and return it.
6306
6307 The compiler will automatically predict the last edge leading to a call
6308 to a noreturn function as very unlikely taken. This function makes it
6309 possible to expand the prediction to predecessors in case the condition
6310 is made up of several short-circuit operators. */
6311
6312 static tree
6313 build_noreturn_cond (tree cond)
6314 {
6315 tree fn = builtin_decl_explicit (BUILT_IN_EXPECT);
6316 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
6317 tree pred_type = TREE_VALUE (arg_types);
6318 tree expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
6319
6320 tree t = build_call_expr (fn, 3,
6321 fold_convert (pred_type, cond),
6322 build_int_cst (expected_type, 0),
6323 build_int_cst (integer_type_node,
6324 PRED_NORETURN));
6325
6326 return build1 (NOP_EXPR, boolean_type_node, t);
6327 }
6328
6329 /* Subroutine of gnat_to_gnu to translate GNAT_RANGE, a node representing a
6330 range of values, into GNU_LOW and GNU_HIGH bounds. */
6331
6332 static void
6333 Range_to_gnu (Node_Id gnat_range, tree *gnu_low, tree *gnu_high)
6334 {
6335 /* GNAT_RANGE is either an N_Range or an identifier denoting a subtype. */
6336 switch (Nkind (gnat_range))
6337 {
6338 case N_Range:
6339 *gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
6340 *gnu_high = gnat_to_gnu (High_Bound (gnat_range));
6341 break;
6342
6343 case N_Expanded_Name:
6344 case N_Identifier:
6345 {
6346 tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
6347 tree gnu_range_base_type = get_base_type (gnu_range_type);
6348
6349 *gnu_low
6350 = convert (gnu_range_base_type, TYPE_MIN_VALUE (gnu_range_type));
6351 *gnu_high
6352 = convert (gnu_range_base_type, TYPE_MAX_VALUE (gnu_range_type));
6353 }
6354 break;
6355
6356 default:
6357 gcc_unreachable ();
6358 }
6359 }
6360
6361 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Raise_xxx_Error,
6362 to a GCC tree and return it. GNU_RESULT_TYPE_P is a pointer to where
6363 we should place the result type. */
6364
6365 static tree
6366 Raise_Error_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
6367 {
6368 const Node_Kind kind = Nkind (gnat_node);
6369 const int reason = UI_To_Int (Reason (gnat_node));
6370 const Node_Id gnat_cond = Condition (gnat_node);
6371 const bool with_extra_info
6372 = Exception_Extra_Info
6373 && !No_Exception_Handlers_Set ()
6374 && No (get_exception_label (kind));
6375 tree gnu_result = NULL_TREE, gnu_cond = NULL_TREE;
6376
6377 /* The following processing is not required for correctness. Its purpose is
6378 to give more precise error messages and to record some information. */
6379 switch (reason)
6380 {
6381 case CE_Access_Check_Failed:
6382 if (with_extra_info)
6383 gnu_result = build_call_raise_column (reason, gnat_node, kind);
6384 break;
6385
6386 case CE_Index_Check_Failed:
6387 case CE_Range_Check_Failed:
6388 case CE_Invalid_Data:
6389 if (Present (gnat_cond) && Nkind (gnat_cond) == N_Op_Not)
6390 {
6391 Node_Id gnat_index, gnat_type;
6392 tree gnu_type, gnu_index, gnu_low_bound, gnu_high_bound, disp;
6393 bool neg_p;
6394 struct loop_info_d *loop;
6395
6396 switch (Nkind (Right_Opnd (gnat_cond)))
6397 {
6398 case N_In:
6399 Range_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)),
6400 &gnu_low_bound, &gnu_high_bound);
6401 break;
6402
6403 case N_Op_Ge:
6404 gnu_low_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
6405 gnu_high_bound = NULL_TREE;
6406 break;
6407
6408 case N_Op_Le:
6409 gnu_low_bound = NULL_TREE;
6410 gnu_high_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
6411 break;
6412
6413 default:
6414 goto common;
6415 }
6416
6417 gnat_index = Left_Opnd (Right_Opnd (gnat_cond));
6418 gnat_type = Etype (gnat_index);
6419 gnu_type = maybe_character_type (get_unpadded_type (gnat_type));
6420 gnu_index = gnat_to_gnu (gnat_index);
6421
6422 if (TREE_TYPE (gnu_index) != gnu_type)
6423 {
6424 if (gnu_low_bound)
6425 gnu_low_bound = convert (gnu_type, gnu_low_bound);
6426 if (gnu_high_bound)
6427 gnu_high_bound = convert (gnu_type, gnu_high_bound);
6428 gnu_index = convert (gnu_type, gnu_index);
6429 }
6430
6431 if (with_extra_info
6432 && gnu_low_bound
6433 && gnu_high_bound
6434 && Known_Esize (gnat_type)
6435 && UI_To_Int (Esize (gnat_type)) <= 32)
6436 gnu_result
6437 = build_call_raise_range (reason, gnat_node, kind, gnu_index,
6438 gnu_low_bound, gnu_high_bound);
6439
6440 /* If optimization is enabled and we are inside a loop, we try to
6441 compute invariant conditions for checks applied to the iteration
6442 variable, i.e. conditions that are independent of the variable
6443 and necessary in order for the checks to fail in the course of
6444 some iteration. If we succeed, we consider an alternative:
6445
6446 1. If loop unswitching is enabled, we prepend these conditions
6447 to the original conditions of the checks. This will make it
6448 possible for the loop unswitching pass to replace the loop
6449 with two loops, one of which has the checks eliminated and
6450 the other has the original checks reinstated, and a prologue
6451 implementing a run-time selection. The former loop will be
6452 for example suitable for vectorization.
6453
6454 2. Otherwise, we instead append the conditions to the original
6455 conditions of the checks. At worse, if the conditions cannot
6456 be evaluated at compile time, they will be evaluated as true
6457 at run time only when the checks have already failed, thus
6458 contributing negatively only to the size of the executable.
6459 But the hope is that these invariant conditions be evaluated
6460 at compile time to false, thus taking away the entire checks
6461 with them. */
6462 if (optimize
6463 && inside_loop_p ()
6464 && (!gnu_low_bound
6465 || (gnu_low_bound = gnat_invariant_expr (gnu_low_bound)))
6466 && (!gnu_high_bound
6467 || (gnu_high_bound = gnat_invariant_expr (gnu_high_bound)))
6468 && (loop = find_loop_for (gnu_index, &disp, &neg_p)))
6469 {
6470 struct range_check_info_d *rci = ggc_alloc<range_check_info_d> ();
6471 rci->low_bound = gnu_low_bound;
6472 rci->high_bound = gnu_high_bound;
6473 rci->disp = disp;
6474 rci->neg_p = neg_p;
6475 rci->type = gnu_type;
6476 rci->inserted_cond
6477 = build1 (SAVE_EXPR, boolean_type_node, boolean_true_node);
6478 vec_safe_push (loop->checks, rci);
6479 gnu_cond = build_noreturn_cond (gnat_to_gnu (gnat_cond));
6480 if (optimize >= 3)
6481 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
6482 boolean_type_node,
6483 rci->inserted_cond,
6484 gnu_cond);
6485 else
6486 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
6487 boolean_type_node,
6488 gnu_cond,
6489 rci->inserted_cond);
6490 }
6491 }
6492 break;
6493
6494 default:
6495 break;
6496 }
6497
6498 /* The following processing does the common work. */
6499 common:
6500 if (!gnu_result)
6501 gnu_result = build_call_raise (reason, gnat_node, kind);
6502 set_expr_location_from_node (gnu_result, gnat_node);
6503
6504 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
6505
6506 /* If the type is VOID, this is a statement, so we need to generate the code
6507 for the call. Handle a condition, if there is one. */
6508 if (VOID_TYPE_P (*gnu_result_type_p))
6509 {
6510 if (Present (gnat_cond))
6511 {
6512 if (!gnu_cond)
6513 gnu_cond = gnat_to_gnu (gnat_cond);
6514 gnu_result = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
6515 alloc_stmt_list ());
6516 }
6517 }
6518 else
6519 gnu_result = build1 (NULL_EXPR, *gnu_result_type_p, gnu_result);
6520
6521 return gnu_result;
6522 }
6523 \f
6524 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
6525 parameter of a call. */
6526
6527 static bool
6528 lhs_or_actual_p (Node_Id gnat_node)
6529 {
6530 Node_Id gnat_parent = Parent (gnat_node);
6531 Node_Kind kind = Nkind (gnat_parent);
6532
6533 if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
6534 return true;
6535
6536 if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
6537 && Name (gnat_parent) != gnat_node)
6538 return true;
6539
6540 if (kind == N_Parameter_Association)
6541 return true;
6542
6543 return false;
6544 }
6545
6546 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
6547 of an assignment or an actual parameter of a call. */
6548
6549 static bool
6550 present_in_lhs_or_actual_p (Node_Id gnat_node)
6551 {
6552 Node_Kind kind;
6553
6554 if (lhs_or_actual_p (gnat_node))
6555 return true;
6556
6557 kind = Nkind (Parent (gnat_node));
6558
6559 if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
6560 && lhs_or_actual_p (Parent (gnat_node)))
6561 return true;
6562
6563 return false;
6564 }
6565
6566 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
6567 as gigi is concerned. This is used to avoid conversions on the LHS. */
6568
6569 static bool
6570 unchecked_conversion_nop (Node_Id gnat_node)
6571 {
6572 Entity_Id from_type, to_type;
6573
6574 /* The conversion must be on the LHS of an assignment or an actual parameter
6575 of a call. Otherwise, even if the conversion was essentially a no-op, it
6576 could de facto ensure type consistency and this should be preserved. */
6577 if (!lhs_or_actual_p (gnat_node))
6578 return false;
6579
6580 from_type = Etype (Expression (gnat_node));
6581
6582 /* We're interested in artificial conversions generated by the front-end
6583 to make private types explicit, e.g. in Expand_Assign_Array. */
6584 if (!Is_Private_Type (from_type))
6585 return false;
6586
6587 from_type = Underlying_Type (from_type);
6588 to_type = Etype (gnat_node);
6589
6590 /* The direct conversion to the underlying type is a no-op. */
6591 if (to_type == from_type)
6592 return true;
6593
6594 /* For an array subtype, the conversion to the PAIT is a no-op. */
6595 if (Ekind (from_type) == E_Array_Subtype
6596 && to_type == Packed_Array_Impl_Type (from_type))
6597 return true;
6598
6599 /* For a record subtype, the conversion to the type is a no-op. */
6600 if (Ekind (from_type) == E_Record_Subtype
6601 && to_type == Etype (from_type))
6602 return true;
6603
6604 return false;
6605 }
6606
6607 /* Return true if GNAT_NODE represents a statement. */
6608
6609 static bool
6610 statement_node_p (Node_Id gnat_node)
6611 {
6612 const Node_Kind kind = Nkind (gnat_node);
6613
6614 if (kind == N_Label)
6615 return true;
6616
6617 if (IN (kind, N_Statement_Other_Than_Procedure_Call))
6618 return true;
6619
6620 if (kind == N_Procedure_Call_Statement)
6621 return true;
6622
6623 if (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void)
6624 return true;
6625
6626 return false;
6627 }
6628
6629 /* This function is the driver of the GNAT to GCC tree transformation process.
6630 It is the entry point of the tree transformer. GNAT_NODE is the root of
6631 some GNAT tree. Return the root of the corresponding GCC tree. If this
6632 is an expression, return the GCC equivalent of the expression. If this
6633 is a statement, return the statement or add it to the current statement
6634 group, in which case anything returned is to be interpreted as occurring
6635 after anything added. */
6636
6637 tree
6638 gnat_to_gnu (Node_Id gnat_node)
6639 {
6640 const Node_Kind kind = Nkind (gnat_node);
6641 bool went_into_elab_proc = false;
6642 tree gnu_result = error_mark_node; /* Default to no value. */
6643 tree gnu_result_type = void_type_node;
6644 tree gnu_expr, gnu_lhs, gnu_rhs;
6645 Node_Id gnat_temp;
6646 bool sync = false;
6647
6648 /* Save node number for error message and set location information. */
6649 Current_Error_Node = gnat_node;
6650 Sloc_to_locus (Sloc (gnat_node), &input_location);
6651
6652 /* If we are only annotating types and this node is a statement, return
6653 an empty statement list. */
6654 if (type_annotate_only && statement_node_p (gnat_node))
6655 return alloc_stmt_list ();
6656
6657 /* If we are only annotating types and this node is a subexpression, return
6658 a NULL_EXPR, but filter out nodes appearing in the expressions attached
6659 to packed array implementation types. */
6660 if (type_annotate_only
6661 && IN (kind, N_Subexpr)
6662 && !(((IN (kind, N_Op) && kind != N_Op_Expon)
6663 || kind == N_Type_Conversion)
6664 && Is_Integer_Type (Etype (gnat_node)))
6665 && !(kind == N_Attribute_Reference
6666 && (Get_Attribute_Id (Attribute_Name (gnat_node)) == Attr_Length
6667 || Get_Attribute_Id (Attribute_Name (gnat_node)) == Attr_Size)
6668 && Is_Constrained (Etype (Prefix (gnat_node)))
6669 && !Is_Constr_Subt_For_U_Nominal (Etype (Prefix (gnat_node))))
6670 && kind != N_Expanded_Name
6671 && kind != N_Identifier
6672 && !Compile_Time_Known_Value (gnat_node))
6673 return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
6674 build_call_raise (CE_Range_Check_Failed, gnat_node,
6675 N_Raise_Constraint_Error));
6676
6677 if ((statement_node_p (gnat_node) && kind != N_Null_Statement)
6678 || kind == N_Handled_Sequence_Of_Statements
6679 || kind == N_Implicit_Label_Declaration)
6680 {
6681 tree current_elab_proc = get_elaboration_procedure ();
6682
6683 /* If this is a statement and we are at top level, it must be part of
6684 the elaboration procedure, so mark us as being in that procedure. */
6685 if (!current_function_decl)
6686 {
6687 current_function_decl = current_elab_proc;
6688 went_into_elab_proc = true;
6689 }
6690
6691 /* If we are in the elaboration procedure, check if we are violating a
6692 No_Elaboration_Code restriction by having a statement there. Don't
6693 check for a possible No_Elaboration_Code restriction violation on
6694 N_Handled_Sequence_Of_Statements, as we want to signal an error on
6695 every nested real statement instead. This also avoids triggering
6696 spurious errors on dummy (empty) sequences created by the front-end
6697 for package bodies in some cases. */
6698 if (current_function_decl == current_elab_proc
6699 && kind != N_Handled_Sequence_Of_Statements
6700 && kind != N_Implicit_Label_Declaration)
6701 Check_Elaboration_Code_Allowed (gnat_node);
6702 }
6703
6704 switch (kind)
6705 {
6706 /********************************/
6707 /* Chapter 2: Lexical Elements */
6708 /********************************/
6709
6710 case N_Identifier:
6711 case N_Expanded_Name:
6712 case N_Operator_Symbol:
6713 case N_Defining_Identifier:
6714 case N_Defining_Operator_Symbol:
6715 gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
6716
6717 /* If atomic access is required on the RHS, build the atomic load. */
6718 if (atomic_access_required_p (gnat_node, &sync)
6719 && !present_in_lhs_or_actual_p (gnat_node))
6720 gnu_result = build_atomic_load (gnu_result, sync);
6721 break;
6722
6723 case N_Integer_Literal:
6724 {
6725 tree gnu_type;
6726
6727 /* Get the type of the result, looking inside any padding and
6728 justified modular types. Then get the value in that type. */
6729 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6730
6731 if (TREE_CODE (gnu_type) == RECORD_TYPE
6732 && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
6733 gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
6734
6735 gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
6736
6737 /* If the result overflows (meaning it doesn't fit in its base type),
6738 abort. We would like to check that the value is within the range
6739 of the subtype, but that causes problems with subtypes whose usage
6740 will raise Constraint_Error and with biased representation, so
6741 we don't. */
6742 gcc_assert (!TREE_OVERFLOW (gnu_result));
6743 }
6744 break;
6745
6746 case N_Character_Literal:
6747 /* If a Entity is present, it means that this was one of the
6748 literals in a user-defined character type. In that case,
6749 just return the value in the CONST_DECL. Otherwise, use the
6750 character code. In that case, the base type should be an
6751 INTEGER_TYPE, but we won't bother checking for that. */
6752 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6753 if (Present (Entity (gnat_node)))
6754 gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
6755 else
6756 gnu_result
6757 = build_int_cst (gnu_result_type,
6758 UI_To_CC (Char_Literal_Value (gnat_node)));
6759 break;
6760
6761 case N_Real_Literal:
6762 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6763
6764 /* If this is of a fixed-point type, the value we want is the value of
6765 the corresponding integer. */
6766 if (Is_Fixed_Point_Type (Underlying_Type (Etype (gnat_node))))
6767 {
6768 gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
6769 gnu_result_type);
6770 gcc_assert (!TREE_OVERFLOW (gnu_result));
6771 }
6772
6773 else
6774 {
6775 Ureal ur_realval = Realval (gnat_node);
6776
6777 /* First convert the value to a machine number if it isn't already.
6778 That will force the base to 2 for non-zero values and simplify
6779 the rest of the logic. */
6780 if (!Is_Machine_Number (gnat_node))
6781 ur_realval
6782 = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
6783 ur_realval, Round_Even, gnat_node);
6784
6785 if (UR_Is_Zero (ur_realval))
6786 gnu_result = build_real (gnu_result_type, dconst0);
6787 else
6788 {
6789 REAL_VALUE_TYPE tmp;
6790
6791 gnu_result = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
6792
6793 /* The base must be 2 as Machine guarantees this, so we scale
6794 the value, which we know can fit in the mantissa of the type
6795 (hence the use of that type above). */
6796 gcc_assert (Rbase (ur_realval) == 2);
6797 real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
6798 - UI_To_Int (Denominator (ur_realval)));
6799 gnu_result = build_real (gnu_result_type, tmp);
6800 }
6801
6802 /* Now see if we need to negate the result. Do it this way to
6803 properly handle -0. */
6804 if (UR_Is_Negative (Realval (gnat_node)))
6805 gnu_result
6806 = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
6807 gnu_result);
6808 }
6809
6810 break;
6811
6812 case N_String_Literal:
6813 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6814 if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
6815 {
6816 String_Id gnat_string = Strval (gnat_node);
6817 int length = String_Length (gnat_string);
6818 int i;
6819 char *string;
6820 if (length >= ALLOCA_THRESHOLD)
6821 string = XNEWVEC (char, length + 1);
6822 else
6823 string = (char *) alloca (length + 1);
6824
6825 /* Build the string with the characters in the literal. Note
6826 that Ada strings are 1-origin. */
6827 for (i = 0; i < length; i++)
6828 string[i] = Get_String_Char (gnat_string, i + 1);
6829
6830 /* Put a null at the end of the string in case it's in a context
6831 where GCC will want to treat it as a C string. */
6832 string[i] = 0;
6833
6834 gnu_result = build_string (length, string);
6835
6836 /* Strings in GCC don't normally have types, but we want
6837 this to not be converted to the array type. */
6838 TREE_TYPE (gnu_result) = gnu_result_type;
6839
6840 if (length >= ALLOCA_THRESHOLD)
6841 free (string);
6842 }
6843 else
6844 {
6845 /* Build a list consisting of each character, then make
6846 the aggregate. */
6847 String_Id gnat_string = Strval (gnat_node);
6848 int length = String_Length (gnat_string);
6849 int i;
6850 tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
6851 tree gnu_one_node = convert (TREE_TYPE (gnu_idx), integer_one_node);
6852 vec<constructor_elt, va_gc> *gnu_vec;
6853 vec_alloc (gnu_vec, length);
6854
6855 for (i = 0; i < length; i++)
6856 {
6857 tree t = build_int_cst (TREE_TYPE (gnu_result_type),
6858 Get_String_Char (gnat_string, i + 1));
6859
6860 CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
6861 gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, gnu_one_node);
6862 }
6863
6864 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
6865 }
6866 break;
6867
6868 case N_Pragma:
6869 gnu_result = Pragma_to_gnu (gnat_node);
6870 break;
6871
6872 /**************************************/
6873 /* Chapter 3: Declarations and Types */
6874 /**************************************/
6875
6876 case N_Subtype_Declaration:
6877 case N_Full_Type_Declaration:
6878 case N_Incomplete_Type_Declaration:
6879 case N_Private_Type_Declaration:
6880 case N_Private_Extension_Declaration:
6881 case N_Task_Type_Declaration:
6882 process_type (Defining_Entity (gnat_node));
6883 gnu_result = alloc_stmt_list ();
6884 break;
6885
6886 case N_Object_Declaration:
6887 case N_Exception_Declaration:
6888 gnat_temp = Defining_Entity (gnat_node);
6889 gnu_result = alloc_stmt_list ();
6890
6891 /* If we are just annotating types and this object has an unconstrained
6892 or task type, don't elaborate it. */
6893 if (type_annotate_only
6894 && (((Is_Array_Type (Etype (gnat_temp))
6895 || Is_Record_Type (Etype (gnat_temp)))
6896 && !Is_Constrained (Etype (gnat_temp)))
6897 || Is_Concurrent_Type (Etype (gnat_temp))))
6898 break;
6899
6900 if (Present (Expression (gnat_node))
6901 && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
6902 && (!type_annotate_only
6903 || Compile_Time_Known_Value (Expression (gnat_node))))
6904 {
6905 gnu_expr = gnat_to_gnu (Expression (gnat_node));
6906 if (Do_Range_Check (Expression (gnat_node)))
6907 gnu_expr
6908 = emit_range_check (gnu_expr, Etype (gnat_temp), gnat_node);
6909
6910 if (type_annotate_only && TREE_CODE (gnu_expr) == ERROR_MARK)
6911 gnu_expr = NULL_TREE;
6912 }
6913 else
6914 gnu_expr = NULL_TREE;
6915
6916 /* If this is a deferred constant with an address clause, we ignore the
6917 full view since the clause is on the partial view and we cannot have
6918 2 different GCC trees for the object. The only bits of the full view
6919 we will use is the initializer, but it will be directly fetched. */
6920 if (Ekind (gnat_temp) == E_Constant
6921 && Present (Address_Clause (gnat_temp))
6922 && Present (Full_View (gnat_temp)))
6923 save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
6924
6925 /* If this object has its elaboration delayed, we must force evaluation
6926 of GNU_EXPR now and save it for the freeze point. Note that we need
6927 not do anything special at the global level since the lifetime of the
6928 temporary is fully contained within the elaboration routine. */
6929 if (Present (Freeze_Node (gnat_temp)))
6930 {
6931 if (gnu_expr)
6932 {
6933 gnu_result = gnat_save_expr (gnu_expr);
6934 save_gnu_tree (gnat_node, gnu_result, true);
6935 }
6936 }
6937 else
6938 gnat_to_gnu_entity (gnat_temp, gnu_expr, true);
6939 break;
6940
6941 case N_Object_Renaming_Declaration:
6942 gnat_temp = Defining_Entity (gnat_node);
6943 gnu_result = alloc_stmt_list ();
6944
6945 /* Don't do anything if this renaming is handled by the front end and it
6946 does not need debug info. Note that we consider renamings don't need
6947 debug info when optimizing: our way to describe them has a
6948 memory/elaboration footprint.
6949
6950 Don't do anything neither if we are just annotating types and this
6951 object has a composite or task type, don't elaborate it. */
6952 if ((!Is_Renaming_Of_Object (gnat_temp)
6953 || (Needs_Debug_Info (gnat_temp)
6954 && !optimize
6955 && can_materialize_object_renaming_p
6956 (Renamed_Object (gnat_temp))))
6957 && ! (type_annotate_only
6958 && (Is_Array_Type (Etype (gnat_temp))
6959 || Is_Record_Type (Etype (gnat_temp))
6960 || Is_Concurrent_Type (Etype (gnat_temp)))))
6961 {
6962 tree gnu_temp
6963 = gnat_to_gnu_entity (gnat_temp,
6964 gnat_to_gnu (Renamed_Object (gnat_temp)),
6965 true);
6966 /* See case 2 of renaming in gnat_to_gnu_entity. */
6967 if (TREE_SIDE_EFFECTS (gnu_temp))
6968 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_temp);
6969 }
6970 break;
6971
6972 case N_Exception_Renaming_Declaration:
6973 gnat_temp = Defining_Entity (gnat_node);
6974 gnu_result = alloc_stmt_list ();
6975
6976 /* See the above case for the rationale. */
6977 if (Present (Renamed_Entity (gnat_temp)))
6978 {
6979 tree gnu_temp
6980 = gnat_to_gnu_entity (gnat_temp,
6981 gnat_to_gnu (Renamed_Entity (gnat_temp)),
6982 true);
6983 if (TREE_SIDE_EFFECTS (gnu_temp))
6984 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_temp);
6985 }
6986 break;
6987
6988 case N_Subprogram_Renaming_Declaration:
6989 {
6990 const Node_Id gnat_renaming = Defining_Entity (gnat_node);
6991 const Node_Id gnat_renamed = Renamed_Entity (gnat_renaming);
6992
6993 gnu_result = alloc_stmt_list ();
6994
6995 /* Materializing renamed subprograms will only benefit the debugging
6996 information as they aren't referenced in the generated code. So
6997 skip them when they aren't needed. Avoid doing this if:
6998
6999 - there is a freeze node: in this case the renamed entity is not
7000 elaborated yet,
7001 - the renamed subprogram is intrinsic: it will not be available in
7002 the debugging information (note that both or only one of the
7003 renaming and the renamed subprograms can be intrinsic). */
7004 if (!type_annotate_only
7005 && Needs_Debug_Info (gnat_renaming)
7006 && No (Freeze_Node (gnat_renaming))
7007 && Present (gnat_renamed)
7008 && (Ekind (gnat_renamed) == E_Function
7009 || Ekind (gnat_renamed) == E_Procedure)
7010 && !Is_Intrinsic_Subprogram (gnat_renaming)
7011 && !Is_Intrinsic_Subprogram (gnat_renamed))
7012 gnat_to_gnu_entity (gnat_renaming, gnat_to_gnu (gnat_renamed), true);
7013 break;
7014 }
7015
7016 case N_Implicit_Label_Declaration:
7017 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, true);
7018 gnu_result = alloc_stmt_list ();
7019 break;
7020
7021 case N_Number_Declaration:
7022 case N_Package_Renaming_Declaration:
7023 /* These are fully handled in the front end. */
7024 /* ??? For package renamings, find a way to use GENERIC namespaces so
7025 that we get proper debug information for them. */
7026 gnu_result = alloc_stmt_list ();
7027 break;
7028
7029 /*************************************/
7030 /* Chapter 4: Names and Expressions */
7031 /*************************************/
7032
7033 case N_Explicit_Dereference:
7034 /* Make sure the designated type is complete before dereferencing. */
7035 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7036 gnu_result = gnat_to_gnu (Prefix (gnat_node));
7037 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
7038
7039 /* If atomic access is required on the RHS, build the atomic load. */
7040 if (atomic_access_required_p (gnat_node, &sync)
7041 && !present_in_lhs_or_actual_p (gnat_node))
7042 gnu_result = build_atomic_load (gnu_result, sync);
7043 break;
7044
7045 case N_Indexed_Component:
7046 {
7047 tree gnu_array_object
7048 = gnat_to_gnu (adjust_for_implicit_deref (Prefix (gnat_node)));
7049 tree gnu_type;
7050 int ndim;
7051 int i;
7052 Node_Id *gnat_expr_array;
7053
7054 gnu_array_object = maybe_implicit_deref (gnu_array_object);
7055
7056 /* Convert vector inputs to their representative array type, to fit
7057 what the code below expects. */
7058 if (VECTOR_TYPE_P (TREE_TYPE (gnu_array_object)))
7059 {
7060 if (present_in_lhs_or_actual_p (gnat_node))
7061 gnat_mark_addressable (gnu_array_object);
7062 gnu_array_object = maybe_vector_array (gnu_array_object);
7063 }
7064
7065 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
7066
7067 /* If we got a padded type, remove it too. */
7068 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
7069 gnu_array_object
7070 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
7071 gnu_array_object);
7072
7073 /* The failure of this assertion will very likely come from a missing
7074 expansion for a packed array access. */
7075 gcc_assert (TREE_CODE (TREE_TYPE (gnu_array_object)) == ARRAY_TYPE);
7076
7077 /* First compute the number of dimensions of the array, then
7078 fill the expression array, the order depending on whether
7079 this is a Convention_Fortran array or not. */
7080 for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
7081 TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
7082 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
7083 ndim++, gnu_type = TREE_TYPE (gnu_type))
7084 ;
7085
7086 gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
7087
7088 if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
7089 for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
7090 i >= 0;
7091 i--, gnat_temp = Next (gnat_temp))
7092 gnat_expr_array[i] = gnat_temp;
7093 else
7094 for (i = 0, gnat_temp = First (Expressions (gnat_node));
7095 i < ndim;
7096 i++, gnat_temp = Next (gnat_temp))
7097 gnat_expr_array[i] = gnat_temp;
7098
7099 /* Start with the prefix and build the successive references. */
7100 gnu_result = gnu_array_object;
7101
7102 for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
7103 i < ndim;
7104 i++, gnu_type = TREE_TYPE (gnu_type))
7105 {
7106 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
7107 gnat_temp = gnat_expr_array[i];
7108 gnu_expr = maybe_character_value (gnat_to_gnu (gnat_temp));
7109
7110 gnu_result
7111 = build_binary_op (ARRAY_REF, NULL_TREE, gnu_result, gnu_expr);
7112 }
7113
7114 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7115
7116 /* If atomic access is required on the RHS, build the atomic load. */
7117 if (atomic_access_required_p (gnat_node, &sync)
7118 && !present_in_lhs_or_actual_p (gnat_node))
7119 gnu_result = build_atomic_load (gnu_result, sync);
7120 }
7121 break;
7122
7123 case N_Slice:
7124 {
7125 tree gnu_array_object
7126 = gnat_to_gnu (adjust_for_implicit_deref (Prefix (gnat_node)));
7127
7128 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7129
7130 gnu_array_object = maybe_implicit_deref (gnu_array_object);
7131 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
7132
7133 gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
7134 gnu_expr = maybe_character_value (gnu_expr);
7135
7136 /* If this is a slice with non-constant size of an array with constant
7137 size, set the maximum size for the allocation of temporaries. */
7138 if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
7139 && TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (gnu_array_object))))
7140 TYPE_ARRAY_MAX_SIZE (gnu_result_type)
7141 = TYPE_SIZE_UNIT (TREE_TYPE (gnu_array_object));
7142
7143 gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
7144 gnu_array_object, gnu_expr);
7145 }
7146 break;
7147
7148 case N_Selected_Component:
7149 {
7150 Entity_Id gnat_prefix
7151 = adjust_for_implicit_deref (Prefix (gnat_node));
7152 Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
7153 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
7154
7155 gnu_prefix = maybe_implicit_deref (gnu_prefix);
7156
7157 /* gnat_to_gnu_entity does not save the GNU tree made for renamed
7158 discriminants so avoid making recursive calls on each reference
7159 to them by following the appropriate link directly here. */
7160 if (Ekind (gnat_field) == E_Discriminant)
7161 {
7162 /* For discriminant references in tagged types always substitute
7163 the corresponding discriminant as the actual component. */
7164 if (Is_Tagged_Type (Underlying_Type (Etype (gnat_prefix))))
7165 while (Present (Corresponding_Discriminant (gnat_field)))
7166 gnat_field = Corresponding_Discriminant (gnat_field);
7167
7168 /* For discriminant references in untagged types always substitute
7169 the corresponding stored discriminant. */
7170 else if (Present (Corresponding_Discriminant (gnat_field)))
7171 gnat_field = Original_Record_Component (gnat_field);
7172 }
7173
7174 /* Handle extracting the real or imaginary part of a complex.
7175 The real part is the first field and the imaginary the last. */
7176 if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
7177 gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
7178 ? REALPART_EXPR : IMAGPART_EXPR,
7179 NULL_TREE, gnu_prefix);
7180 else
7181 {
7182 tree gnu_field = gnat_to_gnu_field_decl (gnat_field);
7183
7184 gnu_result
7185 = build_component_ref (gnu_prefix, gnu_field,
7186 (Nkind (Parent (gnat_node))
7187 == N_Attribute_Reference)
7188 && lvalue_required_for_attribute_p
7189 (Parent (gnat_node)));
7190 }
7191
7192 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7193
7194 /* If atomic access is required on the RHS, build the atomic load. */
7195 if (atomic_access_required_p (gnat_node, &sync)
7196 && !present_in_lhs_or_actual_p (gnat_node))
7197 gnu_result = build_atomic_load (gnu_result, sync);
7198 }
7199 break;
7200
7201 case N_Attribute_Reference:
7202 {
7203 /* The attribute designator. */
7204 const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
7205
7206 /* The Elab_Spec and Elab_Body attributes are special in that Prefix
7207 is a unit, not an object with a GCC equivalent. */
7208 if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
7209 return
7210 create_subprog_decl (create_concat_name
7211 (Entity (Prefix (gnat_node)),
7212 attr == Attr_Elab_Body ? "elabb" : "elabs"),
7213 NULL_TREE, void_ftype, NULL_TREE, is_default,
7214 true, true, true, true, false, NULL,
7215 gnat_node);
7216
7217 gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
7218 }
7219 break;
7220
7221 case N_Reference:
7222 /* Like 'Access as far as we are concerned. */
7223 gnu_result = gnat_to_gnu (Prefix (gnat_node));
7224 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
7225 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7226 break;
7227
7228 case N_Aggregate:
7229 case N_Extension_Aggregate:
7230 {
7231 tree gnu_aggr_type;
7232
7233 /* Check that this aggregate has not slipped through the cracks. */
7234 gcc_assert (!Expansion_Delayed (gnat_node));
7235
7236 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7237
7238 if (TREE_CODE (gnu_result_type) == RECORD_TYPE
7239 && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
7240 gnu_aggr_type
7241 = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
7242 else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
7243 gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
7244 else
7245 gnu_aggr_type = gnu_result_type;
7246
7247 if (Null_Record_Present (gnat_node))
7248 gnu_result = gnat_build_constructor (gnu_aggr_type, NULL);
7249
7250 else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
7251 || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
7252 gnu_result
7253 = assoc_to_constructor (Etype (gnat_node),
7254 First (Component_Associations (gnat_node)),
7255 gnu_aggr_type);
7256 else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
7257 gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
7258 gnu_aggr_type,
7259 Component_Type (Etype (gnat_node)));
7260 else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
7261 gnu_result
7262 = build_binary_op
7263 (COMPLEX_EXPR, gnu_aggr_type,
7264 gnat_to_gnu (Expression (First
7265 (Component_Associations (gnat_node)))),
7266 gnat_to_gnu (Expression
7267 (Next
7268 (First (Component_Associations (gnat_node))))));
7269 else
7270 gcc_unreachable ();
7271
7272 gnu_result = convert (gnu_result_type, gnu_result);
7273 }
7274 break;
7275
7276 case N_Null:
7277 if (TARGET_VTABLE_USES_DESCRIPTORS
7278 && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
7279 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
7280 gnu_result = null_fdesc_node;
7281 else
7282 gnu_result = null_pointer_node;
7283 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7284 break;
7285
7286 case N_Type_Conversion:
7287 case N_Qualified_Expression:
7288 gnu_expr = maybe_character_value (gnat_to_gnu (Expression (gnat_node)));
7289 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7290
7291 /* If this is a qualified expression for a tagged type, we mark the type
7292 as used. Because of polymorphism, this might be the only reference to
7293 the tagged type in the program while objects have it as dynamic type.
7294 The debugger needs to see it to display these objects properly. */
7295 if (kind == N_Qualified_Expression && Is_Tagged_Type (Etype (gnat_node)))
7296 used_types_insert (gnu_result_type);
7297
7298 gnu_result
7299 = convert_with_check (Etype (gnat_node), gnu_expr,
7300 Do_Overflow_Check (gnat_node),
7301 Do_Range_Check (Expression (gnat_node)),
7302 kind == N_Type_Conversion
7303 && Float_Truncate (gnat_node), gnat_node);
7304 break;
7305
7306 case N_Unchecked_Type_Conversion:
7307 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7308 gnu_expr = maybe_character_value (gnat_to_gnu (Expression (gnat_node)));
7309
7310 /* Skip further processing if the conversion is deemed a no-op. */
7311 if (unchecked_conversion_nop (gnat_node))
7312 {
7313 gnu_result = gnu_expr;
7314 gnu_result_type = TREE_TYPE (gnu_result);
7315 break;
7316 }
7317
7318 /* If the result is a pointer type, see if we are improperly
7319 converting to a stricter alignment. */
7320 if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
7321 && Is_Access_Type (Etype (gnat_node)))
7322 {
7323 unsigned int align = known_alignment (gnu_expr);
7324 tree gnu_obj_type = TREE_TYPE (gnu_result_type);
7325 unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
7326
7327 if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
7328 post_error_ne_tree_2
7329 ("?source alignment (^) '< alignment of & (^)",
7330 gnat_node, Designated_Type (Etype (gnat_node)),
7331 size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
7332 }
7333
7334 /* If we are converting a descriptor to a function pointer, first
7335 build the pointer. */
7336 if (TARGET_VTABLE_USES_DESCRIPTORS
7337 && TREE_TYPE (gnu_expr) == fdesc_type_node
7338 && POINTER_TYPE_P (gnu_result_type))
7339 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
7340
7341 gnu_result = unchecked_convert (gnu_result_type, gnu_expr,
7342 No_Truncation (gnat_node));
7343 break;
7344
7345 case N_In:
7346 case N_Not_In:
7347 {
7348 tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
7349 tree gnu_low, gnu_high;
7350
7351 Range_to_gnu (Right_Opnd (gnat_node), &gnu_low, &gnu_high);
7352 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7353
7354 tree gnu_op_type = maybe_character_type (TREE_TYPE (gnu_obj));
7355 if (TREE_TYPE (gnu_obj) != gnu_op_type)
7356 {
7357 gnu_obj = convert (gnu_op_type, gnu_obj);
7358 gnu_low = convert (gnu_op_type, gnu_low);
7359 gnu_high = convert (gnu_op_type, gnu_high);
7360 }
7361
7362 /* If LOW and HIGH are identical, perform an equality test. Otherwise,
7363 ensure that GNU_OBJ is evaluated only once and perform a full range
7364 test. */
7365 if (operand_equal_p (gnu_low, gnu_high, 0))
7366 gnu_result
7367 = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
7368 else
7369 {
7370 tree t1, t2;
7371 gnu_obj = gnat_protect_expr (gnu_obj);
7372 t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
7373 if (EXPR_P (t1))
7374 set_expr_location_from_node (t1, gnat_node);
7375 t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
7376 if (EXPR_P (t2))
7377 set_expr_location_from_node (t2, gnat_node);
7378 gnu_result
7379 = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
7380 }
7381
7382 if (kind == N_Not_In)
7383 gnu_result
7384 = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
7385 }
7386 break;
7387
7388 case N_Op_Divide:
7389 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
7390 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
7391 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7392 gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
7393 ? RDIV_EXPR
7394 : (Rounded_Result (gnat_node)
7395 ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
7396 gnu_result_type, gnu_lhs, gnu_rhs);
7397 break;
7398
7399 case N_Op_Eq:
7400 case N_Op_Ne:
7401 case N_Op_Lt:
7402 case N_Op_Le:
7403 case N_Op_Gt:
7404 case N_Op_Ge:
7405 case N_Op_Add:
7406 case N_Op_Subtract:
7407 case N_Op_Multiply:
7408 case N_Op_Mod:
7409 case N_Op_Rem:
7410 case N_Op_Rotate_Left:
7411 case N_Op_Rotate_Right:
7412 case N_Op_Shift_Left:
7413 case N_Op_Shift_Right:
7414 case N_Op_Shift_Right_Arithmetic:
7415 case N_Op_And:
7416 case N_Op_Or:
7417 case N_Op_Xor:
7418 case N_And_Then:
7419 case N_Or_Else:
7420 {
7421 enum tree_code code = gnu_codes[kind];
7422 bool ignore_lhs_overflow = false;
7423 location_t saved_location = input_location;
7424 tree gnu_type;
7425
7426 /* Fix operations set up for boolean types in GNU_CODES above. */
7427 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
7428 switch (kind)
7429 {
7430 case N_Op_And:
7431 code = BIT_AND_EXPR;
7432 break;
7433 case N_Op_Or:
7434 code = BIT_IOR_EXPR;
7435 break;
7436 case N_Op_Xor:
7437 code = BIT_XOR_EXPR;
7438 break;
7439 default:
7440 break;
7441 }
7442
7443 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
7444 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
7445 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
7446
7447 /* Pending generic support for efficient vector logical operations in
7448 GCC, convert vectors to their representative array type view and
7449 fallthrough. */
7450 gnu_lhs = maybe_vector_array (gnu_lhs);
7451 gnu_rhs = maybe_vector_array (gnu_rhs);
7452
7453 /* If this is a comparison operator, convert any references to an
7454 unconstrained array value into a reference to the actual array. */
7455 if (TREE_CODE_CLASS (code) == tcc_comparison)
7456 {
7457 gnu_lhs = maybe_unconstrained_array (gnu_lhs);
7458 gnu_rhs = maybe_unconstrained_array (gnu_rhs);
7459
7460 tree gnu_op_type = maybe_character_type (TREE_TYPE (gnu_lhs));
7461 if (TREE_TYPE (gnu_lhs) != gnu_op_type)
7462 {
7463 gnu_lhs = convert (gnu_op_type, gnu_lhs);
7464 gnu_rhs = convert (gnu_op_type, gnu_rhs);
7465 }
7466 }
7467
7468 /* If this is a shift whose count is not guaranteed to be correct,
7469 we need to adjust the shift count. */
7470 if (IN (kind, N_Op_Shift) && !Shift_Count_OK (gnat_node))
7471 {
7472 tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
7473 tree gnu_max_shift
7474 = convert (gnu_count_type, TYPE_SIZE (gnu_type));
7475
7476 if (kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
7477 gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
7478 gnu_rhs, gnu_max_shift);
7479 else if (kind == N_Op_Shift_Right_Arithmetic)
7480 gnu_rhs
7481 = build_binary_op
7482 (MIN_EXPR, gnu_count_type,
7483 build_binary_op (MINUS_EXPR,
7484 gnu_count_type,
7485 gnu_max_shift,
7486 build_int_cst (gnu_count_type, 1)),
7487 gnu_rhs);
7488 }
7489
7490 /* For right shifts, the type says what kind of shift to do,
7491 so we may need to choose a different type. In this case,
7492 we have to ignore integer overflow lest it propagates all
7493 the way down and causes a CE to be explicitly raised. */
7494 if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
7495 {
7496 gnu_type = gnat_unsigned_type_for (gnu_type);
7497 ignore_lhs_overflow = true;
7498 }
7499 else if (kind == N_Op_Shift_Right_Arithmetic
7500 && TYPE_UNSIGNED (gnu_type))
7501 {
7502 gnu_type = gnat_signed_type_for (gnu_type);
7503 ignore_lhs_overflow = true;
7504 }
7505
7506 if (gnu_type != gnu_result_type)
7507 {
7508 tree gnu_old_lhs = gnu_lhs;
7509 gnu_lhs = convert (gnu_type, gnu_lhs);
7510 if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
7511 TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
7512 gnu_rhs = convert (gnu_type, gnu_rhs);
7513 }
7514
7515 /* Instead of expanding overflow checks for addition, subtraction
7516 and multiplication itself, the front end will leave this to
7517 the back end when Backend_Overflow_Checks_On_Target is set. */
7518 if (Do_Overflow_Check (gnat_node)
7519 && Backend_Overflow_Checks_On_Target
7520 && (code == PLUS_EXPR || code == MINUS_EXPR || code == MULT_EXPR)
7521 && !TYPE_UNSIGNED (gnu_type)
7522 && !FLOAT_TYPE_P (gnu_type))
7523 gnu_result = build_binary_op_trapv (code, gnu_type,
7524 gnu_lhs, gnu_rhs, gnat_node);
7525 else
7526 {
7527 /* Some operations, e.g. comparisons of arrays, generate complex
7528 trees that need to be annotated while they are being built. */
7529 input_location = saved_location;
7530 gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
7531 }
7532
7533 /* If this is a logical shift with the shift count not verified,
7534 we must return zero if it is too large. We cannot compensate
7535 above in this case. */
7536 if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
7537 && !Shift_Count_OK (gnat_node))
7538 gnu_result
7539 = build_cond_expr
7540 (gnu_type,
7541 build_binary_op (GE_EXPR, boolean_type_node,
7542 gnu_rhs,
7543 convert (TREE_TYPE (gnu_rhs),
7544 TYPE_SIZE (gnu_type))),
7545 build_int_cst (gnu_type, 0),
7546 gnu_result);
7547 }
7548 break;
7549
7550 case N_If_Expression:
7551 {
7552 tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
7553 tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
7554 tree gnu_false
7555 = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
7556
7557 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7558 gnu_result
7559 = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
7560 }
7561 break;
7562
7563 case N_Op_Plus:
7564 gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
7565 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7566 break;
7567
7568 case N_Op_Not:
7569 /* This case can apply to a boolean or a modular type.
7570 Fall through for a boolean operand since GNU_CODES is set
7571 up to handle this. */
7572 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
7573 {
7574 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
7575 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7576 gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
7577 gnu_expr);
7578 break;
7579 }
7580
7581 /* ... fall through ... */
7582
7583 case N_Op_Minus:
7584 case N_Op_Abs:
7585 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
7586 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7587
7588 /* Instead of expanding overflow checks for negation and absolute
7589 value itself, the front end will leave this to the back end
7590 when Backend_Overflow_Checks_On_Target is set. */
7591 if (Do_Overflow_Check (gnat_node)
7592 && Backend_Overflow_Checks_On_Target
7593 && !TYPE_UNSIGNED (gnu_result_type)
7594 && !FLOAT_TYPE_P (gnu_result_type))
7595 gnu_result
7596 = build_unary_op_trapv (gnu_codes[kind],
7597 gnu_result_type, gnu_expr, gnat_node);
7598 else
7599 gnu_result = build_unary_op (gnu_codes[kind],
7600 gnu_result_type, gnu_expr);
7601 break;
7602
7603 case N_Allocator:
7604 {
7605 tree gnu_init = NULL_TREE;
7606 tree gnu_type;
7607 bool ignore_init_type = false;
7608
7609 gnat_temp = Expression (gnat_node);
7610
7611 /* The Expression operand can either be an N_Identifier or
7612 Expanded_Name, which must represent a type, or a
7613 N_Qualified_Expression, which contains both the object type and an
7614 initial value for the object. */
7615 if (Nkind (gnat_temp) == N_Identifier
7616 || Nkind (gnat_temp) == N_Expanded_Name)
7617 gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
7618 else if (Nkind (gnat_temp) == N_Qualified_Expression)
7619 {
7620 Entity_Id gnat_desig_type
7621 = Designated_Type (Underlying_Type (Etype (gnat_node)));
7622
7623 ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
7624 gnu_init = gnat_to_gnu (Expression (gnat_temp));
7625
7626 gnu_init = maybe_unconstrained_array (gnu_init);
7627 if (Do_Range_Check (Expression (gnat_temp)))
7628 gnu_init
7629 = emit_range_check (gnu_init, gnat_desig_type, gnat_temp);
7630
7631 if (Is_Elementary_Type (gnat_desig_type)
7632 || Is_Constrained (gnat_desig_type))
7633 gnu_type = gnat_to_gnu_type (gnat_desig_type);
7634 else
7635 {
7636 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
7637 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
7638 gnu_type = TREE_TYPE (gnu_init);
7639 }
7640
7641 /* See the N_Qualified_Expression case for the rationale. */
7642 if (Is_Tagged_Type (gnat_desig_type))
7643 used_types_insert (gnu_type);
7644
7645 gnu_init = convert (gnu_type, gnu_init);
7646 }
7647 else
7648 gcc_unreachable ();
7649
7650 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7651 return build_allocator (gnu_type, gnu_init, gnu_result_type,
7652 Procedure_To_Call (gnat_node),
7653 Storage_Pool (gnat_node), gnat_node,
7654 ignore_init_type);
7655 }
7656 break;
7657
7658 /**************************/
7659 /* Chapter 5: Statements */
7660 /**************************/
7661
7662 case N_Label:
7663 gnu_result = build1 (LABEL_EXPR, void_type_node,
7664 gnat_to_gnu (Identifier (gnat_node)));
7665 break;
7666
7667 case N_Null_Statement:
7668 /* When not optimizing, turn null statements from source into gotos to
7669 the next statement that the middle-end knows how to preserve. */
7670 if (!optimize && Comes_From_Source (gnat_node))
7671 {
7672 tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
7673 DECL_IGNORED_P (label) = 1;
7674 start_stmt_group ();
7675 stmt = build1 (GOTO_EXPR, void_type_node, label);
7676 set_expr_location_from_node (stmt, gnat_node);
7677 add_stmt (stmt);
7678 stmt = build1 (LABEL_EXPR, void_type_node, label);
7679 set_expr_location_from_node (stmt, gnat_node);
7680 add_stmt (stmt);
7681 gnu_result = end_stmt_group ();
7682 }
7683 else
7684 gnu_result = alloc_stmt_list ();
7685 break;
7686
7687 case N_Assignment_Statement:
7688 /* Get the LHS and RHS of the statement and convert any reference to an
7689 unconstrained array into a reference to the underlying array. */
7690 gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
7691
7692 /* If the type has a size that overflows, convert this into raise of
7693 Storage_Error: execution shouldn't have gotten here anyway. */
7694 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
7695 && !valid_constant_size_p (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
7696 gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
7697 N_Raise_Storage_Error);
7698 else if (Nkind (Expression (gnat_node)) == N_Function_Call)
7699 {
7700 bool outer_atomic_access
7701 = outer_atomic_access_required_p (Name (gnat_node));
7702 bool atomic_access
7703 = !outer_atomic_access
7704 && atomic_access_required_p (Name (gnat_node), &sync);
7705 gnu_result
7706 = Call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
7707 outer_atomic_access, atomic_access, sync);
7708 }
7709 else
7710 {
7711 const Node_Id gnat_expr = Expression (gnat_node);
7712 const Entity_Id gnat_type
7713 = Underlying_Type (Etype (Name (gnat_node)));
7714 const bool regular_array_type_p
7715 = (Is_Array_Type (gnat_type) && !Is_Bit_Packed_Array (gnat_type));
7716 const bool use_memset_p
7717 = (regular_array_type_p
7718 && Nkind (gnat_expr) == N_Aggregate
7719 && Is_Others_Aggregate (gnat_expr));
7720
7721 /* If we'll use memset, we need to find the inner expression. */
7722 if (use_memset_p)
7723 {
7724 Node_Id gnat_inner
7725 = Expression (First (Component_Associations (gnat_expr)));
7726 while (Nkind (gnat_inner) == N_Aggregate
7727 && Is_Others_Aggregate (gnat_inner))
7728 gnat_inner
7729 = Expression (First (Component_Associations (gnat_inner)));
7730 gnu_rhs = gnat_to_gnu (gnat_inner);
7731 }
7732 else
7733 gnu_rhs = maybe_unconstrained_array (gnat_to_gnu (gnat_expr));
7734
7735 /* If range check is needed, emit code to generate it. */
7736 if (Do_Range_Check (gnat_expr))
7737 gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)),
7738 gnat_node);
7739
7740 /* If an outer atomic access is required on the LHS, build the load-
7741 modify-store sequence. */
7742 if (outer_atomic_access_required_p (Name (gnat_node)))
7743 gnu_result = build_load_modify_store (gnu_lhs, gnu_rhs, gnat_node);
7744
7745 /* Or else, if atomic access is required, build the atomic store. */
7746 else if (atomic_access_required_p (Name (gnat_node), &sync))
7747 gnu_result = build_atomic_store (gnu_lhs, gnu_rhs, sync);
7748
7749 /* Or else, use memset when the conditions are met. This has already
7750 been validated by Aggr_Assignment_OK_For_Backend in the front-end
7751 and the RHS is thus guaranteed to be of the appropriate form. */
7752 else if (use_memset_p)
7753 {
7754 tree value
7755 = real_zerop (gnu_rhs)
7756 ? integer_zero_node
7757 : fold_convert (integer_type_node, gnu_rhs);
7758 tree dest = build_fold_addr_expr (gnu_lhs);
7759 tree t = builtin_decl_explicit (BUILT_IN_MEMSET);
7760 /* Be extra careful not to write too much data. */
7761 tree size;
7762 if (TREE_CODE (gnu_lhs) == COMPONENT_REF)
7763 size = DECL_SIZE_UNIT (TREE_OPERAND (gnu_lhs, 1));
7764 else if (DECL_P (gnu_lhs))
7765 size = DECL_SIZE_UNIT (gnu_lhs);
7766 else
7767 size = TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs));
7768 size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, gnu_lhs);
7769 if (TREE_CODE (value) == INTEGER_CST && !integer_zerop (value))
7770 {
7771 tree mask
7772 = build_int_cst (integer_type_node,
7773 ((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
7774 value = int_const_binop (BIT_AND_EXPR, value, mask);
7775 }
7776 gnu_result = build_call_expr (t, 3, dest, value, size);
7777 }
7778
7779 /* Otherwise build a regular assignment. */
7780 else
7781 gnu_result
7782 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
7783
7784 /* If the assignment type is a regular array and the two sides are
7785 not completely disjoint, play safe and use memmove. But don't do
7786 it for a bit-packed array as it might not be byte-aligned. */
7787 if (TREE_CODE (gnu_result) == MODIFY_EXPR
7788 && regular_array_type_p
7789 && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
7790 {
7791 tree to = TREE_OPERAND (gnu_result, 0);
7792 tree from = TREE_OPERAND (gnu_result, 1);
7793 tree type = TREE_TYPE (from);
7794 tree size
7795 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), from);
7796 tree to_ptr = build_fold_addr_expr (to);
7797 tree from_ptr = build_fold_addr_expr (from);
7798 tree t = builtin_decl_explicit (BUILT_IN_MEMMOVE);
7799 gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
7800 }
7801 }
7802 break;
7803
7804 case N_If_Statement:
7805 {
7806 tree *gnu_else_ptr; /* Point to put next "else if" or "else". */
7807
7808 /* Make the outer COND_EXPR. Avoid non-determinism. */
7809 gnu_result = build3 (COND_EXPR, void_type_node,
7810 gnat_to_gnu (Condition (gnat_node)),
7811 NULL_TREE, NULL_TREE);
7812 COND_EXPR_THEN (gnu_result)
7813 = build_stmt_group (Then_Statements (gnat_node), false);
7814 TREE_SIDE_EFFECTS (gnu_result) = 1;
7815 gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
7816
7817 /* Now make a COND_EXPR for each of the "else if" parts. Put each
7818 into the previous "else" part and point to where to put any
7819 outer "else". Also avoid non-determinism. */
7820 if (Present (Elsif_Parts (gnat_node)))
7821 for (gnat_temp = First (Elsif_Parts (gnat_node));
7822 Present (gnat_temp); gnat_temp = Next (gnat_temp))
7823 {
7824 gnu_expr = build3 (COND_EXPR, void_type_node,
7825 gnat_to_gnu (Condition (gnat_temp)),
7826 NULL_TREE, NULL_TREE);
7827 COND_EXPR_THEN (gnu_expr)
7828 = build_stmt_group (Then_Statements (gnat_temp), false);
7829 TREE_SIDE_EFFECTS (gnu_expr) = 1;
7830 set_expr_location_from_node (gnu_expr, gnat_temp);
7831 *gnu_else_ptr = gnu_expr;
7832 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
7833 }
7834
7835 *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
7836 }
7837 break;
7838
7839 case N_Case_Statement:
7840 gnu_result = Case_Statement_to_gnu (gnat_node);
7841 break;
7842
7843 case N_Loop_Statement:
7844 gnu_result = Loop_Statement_to_gnu (gnat_node);
7845 break;
7846
7847 case N_Block_Statement:
7848 /* The only way to enter the block is to fall through to it. */
7849 if (stmt_group_may_fallthru ())
7850 {
7851 start_stmt_group ();
7852 gnat_pushlevel ();
7853 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7854 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
7855 gnat_poplevel ();
7856 gnu_result = end_stmt_group ();
7857 }
7858 else
7859 gnu_result = alloc_stmt_list ();
7860 break;
7861
7862 case N_Exit_Statement:
7863 gnu_result
7864 = build2 (EXIT_STMT, void_type_node,
7865 (Present (Condition (gnat_node))
7866 ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
7867 (Present (Name (gnat_node))
7868 ? get_gnu_tree (Entity (Name (gnat_node)))
7869 : LOOP_STMT_LABEL (gnu_loop_stack->last ()->stmt)));
7870 break;
7871
7872 case N_Simple_Return_Statement:
7873 {
7874 tree gnu_ret_obj, gnu_ret_val;
7875
7876 /* If the subprogram is a function, we must return the expression. */
7877 if (Present (Expression (gnat_node)))
7878 {
7879 tree gnu_subprog_type = TREE_TYPE (current_function_decl);
7880
7881 /* If this function has copy-in/copy-out parameters parameters and
7882 doesn't return by invisible reference, get the real object for
7883 the return. See Subprogram_Body_to_gnu. */
7884 if (TYPE_CI_CO_LIST (gnu_subprog_type)
7885 && !TREE_ADDRESSABLE (gnu_subprog_type))
7886 gnu_ret_obj = gnu_return_var_stack->last ();
7887 else
7888 gnu_ret_obj = DECL_RESULT (current_function_decl);
7889
7890 /* Get the GCC tree for the expression to be returned. */
7891 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
7892
7893 /* Do not remove the padding from GNU_RET_VAL if the inner type is
7894 self-referential since we want to allocate the fixed size. */
7895 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
7896 && type_is_padding_self_referential
7897 (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0))))
7898 gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
7899
7900 /* If the function returns by direct reference, return a pointer
7901 to the return value. */
7902 if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
7903 || By_Ref (gnat_node))
7904 gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
7905
7906 /* Otherwise, if it returns an unconstrained array, we have to
7907 allocate a new version of the result and return it. */
7908 else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
7909 {
7910 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
7911
7912 /* And find out whether this is a candidate for Named Return
7913 Value. If so, record it. */
7914 if (!TYPE_CI_CO_LIST (gnu_subprog_type) && optimize)
7915 {
7916 tree ret_val = gnu_ret_val;
7917
7918 /* Strip useless conversions around the return value. */
7919 if (gnat_useless_type_conversion (ret_val))
7920 ret_val = TREE_OPERAND (ret_val, 0);
7921
7922 /* Strip unpadding around the return value. */
7923 if (TREE_CODE (ret_val) == COMPONENT_REF
7924 && TYPE_IS_PADDING_P
7925 (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
7926 ret_val = TREE_OPERAND (ret_val, 0);
7927
7928 /* Now apply the test to the return value. */
7929 if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
7930 {
7931 if (!f_named_ret_val)
7932 f_named_ret_val = BITMAP_GGC_ALLOC ();
7933 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
7934 if (!f_gnat_ret)
7935 f_gnat_ret = gnat_node;
7936 }
7937 }
7938
7939 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
7940 gnu_ret_val,
7941 TREE_TYPE (gnu_ret_obj),
7942 Procedure_To_Call (gnat_node),
7943 Storage_Pool (gnat_node),
7944 gnat_node, false);
7945 }
7946
7947 /* Otherwise, if it returns by invisible reference, dereference
7948 the pointer it is passed using the type of the return value
7949 and build the copy operation manually. This ensures that we
7950 don't copy too much data, for example if the return type is
7951 unconstrained with a maximum size. */
7952 else if (TREE_ADDRESSABLE (gnu_subprog_type))
7953 {
7954 tree gnu_ret_deref
7955 = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
7956 gnu_ret_obj);
7957 gnu_result = build2 (INIT_EXPR, void_type_node,
7958 gnu_ret_deref, gnu_ret_val);
7959 add_stmt_with_node (gnu_result, gnat_node);
7960 gnu_ret_val = NULL_TREE;
7961 }
7962 }
7963
7964 else
7965 gnu_ret_obj = gnu_ret_val = NULL_TREE;
7966
7967 /* If we have a return label defined, convert this into a branch to
7968 that label. The return proper will be handled elsewhere. */
7969 if (gnu_return_label_stack->last ())
7970 {
7971 if (gnu_ret_val)
7972 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_ret_obj,
7973 gnu_ret_val));
7974
7975 gnu_result = build1 (GOTO_EXPR, void_type_node,
7976 gnu_return_label_stack->last ());
7977
7978 /* When not optimizing, make sure the return is preserved. */
7979 if (!optimize && Comes_From_Source (gnat_node))
7980 DECL_ARTIFICIAL (gnu_return_label_stack->last ()) = 0;
7981 }
7982
7983 /* Otherwise, build a regular return. */
7984 else
7985 gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
7986 }
7987 break;
7988
7989 case N_Goto_Statement:
7990 gnu_expr = gnat_to_gnu (Name (gnat_node));
7991 gnu_result = build1 (GOTO_EXPR, void_type_node, gnu_expr);
7992 TREE_USED (gnu_expr) = 1;
7993 break;
7994
7995 /***************************/
7996 /* Chapter 6: Subprograms */
7997 /***************************/
7998
7999 case N_Subprogram_Declaration:
8000 /* Unless there is a freeze node, declare the entity. We consider
8001 this a definition even though we're not generating code for the
8002 subprogram because we will be making the corresponding GCC node.
8003 When there is a freeze node, it is considered the definition of
8004 the subprogram and we do nothing until after it is encountered.
8005 That's an efficiency issue: the types involved in the profile
8006 are far more likely to be frozen between the declaration and
8007 the freeze node than before the declaration, so we save some
8008 updates of the GCC node by waiting until the freeze node.
8009 The counterpart is that we assume that there is no reference
8010 to the subprogram between the declaration and the freeze node
8011 in the expanded code; otherwise, it will be interpreted as an
8012 external reference and very likely give rise to a link failure. */
8013 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
8014 gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
8015 NULL_TREE, true);
8016 gnu_result = alloc_stmt_list ();
8017 break;
8018
8019 case N_Abstract_Subprogram_Declaration:
8020 /* This subprogram doesn't exist for code generation purposes, but we
8021 have to elaborate the types of any parameters and result, unless
8022 they are imported types (nothing to generate in this case).
8023
8024 The parameter list may contain types with freeze nodes, e.g. not null
8025 subtypes, so the subprogram itself may carry a freeze node, in which
8026 case its elaboration must be deferred. */
8027
8028 /* Process the parameter types first. */
8029 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
8030 for (gnat_temp
8031 = First_Formal_With_Extras
8032 (Defining_Entity (Specification (gnat_node)));
8033 Present (gnat_temp);
8034 gnat_temp = Next_Formal_With_Extras (gnat_temp))
8035 if (Is_Itype (Etype (gnat_temp))
8036 && !From_Limited_With (Etype (gnat_temp)))
8037 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, false);
8038
8039 /* Then the result type, set to Standard_Void_Type for procedures. */
8040 {
8041 Entity_Id gnat_temp_type
8042 = Etype (Defining_Entity (Specification (gnat_node)));
8043
8044 if (Is_Itype (gnat_temp_type) && !From_Limited_With (gnat_temp_type))
8045 gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, false);
8046 }
8047
8048 gnu_result = alloc_stmt_list ();
8049 break;
8050
8051 case N_Defining_Program_Unit_Name:
8052 /* For a child unit identifier go up a level to get the specification.
8053 We get this when we try to find the spec of a child unit package
8054 that is the compilation unit being compiled. */
8055 gnu_result = gnat_to_gnu (Parent (gnat_node));
8056 break;
8057
8058 case N_Subprogram_Body:
8059 Subprogram_Body_to_gnu (gnat_node);
8060 gnu_result = alloc_stmt_list ();
8061 break;
8062
8063 case N_Function_Call:
8064 case N_Procedure_Call_Statement:
8065 gnu_result = Call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE,
8066 false, false, false);
8067 break;
8068
8069 /************************/
8070 /* Chapter 7: Packages */
8071 /************************/
8072
8073 case N_Package_Declaration:
8074 gnu_result = gnat_to_gnu (Specification (gnat_node));
8075 break;
8076
8077 case N_Package_Specification:
8078
8079 start_stmt_group ();
8080 process_decls (Visible_Declarations (gnat_node),
8081 Private_Declarations (gnat_node), Empty, true, true);
8082 gnu_result = end_stmt_group ();
8083 break;
8084
8085 case N_Package_Body:
8086
8087 /* If this is the body of a generic package - do nothing. */
8088 if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
8089 {
8090 gnu_result = alloc_stmt_list ();
8091 break;
8092 }
8093
8094 start_stmt_group ();
8095 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
8096
8097 if (Present (Handled_Statement_Sequence (gnat_node)))
8098 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
8099
8100 gnu_result = end_stmt_group ();
8101 break;
8102
8103 /********************************/
8104 /* Chapter 8: Visibility Rules */
8105 /********************************/
8106
8107 case N_Use_Package_Clause:
8108 case N_Use_Type_Clause:
8109 /* Nothing to do here - but these may appear in list of declarations. */
8110 gnu_result = alloc_stmt_list ();
8111 break;
8112
8113 /*********************/
8114 /* Chapter 9: Tasks */
8115 /*********************/
8116
8117 case N_Protected_Type_Declaration:
8118 gnu_result = alloc_stmt_list ();
8119 break;
8120
8121 case N_Single_Task_Declaration:
8122 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, true);
8123 gnu_result = alloc_stmt_list ();
8124 break;
8125
8126 /*********************************************************/
8127 /* Chapter 10: Program Structure and Compilation Issues */
8128 /*********************************************************/
8129
8130 case N_Compilation_Unit:
8131 /* This is not called for the main unit on which gigi is invoked. */
8132 Compilation_Unit_to_gnu (gnat_node);
8133 gnu_result = alloc_stmt_list ();
8134 break;
8135
8136 case N_Subunit:
8137 gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
8138 break;
8139
8140 case N_Entry_Body:
8141 case N_Protected_Body:
8142 case N_Task_Body:
8143 /* These nodes should only be present when annotating types. */
8144 gcc_assert (type_annotate_only);
8145 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
8146 gnu_result = alloc_stmt_list ();
8147 break;
8148
8149 case N_Subprogram_Body_Stub:
8150 case N_Package_Body_Stub:
8151 case N_Protected_Body_Stub:
8152 case N_Task_Body_Stub:
8153 /* Simply process whatever unit is being inserted. */
8154 if (Present (Library_Unit (gnat_node)))
8155 gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
8156 else
8157 {
8158 gcc_assert (type_annotate_only);
8159 gnu_result = alloc_stmt_list ();
8160 }
8161 break;
8162
8163 /***************************/
8164 /* Chapter 11: Exceptions */
8165 /***************************/
8166
8167 case N_Handled_Sequence_Of_Statements:
8168 /* If there is an At_End procedure attached to this node, and the EH
8169 mechanism is front-end, we must have at least a corresponding At_End
8170 handler, unless the No_Exception_Handlers restriction is set. */
8171 gcc_assert (type_annotate_only
8172 || !Front_End_Exceptions ()
8173 || No (At_End_Proc (gnat_node))
8174 || Present (Exception_Handlers (gnat_node))
8175 || No_Exception_Handlers_Set ());
8176
8177 gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
8178 break;
8179
8180 case N_Exception_Handler:
8181 if (Back_End_Exceptions ())
8182 gnu_result = Exception_Handler_to_gnu_gcc (gnat_node);
8183 else if (Exception_Mechanism == Front_End_SJLJ)
8184 gnu_result = Exception_Handler_to_gnu_fe_sjlj (gnat_node);
8185 else
8186 gcc_unreachable ();
8187 break;
8188
8189 case N_Raise_Statement:
8190 /* Only for reraise in back-end exceptions mode. */
8191 gcc_assert (No (Name (gnat_node)) && Back_End_Exceptions ());
8192
8193 start_stmt_group ();
8194 gnat_pushlevel ();
8195
8196 /* Clear the current exception pointer so that the occurrence won't be
8197 deallocated. */
8198 gnu_expr = create_var_decl (get_identifier ("SAVED_EXPTR"), NULL_TREE,
8199 ptr_type_node, gnu_incoming_exc_ptr,
8200 false, false, false, false, false,
8201 true, true, NULL, gnat_node);
8202
8203 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_incoming_exc_ptr,
8204 build_int_cst (ptr_type_node, 0)));
8205 add_stmt (build_call_n_expr (reraise_zcx_decl, 1, gnu_expr));
8206 gnat_poplevel ();
8207 gnu_result = end_stmt_group ();
8208 break;
8209
8210 case N_Push_Constraint_Error_Label:
8211 gnu_constraint_error_label_stack.safe_push (Exception_Label (gnat_node));
8212 break;
8213
8214 case N_Push_Storage_Error_Label:
8215 gnu_storage_error_label_stack.safe_push (Exception_Label (gnat_node));
8216 break;
8217
8218 case N_Push_Program_Error_Label:
8219 gnu_program_error_label_stack.safe_push (Exception_Label (gnat_node));
8220 break;
8221
8222 case N_Pop_Constraint_Error_Label:
8223 gnat_temp = gnu_constraint_error_label_stack.pop ();
8224 if (Present (gnat_temp)
8225 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false)))
8226 Warn_If_No_Local_Raise (gnat_temp);
8227 break;
8228
8229 case N_Pop_Storage_Error_Label:
8230 gnat_temp = gnu_storage_error_label_stack.pop ();
8231 if (Present (gnat_temp)
8232 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false)))
8233 Warn_If_No_Local_Raise (gnat_temp);
8234 break;
8235
8236 case N_Pop_Program_Error_Label:
8237 gnat_temp = gnu_program_error_label_stack.pop ();
8238 if (Present (gnat_temp)
8239 && !TREE_USED (gnat_to_gnu_entity (gnat_temp, NULL_TREE, false)))
8240 Warn_If_No_Local_Raise (gnat_temp);
8241 break;
8242
8243 /******************************/
8244 /* Chapter 12: Generic Units */
8245 /******************************/
8246
8247 case N_Generic_Function_Renaming_Declaration:
8248 case N_Generic_Package_Renaming_Declaration:
8249 case N_Generic_Procedure_Renaming_Declaration:
8250 case N_Generic_Package_Declaration:
8251 case N_Generic_Subprogram_Declaration:
8252 case N_Package_Instantiation:
8253 case N_Procedure_Instantiation:
8254 case N_Function_Instantiation:
8255 /* These nodes can appear on a declaration list but there is nothing to
8256 to be done with them. */
8257 gnu_result = alloc_stmt_list ();
8258 break;
8259
8260 /**************************************************/
8261 /* Chapter 13: Representation Clauses and */
8262 /* Implementation-Dependent Features */
8263 /**************************************************/
8264
8265 case N_Attribute_Definition_Clause:
8266 gnu_result = alloc_stmt_list ();
8267
8268 /* The only one we need to deal with is 'Address since, for the others,
8269 the front-end puts the information elsewhere. */
8270 if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
8271 break;
8272
8273 /* And we only deal with 'Address if the object has a Freeze node. */
8274 gnat_temp = Entity (Name (gnat_node));
8275 if (Freeze_Node (gnat_temp))
8276 {
8277 tree gnu_address = gnat_to_gnu (Expression (gnat_node));
8278
8279 /* Get the value to use as the address and save it as the equivalent
8280 for the object; when it is frozen, gnat_to_gnu_entity will do the
8281 right thing. For a subprogram, put the naked address but build a
8282 meaningfull expression for an object in case its address is taken
8283 before the Freeze node is encountered; this can happen if the type
8284 of the object is limited and it is initialized with the result of
8285 a function call. */
8286 if (Is_Subprogram (gnat_temp))
8287 gnu_result = gnu_address;
8288 else
8289 {
8290 tree gnu_type = gnat_to_gnu_type (Etype (gnat_temp));
8291 /* Drop atomic and volatile qualifiers for the expression. */
8292 gnu_type = TYPE_MAIN_VARIANT (gnu_type);
8293 gnu_type
8294 = build_reference_type_for_mode (gnu_type, ptr_mode, true);
8295 gnu_address = convert (gnu_type, gnu_address);
8296 gnu_result
8297 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_address);
8298 }
8299
8300 save_gnu_tree (gnat_temp, gnu_result, true);
8301 }
8302 break;
8303
8304 case N_Enumeration_Representation_Clause:
8305 case N_Record_Representation_Clause:
8306 case N_At_Clause:
8307 /* We do nothing with these. SEM puts the information elsewhere. */
8308 gnu_result = alloc_stmt_list ();
8309 break;
8310
8311 case N_Code_Statement:
8312 if (!type_annotate_only)
8313 {
8314 tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
8315 tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
8316 tree gnu_clobbers = NULL_TREE, tail;
8317 bool allows_mem, allows_reg, fake;
8318 int ninputs, noutputs, i;
8319 const char **oconstraints;
8320 const char *constraint;
8321 char *clobber;
8322
8323 /* First retrieve the 3 operand lists built by the front-end. */
8324 Setup_Asm_Outputs (gnat_node);
8325 while (Present (gnat_temp = Asm_Output_Variable ()))
8326 {
8327 tree gnu_value = gnat_to_gnu (gnat_temp);
8328 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
8329 (Asm_Output_Constraint ()));
8330
8331 gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
8332 Next_Asm_Output ();
8333 }
8334
8335 Setup_Asm_Inputs (gnat_node);
8336 while (Present (gnat_temp = Asm_Input_Value ()))
8337 {
8338 tree gnu_value = gnat_to_gnu (gnat_temp);
8339 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
8340 (Asm_Input_Constraint ()));
8341
8342 gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
8343 Next_Asm_Input ();
8344 }
8345
8346 Clobber_Setup (gnat_node);
8347 while ((clobber = Clobber_Get_Next ()))
8348 gnu_clobbers
8349 = tree_cons (NULL_TREE,
8350 build_string (strlen (clobber) + 1, clobber),
8351 gnu_clobbers);
8352
8353 /* Then perform some standard checking and processing on the
8354 operands. In particular, mark them addressable if needed. */
8355 gnu_outputs = nreverse (gnu_outputs);
8356 noutputs = list_length (gnu_outputs);
8357 gnu_inputs = nreverse (gnu_inputs);
8358 ninputs = list_length (gnu_inputs);
8359 oconstraints = XALLOCAVEC (const char *, noutputs);
8360
8361 for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
8362 {
8363 tree output = TREE_VALUE (tail);
8364 constraint
8365 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
8366 oconstraints[i] = constraint;
8367
8368 if (parse_output_constraint (&constraint, i, ninputs, noutputs,
8369 &allows_mem, &allows_reg, &fake))
8370 {
8371 /* If the operand is going to end up in memory,
8372 mark it addressable. Note that we don't test
8373 allows_mem like in the input case below; this
8374 is modelled on the C front-end. */
8375 if (!allows_reg)
8376 {
8377 output = remove_conversions (output, false);
8378 if (TREE_CODE (output) == CONST_DECL
8379 && DECL_CONST_CORRESPONDING_VAR (output))
8380 output = DECL_CONST_CORRESPONDING_VAR (output);
8381 if (!gnat_mark_addressable (output))
8382 output = error_mark_node;
8383 }
8384 }
8385 else
8386 output = error_mark_node;
8387
8388 TREE_VALUE (tail) = output;
8389 }
8390
8391 for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
8392 {
8393 tree input = TREE_VALUE (tail);
8394 constraint
8395 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
8396
8397 if (parse_input_constraint (&constraint, i, ninputs, noutputs,
8398 0, oconstraints,
8399 &allows_mem, &allows_reg))
8400 {
8401 /* If the operand is going to end up in memory,
8402 mark it addressable. */
8403 if (!allows_reg && allows_mem)
8404 {
8405 input = remove_conversions (input, false);
8406 if (TREE_CODE (input) == CONST_DECL
8407 && DECL_CONST_CORRESPONDING_VAR (input))
8408 input = DECL_CONST_CORRESPONDING_VAR (input);
8409 if (!gnat_mark_addressable (input))
8410 input = error_mark_node;
8411 }
8412 }
8413 else
8414 input = error_mark_node;
8415
8416 TREE_VALUE (tail) = input;
8417 }
8418
8419 gnu_result = build5 (ASM_EXPR, void_type_node,
8420 gnu_template, gnu_outputs,
8421 gnu_inputs, gnu_clobbers, NULL_TREE);
8422 ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
8423 }
8424 else
8425 gnu_result = alloc_stmt_list ();
8426
8427 break;
8428
8429 /****************/
8430 /* Added Nodes */
8431 /****************/
8432
8433 /* Markers are created by the ABE mechanism to capture information which
8434 is either unavailable of expensive to recompute. Markers do not have
8435 and runtime semantics, and should be ignored. */
8436
8437 case N_Call_Marker:
8438 case N_Variable_Reference_Marker:
8439 gnu_result = alloc_stmt_list ();
8440 break;
8441
8442 case N_Expression_With_Actions:
8443 /* This construct doesn't define a scope so we don't push a binding
8444 level around the statement list, but we wrap it in a SAVE_EXPR to
8445 protect it from unsharing. Elaborate the expression as part of the
8446 same statement group as the actions so that the type declaration
8447 gets inserted there as well. This ensures that the type elaboration
8448 code is issued past the actions computing values on which it might
8449 depend. */
8450 start_stmt_group ();
8451 add_stmt_list (Actions (gnat_node));
8452 gnu_expr = gnat_to_gnu (Expression (gnat_node));
8453 gnu_result = end_stmt_group ();
8454
8455 gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
8456 TREE_SIDE_EFFECTS (gnu_result) = 1;
8457
8458 gnu_result
8459 = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
8460 gnu_result_type = get_unpadded_type (Etype (gnat_node));
8461 break;
8462
8463 case N_Freeze_Entity:
8464 start_stmt_group ();
8465 process_freeze_entity (gnat_node);
8466 process_decls (Actions (gnat_node), Empty, Empty, true, true);
8467 gnu_result = end_stmt_group ();
8468 break;
8469
8470 case N_Freeze_Generic_Entity:
8471 gnu_result = alloc_stmt_list ();
8472 break;
8473
8474 case N_Itype_Reference:
8475 if (!present_gnu_tree (Itype (gnat_node)))
8476 process_type (Itype (gnat_node));
8477 gnu_result = alloc_stmt_list ();
8478 break;
8479
8480 case N_Free_Statement:
8481 if (!type_annotate_only)
8482 {
8483 tree gnu_ptr
8484 = gnat_to_gnu (adjust_for_implicit_deref (Expression (gnat_node)));
8485 tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
8486 tree gnu_obj_type, gnu_actual_obj_type;
8487
8488 /* If this is a thin pointer, we must first dereference it to create
8489 a fat pointer, then go back below to a thin pointer. The reason
8490 for this is that we need to have a fat pointer someplace in order
8491 to properly compute the size. */
8492 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
8493 gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
8494 build_unary_op (INDIRECT_REF, NULL_TREE,
8495 gnu_ptr));
8496
8497 /* If this is a fat pointer, the object must have been allocated with
8498 the template in front of the array. So pass the template address,
8499 and get the total size; do it by converting to a thin pointer. */
8500 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
8501 gnu_ptr
8502 = convert (build_pointer_type
8503 (TYPE_OBJECT_RECORD_TYPE
8504 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
8505 gnu_ptr);
8506
8507 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
8508
8509 /* If this is a thin pointer, the object must have been allocated with
8510 the template in front of the array. So pass the template address,
8511 and get the total size. */
8512 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
8513 gnu_ptr
8514 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
8515 gnu_ptr,
8516 fold_build1 (NEGATE_EXPR, sizetype,
8517 byte_position
8518 (DECL_CHAIN
8519 TYPE_FIELDS ((gnu_obj_type)))));
8520
8521 /* If we have a special dynamic constrained subtype on the node, use
8522 it to compute the size; otherwise, use the designated subtype. */
8523 if (Present (Actual_Designated_Subtype (gnat_node)))
8524 {
8525 gnu_actual_obj_type
8526 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
8527
8528 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
8529 gnu_actual_obj_type
8530 = build_unc_object_type_from_ptr (gnu_ptr_type,
8531 gnu_actual_obj_type,
8532 get_identifier ("DEALLOC"),
8533 false);
8534 }
8535 else
8536 gnu_actual_obj_type = gnu_obj_type;
8537
8538 tree gnu_size = TYPE_SIZE_UNIT (gnu_actual_obj_type);
8539 gnu_size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_size, gnu_ptr);
8540
8541 gnu_result
8542 = build_call_alloc_dealloc (gnu_ptr, gnu_size, gnu_obj_type,
8543 Procedure_To_Call (gnat_node),
8544 Storage_Pool (gnat_node),
8545 gnat_node);
8546 }
8547 break;
8548
8549 case N_Raise_Constraint_Error:
8550 case N_Raise_Program_Error:
8551 case N_Raise_Storage_Error:
8552 if (type_annotate_only)
8553 gnu_result = alloc_stmt_list ();
8554 else
8555 gnu_result = Raise_Error_to_gnu (gnat_node, &gnu_result_type);
8556 break;
8557
8558 case N_Validate_Unchecked_Conversion:
8559 /* The only validation we currently do on an unchecked conversion is
8560 that of aliasing assumptions. */
8561 if (flag_strict_aliasing)
8562 gnat_validate_uc_list.safe_push (gnat_node);
8563 gnu_result = alloc_stmt_list ();
8564 break;
8565
8566 case N_Function_Specification:
8567 case N_Procedure_Specification:
8568 case N_Op_Concat:
8569 case N_Component_Association:
8570 /* These nodes should only be present when annotating types. */
8571 gcc_assert (type_annotate_only);
8572 gnu_result = alloc_stmt_list ();
8573 break;
8574
8575 default:
8576 /* Other nodes are not supposed to reach here. */
8577 gcc_unreachable ();
8578 }
8579
8580 /* If we pushed the processing of the elaboration routine, pop it back. */
8581 if (went_into_elab_proc)
8582 current_function_decl = NULL_TREE;
8583
8584 /* When not optimizing, turn boolean rvalues B into B != false tests
8585 so that we can put the location information of the reference to B on
8586 the inequality operator for better debug info. */
8587 if (!optimize
8588 && TREE_CODE (gnu_result) != INTEGER_CST
8589 && TREE_CODE (gnu_result) != TYPE_DECL
8590 && (kind == N_Identifier
8591 || kind == N_Expanded_Name
8592 || kind == N_Explicit_Dereference
8593 || kind == N_Indexed_Component
8594 || kind == N_Selected_Component)
8595 && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
8596 && !lvalue_required_p (gnat_node, gnu_result_type, false, false)
8597 && Nkind (Parent (gnat_node)) != N_Variant_Part)
8598 {
8599 gnu_result
8600 = build_binary_op (NE_EXPR, gnu_result_type,
8601 convert (gnu_result_type, gnu_result),
8602 convert (gnu_result_type, boolean_false_node));
8603 if (TREE_CODE (gnu_result) != INTEGER_CST)
8604 set_gnu_expr_location_from_node (gnu_result, gnat_node);
8605 }
8606
8607 /* Set the location information on the result if it's not a simple name.
8608 Note that we may have no result if we tried to build a CALL_EXPR node
8609 to a procedure with no side-effects and optimization is enabled. */
8610 else if (kind != N_Identifier && gnu_result && EXPR_P (gnu_result))
8611 set_gnu_expr_location_from_node (gnu_result, gnat_node);
8612
8613 /* If we're supposed to return something of void_type, it means we have
8614 something we're elaborating for effect, so just return. */
8615 if (TREE_CODE (gnu_result_type) == VOID_TYPE)
8616 return gnu_result;
8617
8618 /* If the result is a constant that overflowed, raise Constraint_Error. */
8619 if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
8620 {
8621 post_error ("?`Constraint_Error` will be raised at run time", gnat_node);
8622 gnu_result
8623 = build1 (NULL_EXPR, gnu_result_type,
8624 build_call_raise (CE_Overflow_Check_Failed, gnat_node,
8625 N_Raise_Constraint_Error));
8626 }
8627
8628 /* If the result has side-effects and is of an unconstrained type, protect
8629 the expression in case it will be referenced multiple times, i.e. for
8630 its value and to compute the size of an object. But do it neither for
8631 an object nor a renaming declaration, nor a return statement of a call
8632 to a function that returns an unconstrained record type with default
8633 discriminant, because there is no size to be computed in these cases
8634 and this will create a useless temporary. We must do this before any
8635 conversions. */
8636 if (TREE_SIDE_EFFECTS (gnu_result)
8637 && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
8638 || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type)))
8639 && !(TREE_CODE (gnu_result) == CALL_EXPR
8640 && type_is_padding_self_referential (TREE_TYPE (gnu_result))
8641 && (Nkind (Parent (gnat_node)) == N_Object_Declaration
8642 || Nkind (Parent (gnat_node)) == N_Object_Renaming_Declaration
8643 || Nkind (Parent (gnat_node)) == N_Simple_Return_Statement)))
8644 gnu_result = gnat_protect_expr (gnu_result);
8645
8646 /* Now convert the result to the result type, unless we are in one of the
8647 following cases:
8648
8649 1. If this is the LHS of an assignment or an actual parameter of a
8650 call, return the result almost unmodified since the RHS will have
8651 to be converted to our type in that case, unless the result type
8652 has a simpler size. Likewise if there is just a no-op unchecked
8653 conversion in-between. Similarly, don't convert integral types
8654 that are the operands of an unchecked conversion since we need
8655 to ignore those conversions (for 'Valid).
8656
8657 2. If we have a label (which doesn't have any well-defined type), a
8658 field or an error, return the result almost unmodified. Similarly,
8659 if the two types are record types with the same name, don't convert.
8660 This will be the case when we are converting from a packable version
8661 of a type to its original type and we need those conversions to be
8662 NOPs in order for assignments into these types to work properly.
8663
8664 3. If the type is void or if we have no result, return error_mark_node
8665 to show we have no result.
8666
8667 4. If this is a call to a function that returns with variable size and
8668 the call is used as the expression in either an object or a renaming
8669 declaration, return the result unmodified because we want to use the
8670 return slot optimization in this case.
8671
8672 5. Finally, if the type of the result is already correct. */
8673
8674 if (Present (Parent (gnat_node))
8675 && (lhs_or_actual_p (gnat_node)
8676 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
8677 && unchecked_conversion_nop (Parent (gnat_node)))
8678 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
8679 && !AGGREGATE_TYPE_P (gnu_result_type)
8680 && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
8681 && !(TYPE_SIZE (gnu_result_type)
8682 && TYPE_SIZE (TREE_TYPE (gnu_result))
8683 && (AGGREGATE_TYPE_P (gnu_result_type)
8684 == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
8685 && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
8686 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
8687 != INTEGER_CST))
8688 || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
8689 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
8690 && (CONTAINS_PLACEHOLDER_P
8691 (TYPE_SIZE (TREE_TYPE (gnu_result))))))
8692 && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
8693 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
8694 {
8695 /* Remove padding only if the inner object is of self-referential
8696 size: in that case it must be an object of unconstrained type
8697 with a default discriminant and we want to avoid copying too
8698 much data. */
8699 if (type_is_padding_self_referential (TREE_TYPE (gnu_result)))
8700 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
8701 gnu_result);
8702 }
8703
8704 else if (TREE_CODE (gnu_result) == LABEL_DECL
8705 || TREE_CODE (gnu_result) == FIELD_DECL
8706 || TREE_CODE (gnu_result) == ERROR_MARK
8707 || (TYPE_NAME (gnu_result_type)
8708 == TYPE_NAME (TREE_TYPE (gnu_result))
8709 && TREE_CODE (gnu_result_type) == RECORD_TYPE
8710 && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
8711 {
8712 /* Remove any padding. */
8713 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
8714 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
8715 gnu_result);
8716 }
8717
8718 else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
8719 gnu_result = error_mark_node;
8720
8721 else if (Present (Parent (gnat_node))
8722 && (Nkind (Parent (gnat_node)) == N_Object_Declaration
8723 || Nkind (Parent (gnat_node)) == N_Object_Renaming_Declaration)
8724 && TREE_CODE (gnu_result) == CALL_EXPR
8725 && return_type_with_variable_size_p (TREE_TYPE (gnu_result)))
8726 ;
8727
8728 else if (TREE_TYPE (gnu_result) != gnu_result_type)
8729 gnu_result = convert (gnu_result_type, gnu_result);
8730
8731 /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result. */
8732 while ((TREE_CODE (gnu_result) == NOP_EXPR
8733 || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
8734 && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
8735 gnu_result = TREE_OPERAND (gnu_result, 0);
8736
8737 return gnu_result;
8738 }
8739
8740 /* Similar to gnat_to_gnu, but discard any object that might be created in
8741 the course of the translation of GNAT_NODE, which must be an "external"
8742 expression in the sense that it will be elaborated elsewhere. */
8743
8744 tree
8745 gnat_to_gnu_external (Node_Id gnat_node)
8746 {
8747 const int save_force_global = force_global;
8748 bool went_into_elab_proc = false;
8749
8750 /* Force the local context and create a fake scope that we zap
8751 at the end so declarations will not be stuck either in the
8752 global varpool or in the current scope. */
8753 if (!current_function_decl)
8754 {
8755 current_function_decl = get_elaboration_procedure ();
8756 went_into_elab_proc = true;
8757 }
8758 force_global = 0;
8759 gnat_pushlevel ();
8760
8761 tree gnu_result = gnat_to_gnu (gnat_node);
8762
8763 gnat_zaplevel ();
8764 force_global = save_force_global;
8765 if (went_into_elab_proc)
8766 current_function_decl = NULL_TREE;
8767
8768 /* Do not import locations from external units. */
8769 if (gnu_result && EXPR_P (gnu_result))
8770 SET_EXPR_LOCATION (gnu_result, UNKNOWN_LOCATION);
8771
8772 return gnu_result;
8773 }
8774 \f
8775 /* Return true if the statement list STMT_LIST is empty. */
8776
8777 static bool
8778 empty_stmt_list_p (tree stmt_list)
8779 {
8780 tree_stmt_iterator tsi;
8781
8782 for (tsi = tsi_start (stmt_list); !tsi_end_p (tsi); tsi_next (&tsi))
8783 {
8784 tree stmt = tsi_stmt (tsi);
8785
8786 /* Anything else than an empty STMT_STMT counts as something. */
8787 if (TREE_CODE (stmt) != STMT_STMT || STMT_STMT_STMT (stmt))
8788 return false;
8789 }
8790
8791 return true;
8792 }
8793
8794 /* Record the current code position in GNAT_NODE. */
8795
8796 static void
8797 record_code_position (Node_Id gnat_node)
8798 {
8799 tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
8800
8801 add_stmt_with_node (stmt_stmt, gnat_node);
8802 save_gnu_tree (gnat_node, stmt_stmt, true);
8803 }
8804
8805 /* Insert the code for GNAT_NODE at the position saved for that node. */
8806
8807 static void
8808 insert_code_for (Node_Id gnat_node)
8809 {
8810 tree code = gnat_to_gnu (gnat_node);
8811
8812 /* It's too late to remove the STMT_STMT itself at this point. */
8813 if (!empty_stmt_list_p (code))
8814 STMT_STMT_STMT (get_gnu_tree (gnat_node)) = code;
8815
8816 save_gnu_tree (gnat_node, NULL_TREE, true);
8817 }
8818 \f
8819 /* Start a new statement group chained to the previous group. */
8820
8821 void
8822 start_stmt_group (void)
8823 {
8824 struct stmt_group *group = stmt_group_free_list;
8825
8826 /* First see if we can get one from the free list. */
8827 if (group)
8828 stmt_group_free_list = group->previous;
8829 else
8830 group = ggc_alloc<stmt_group> ();
8831
8832 group->previous = current_stmt_group;
8833 group->stmt_list = group->block = group->cleanups = NULL_TREE;
8834 current_stmt_group = group;
8835 }
8836
8837 /* Add GNU_STMT to the current statement group. If it is an expression with
8838 no effects, it is ignored. */
8839
8840 void
8841 add_stmt (tree gnu_stmt)
8842 {
8843 append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
8844 }
8845
8846 /* Similar, but the statement is always added, regardless of side-effects. */
8847
8848 void
8849 add_stmt_force (tree gnu_stmt)
8850 {
8851 append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
8852 }
8853
8854 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE. */
8855
8856 void
8857 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
8858 {
8859 if (Present (gnat_node))
8860 set_expr_location_from_node (gnu_stmt, gnat_node);
8861 add_stmt (gnu_stmt);
8862 }
8863
8864 /* Similar, but the statement is always added, regardless of side-effects. */
8865
8866 void
8867 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
8868 {
8869 if (Present (gnat_node))
8870 set_expr_location_from_node (gnu_stmt, gnat_node);
8871 add_stmt_force (gnu_stmt);
8872 }
8873
8874 /* Add a declaration statement for GNU_DECL to the current statement group.
8875 Get the SLOC to be put onto the statement from GNAT_NODE. */
8876
8877 void
8878 add_decl_expr (tree gnu_decl, Node_Id gnat_node)
8879 {
8880 tree type = TREE_TYPE (gnu_decl);
8881 tree gnu_stmt, gnu_init;
8882
8883 /* If this is a variable that Gigi is to ignore, we may have been given
8884 an ERROR_MARK. So test for it. We also might have been given a
8885 reference for a renaming. So only do something for a decl. Also
8886 ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE. */
8887 if (!DECL_P (gnu_decl)
8888 || (TREE_CODE (gnu_decl) == TYPE_DECL
8889 && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
8890 return;
8891
8892 gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
8893
8894 /* If we are external or global, we don't want to output the DECL_EXPR for
8895 this DECL node since we already have evaluated the expressions in the
8896 sizes and positions as globals and doing it again would be wrong. */
8897 if (DECL_EXTERNAL (gnu_decl) || global_bindings_p ())
8898 {
8899 /* Mark everything as used to prevent node sharing with subprograms.
8900 Note that walk_tree knows how to deal with TYPE_DECL, but neither
8901 VAR_DECL nor CONST_DECL. This appears to be somewhat arbitrary. */
8902 MARK_VISITED (gnu_stmt);
8903 if (TREE_CODE (gnu_decl) == VAR_DECL
8904 || TREE_CODE (gnu_decl) == CONST_DECL)
8905 {
8906 MARK_VISITED (DECL_SIZE (gnu_decl));
8907 MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
8908 MARK_VISITED (DECL_INITIAL (gnu_decl));
8909 }
8910 /* In any case, we have to deal with our own TYPE_ADA_SIZE field. */
8911 else if (TREE_CODE (gnu_decl) == TYPE_DECL
8912 && RECORD_OR_UNION_TYPE_P (type)
8913 && !TYPE_FAT_POINTER_P (type))
8914 MARK_VISITED (TYPE_ADA_SIZE (type));
8915 }
8916 else
8917 add_stmt_with_node (gnu_stmt, gnat_node);
8918
8919 /* If this is a variable and an initializer is attached to it, it must be
8920 valid for the context. Similar to init_const in create_var_decl. */
8921 if (TREE_CODE (gnu_decl) == VAR_DECL
8922 && (gnu_init = DECL_INITIAL (gnu_decl))
8923 && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
8924 || (TREE_STATIC (gnu_decl)
8925 && !initializer_constant_valid_p (gnu_init,
8926 TREE_TYPE (gnu_init)))))
8927 {
8928 DECL_INITIAL (gnu_decl) = NULL_TREE;
8929 if (TREE_READONLY (gnu_decl))
8930 {
8931 TREE_READONLY (gnu_decl) = 0;
8932 DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
8933 }
8934
8935 /* If GNU_DECL has a padded type, convert it to the unpadded
8936 type so the assignment is done properly. */
8937 if (TYPE_IS_PADDING_P (type))
8938 gnu_decl = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
8939
8940 gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_decl, gnu_init);
8941 add_stmt_with_node (gnu_stmt, gnat_node);
8942 }
8943 }
8944
8945 /* Callback for walk_tree to mark the visited trees rooted at *TP. */
8946
8947 static tree
8948 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
8949 {
8950 tree t = *tp;
8951
8952 if (TREE_VISITED (t))
8953 *walk_subtrees = 0;
8954
8955 /* Don't mark a dummy type as visited because we want to mark its sizes
8956 and fields once it's filled in. */
8957 else if (!TYPE_IS_DUMMY_P (t))
8958 TREE_VISITED (t) = 1;
8959
8960 if (TYPE_P (t))
8961 TYPE_SIZES_GIMPLIFIED (t) = 1;
8962
8963 return NULL_TREE;
8964 }
8965
8966 /* Mark nodes rooted at T with TREE_VISITED and types as having their
8967 sized gimplified. We use this to indicate all variable sizes and
8968 positions in global types may not be shared by any subprogram. */
8969
8970 void
8971 mark_visited (tree t)
8972 {
8973 walk_tree (&t, mark_visited_r, NULL, NULL);
8974 }
8975
8976 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
8977 set its location to that of GNAT_NODE if present, but with column info
8978 cleared so that conditional branches generated as part of the cleanup
8979 code do not interfere with coverage analysis tools. */
8980
8981 static void
8982 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
8983 {
8984 if (Present (gnat_node))
8985 set_expr_location_from_node (gnu_cleanup, gnat_node, true);
8986 append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
8987 }
8988
8989 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK. */
8990
8991 void
8992 set_block_for_group (tree gnu_block)
8993 {
8994 gcc_assert (!current_stmt_group->block);
8995 current_stmt_group->block = gnu_block;
8996 }
8997
8998 /* Return code corresponding to the current code group. It is normally
8999 a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
9000 BLOCK or cleanups were set. */
9001
9002 tree
9003 end_stmt_group (void)
9004 {
9005 struct stmt_group *group = current_stmt_group;
9006 tree gnu_retval = group->stmt_list;
9007
9008 /* If this is a null list, allocate a new STATEMENT_LIST. Then, if there
9009 are cleanups, make a TRY_FINALLY_EXPR. Last, if there is a BLOCK,
9010 make a BIND_EXPR. Note that we nest in that because the cleanup may
9011 reference variables in the block. */
9012 if (!gnu_retval)
9013 gnu_retval = alloc_stmt_list ();
9014
9015 if (group->cleanups)
9016 gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
9017 group->cleanups);
9018
9019 if (current_stmt_group->block)
9020 gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
9021 gnu_retval, group->block);
9022
9023 /* Remove this group from the stack and add it to the free list. */
9024 current_stmt_group = group->previous;
9025 group->previous = stmt_group_free_list;
9026 stmt_group_free_list = group;
9027
9028 return gnu_retval;
9029 }
9030
9031 /* Return whether the current statement group may fall through. */
9032
9033 static inline bool
9034 stmt_group_may_fallthru (void)
9035 {
9036 if (current_stmt_group->stmt_list)
9037 return block_may_fallthru (current_stmt_group->stmt_list);
9038 else
9039 return true;
9040 }
9041
9042 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
9043 statements.*/
9044
9045 static void
9046 add_stmt_list (List_Id gnat_list)
9047 {
9048 Node_Id gnat_node;
9049
9050 if (Present (gnat_list))
9051 for (gnat_node = First (gnat_list); Present (gnat_node);
9052 gnat_node = Next (gnat_node))
9053 add_stmt (gnat_to_gnu (gnat_node));
9054 }
9055
9056 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
9057 If BINDING_P is true, push and pop a binding level around the list. */
9058
9059 static tree
9060 build_stmt_group (List_Id gnat_list, bool binding_p)
9061 {
9062 start_stmt_group ();
9063
9064 if (binding_p)
9065 gnat_pushlevel ();
9066
9067 add_stmt_list (gnat_list);
9068
9069 if (binding_p)
9070 gnat_poplevel ();
9071
9072 return end_stmt_group ();
9073 }
9074 \f
9075 /* Generate GIMPLE in place for the expression at *EXPR_P. */
9076
9077 int
9078 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
9079 gimple_seq *post_p ATTRIBUTE_UNUSED)
9080 {
9081 tree expr = *expr_p;
9082 tree type = TREE_TYPE (expr);
9083 tree op;
9084
9085 if (IS_ADA_STMT (expr))
9086 return gnat_gimplify_stmt (expr_p);
9087
9088 switch (TREE_CODE (expr))
9089 {
9090 case NULL_EXPR:
9091 /* If this is an aggregate type, build a null pointer of the appropriate
9092 type and dereference it. */
9093 if (AGGREGATE_TYPE_P (type)
9094 || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
9095 *expr_p = build_unary_op (INDIRECT_REF, NULL_TREE,
9096 convert (build_pointer_type (type),
9097 integer_zero_node));
9098 /* Otherwise, just make a VAR_DECL. */
9099 else
9100 {
9101 *expr_p = create_tmp_var (type, NULL);
9102 TREE_NO_WARNING (*expr_p) = 1;
9103 }
9104
9105 gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
9106 return GS_OK;
9107
9108 case UNCONSTRAINED_ARRAY_REF:
9109 /* We should only do this if we are just elaborating for side-effects,
9110 but we can't know that yet. */
9111 *expr_p = TREE_OPERAND (*expr_p, 0);
9112 return GS_OK;
9113
9114 case ADDR_EXPR:
9115 op = TREE_OPERAND (expr, 0);
9116
9117 /* If we are taking the address of a constant CONSTRUCTOR, make sure it
9118 is put into static memory. We know that it's going to be read-only
9119 given the semantics we have and it must be in static memory when the
9120 reference is in an elaboration procedure. */
9121 if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
9122 {
9123 tree addr = build_fold_addr_expr (tree_output_constant_def (op));
9124 *expr_p = fold_convert (type, addr);
9125 return GS_ALL_DONE;
9126 }
9127
9128 /* Replace atomic loads with their first argument. That's necessary
9129 because the gimplifier would create a temporary otherwise. */
9130 if (TREE_SIDE_EFFECTS (op))
9131 while (handled_component_p (op) || CONVERT_EXPR_P (op))
9132 {
9133 tree inner = TREE_OPERAND (op, 0);
9134 if (TREE_CODE (inner) == CALL_EXPR && call_is_atomic_load (inner))
9135 {
9136 tree t = CALL_EXPR_ARG (inner, 0);
9137 if (TREE_CODE (t) == NOP_EXPR)
9138 t = TREE_OPERAND (t, 0);
9139 if (TREE_CODE (t) == ADDR_EXPR)
9140 TREE_OPERAND (op, 0) = TREE_OPERAND (t, 0);
9141 else
9142 TREE_OPERAND (op, 0) = build_fold_indirect_ref (t);
9143 }
9144 else
9145 op = inner;
9146 }
9147
9148 return GS_UNHANDLED;
9149
9150 case VIEW_CONVERT_EXPR:
9151 op = TREE_OPERAND (expr, 0);
9152
9153 /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
9154 type to a scalar one, explicitly create the local temporary. That's
9155 required if the type is passed by reference. */
9156 if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
9157 && AGGREGATE_TYPE_P (TREE_TYPE (op))
9158 && !AGGREGATE_TYPE_P (type))
9159 {
9160 tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
9161 gimple_add_tmp_var (new_var);
9162
9163 mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
9164 gimplify_and_add (mod, pre_p);
9165
9166 TREE_OPERAND (expr, 0) = new_var;
9167 return GS_OK;
9168 }
9169
9170 return GS_UNHANDLED;
9171
9172 case DECL_EXPR:
9173 op = DECL_EXPR_DECL (expr);
9174
9175 /* The expressions for the RM bounds must be gimplified to ensure that
9176 they are properly elaborated. See gimplify_decl_expr. */
9177 if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
9178 && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
9179 switch (TREE_CODE (TREE_TYPE (op)))
9180 {
9181 case INTEGER_TYPE:
9182 case ENUMERAL_TYPE:
9183 case BOOLEAN_TYPE:
9184 case REAL_TYPE:
9185 {
9186 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
9187
9188 val = TYPE_RM_MIN_VALUE (type);
9189 if (val)
9190 {
9191 gimplify_one_sizepos (&val, pre_p);
9192 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
9193 SET_TYPE_RM_MIN_VALUE (t, val);
9194 }
9195
9196 val = TYPE_RM_MAX_VALUE (type);
9197 if (val)
9198 {
9199 gimplify_one_sizepos (&val, pre_p);
9200 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
9201 SET_TYPE_RM_MAX_VALUE (t, val);
9202 }
9203
9204 }
9205 break;
9206
9207 default:
9208 break;
9209 }
9210
9211 /* ... fall through ... */
9212
9213 default:
9214 return GS_UNHANDLED;
9215 }
9216 }
9217
9218 /* Generate GIMPLE in place for the statement at *STMT_P. */
9219
9220 static enum gimplify_status
9221 gnat_gimplify_stmt (tree *stmt_p)
9222 {
9223 tree stmt = *stmt_p;
9224
9225 switch (TREE_CODE (stmt))
9226 {
9227 case STMT_STMT:
9228 *stmt_p = STMT_STMT_STMT (stmt);
9229 return GS_OK;
9230
9231 case LOOP_STMT:
9232 {
9233 tree gnu_start_label = create_artificial_label (input_location);
9234 tree gnu_cond = LOOP_STMT_COND (stmt);
9235 tree gnu_update = LOOP_STMT_UPDATE (stmt);
9236 tree gnu_end_label = LOOP_STMT_LABEL (stmt);
9237
9238 /* Build the condition expression from the test, if any. */
9239 if (gnu_cond)
9240 {
9241 /* Deal with the optimization hints. */
9242 if (LOOP_STMT_IVDEP (stmt))
9243 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
9244 build_int_cst (integer_type_node,
9245 annot_expr_ivdep_kind),
9246 integer_zero_node);
9247 if (LOOP_STMT_NO_UNROLL (stmt))
9248 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
9249 build_int_cst (integer_type_node,
9250 annot_expr_unroll_kind),
9251 integer_one_node);
9252 if (LOOP_STMT_UNROLL (stmt))
9253 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
9254 build_int_cst (integer_type_node,
9255 annot_expr_unroll_kind),
9256 build_int_cst (NULL_TREE, USHRT_MAX));
9257 if (LOOP_STMT_NO_VECTOR (stmt))
9258 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
9259 build_int_cst (integer_type_node,
9260 annot_expr_no_vector_kind),
9261 integer_zero_node);
9262 if (LOOP_STMT_VECTOR (stmt))
9263 gnu_cond = build3 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
9264 build_int_cst (integer_type_node,
9265 annot_expr_vector_kind),
9266 integer_zero_node);
9267
9268 gnu_cond
9269 = build3 (COND_EXPR, void_type_node, gnu_cond, NULL_TREE,
9270 build1 (GOTO_EXPR, void_type_node, gnu_end_label));
9271 }
9272
9273 /* Set to emit the statements of the loop. */
9274 *stmt_p = NULL_TREE;
9275
9276 /* We first emit the start label and then a conditional jump to the
9277 end label if there's a top condition, then the update if it's at
9278 the top, then the body of the loop, then a conditional jump to
9279 the end label if there's a bottom condition, then the update if
9280 it's at the bottom, and finally a jump to the start label and the
9281 definition of the end label. */
9282 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
9283 gnu_start_label),
9284 stmt_p);
9285
9286 if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
9287 append_to_statement_list (gnu_cond, stmt_p);
9288
9289 if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
9290 append_to_statement_list (gnu_update, stmt_p);
9291
9292 append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
9293
9294 if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
9295 append_to_statement_list (gnu_cond, stmt_p);
9296
9297 if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
9298 append_to_statement_list (gnu_update, stmt_p);
9299
9300 tree t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
9301 SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
9302 append_to_statement_list (t, stmt_p);
9303
9304 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
9305 gnu_end_label),
9306 stmt_p);
9307 return GS_OK;
9308 }
9309
9310 case EXIT_STMT:
9311 /* Build a statement to jump to the corresponding end label, then
9312 see if it needs to be conditional. */
9313 *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
9314 if (EXIT_STMT_COND (stmt))
9315 *stmt_p = build3 (COND_EXPR, void_type_node,
9316 EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
9317 return GS_OK;
9318
9319 default:
9320 gcc_unreachable ();
9321 }
9322 }
9323 \f
9324 /* Force a reference to each of the entities in GNAT_PACKAGE recursively.
9325
9326 This routine is exclusively called in type_annotate mode, to compute DDA
9327 information for types in withed units, for ASIS use. */
9328
9329 static void
9330 elaborate_all_entities_for_package (Entity_Id gnat_package)
9331 {
9332 Entity_Id gnat_entity;
9333
9334 for (gnat_entity = First_Entity (gnat_package);
9335 Present (gnat_entity);
9336 gnat_entity = Next_Entity (gnat_entity))
9337 {
9338 const Entity_Kind kind = Ekind (gnat_entity);
9339
9340 /* We are interested only in entities visible from the main unit. */
9341 if (!Is_Public (gnat_entity))
9342 continue;
9343
9344 /* Skip stuff internal to the compiler. */
9345 if (Convention (gnat_entity) == Convention_Intrinsic)
9346 continue;
9347 if (kind == E_Operator)
9348 continue;
9349 if (IN (kind, Subprogram_Kind)
9350 && (Present (Alias (gnat_entity))
9351 || Is_Intrinsic_Subprogram (gnat_entity)))
9352 continue;
9353 if (Is_Itype (gnat_entity))
9354 continue;
9355
9356 /* Skip named numbers. */
9357 if (IN (kind, Named_Kind))
9358 continue;
9359
9360 /* Skip generic declarations. */
9361 if (IN (kind, Generic_Unit_Kind))
9362 continue;
9363
9364 /* Skip formal objects. */
9365 if (IN (kind, Formal_Object_Kind))
9366 continue;
9367
9368 /* Skip package bodies. */
9369 if (kind == E_Package_Body)
9370 continue;
9371
9372 /* Skip limited views that point back to the main unit. */
9373 if (IN (kind, Incomplete_Kind)
9374 && From_Limited_With (gnat_entity)
9375 && In_Extended_Main_Code_Unit (Non_Limited_View (gnat_entity)))
9376 continue;
9377
9378 /* Skip types that aren't frozen. */
9379 if (IN (kind, Type_Kind) && !Is_Frozen (gnat_entity))
9380 continue;
9381
9382 /* Recurse on real packages that aren't in the main unit. */
9383 if (kind == E_Package)
9384 {
9385 if (No (Renamed_Entity (gnat_entity))
9386 && !In_Extended_Main_Code_Unit (gnat_entity))
9387 elaborate_all_entities_for_package (gnat_entity);
9388 }
9389 else
9390 gnat_to_gnu_entity (gnat_entity, NULL_TREE, false);
9391 }
9392 }
9393
9394 /* Force a reference to each of the entities in packages withed by GNAT_NODE.
9395 Operate recursively but check that we aren't elaborating something more
9396 than once.
9397
9398 This routine is exclusively called in type_annotate mode, to compute DDA
9399 information for types in withed units, for ASIS use. */
9400
9401 static void
9402 elaborate_all_entities (Node_Id gnat_node)
9403 {
9404 Entity_Id gnat_with_clause;
9405
9406 /* Process each unit only once. As we trace the context of all relevant
9407 units transitively, including generic bodies, we may encounter the
9408 same generic unit repeatedly. */
9409 if (!present_gnu_tree (gnat_node))
9410 save_gnu_tree (gnat_node, integer_zero_node, true);
9411
9412 /* Save entities in all context units. A body may have an implicit_with
9413 on its own spec, if the context includes a child unit, so don't save
9414 the spec twice. */
9415 for (gnat_with_clause = First (Context_Items (gnat_node));
9416 Present (gnat_with_clause);
9417 gnat_with_clause = Next (gnat_with_clause))
9418 if (Nkind (gnat_with_clause) == N_With_Clause
9419 && !present_gnu_tree (Library_Unit (gnat_with_clause))
9420 && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
9421 {
9422 Node_Id gnat_unit = Library_Unit (gnat_with_clause);
9423 Entity_Id gnat_entity = Entity (Name (gnat_with_clause));
9424
9425 elaborate_all_entities (gnat_unit);
9426
9427 if (Ekind (gnat_entity) == E_Package
9428 && No (Renamed_Entity (gnat_entity)))
9429 elaborate_all_entities_for_package (gnat_entity);
9430
9431 else if (Ekind (gnat_entity) == E_Generic_Package)
9432 {
9433 Node_Id gnat_body = Corresponding_Body (Unit (gnat_unit));
9434
9435 /* Retrieve compilation unit node of generic body. */
9436 while (Present (gnat_body)
9437 && Nkind (gnat_body) != N_Compilation_Unit)
9438 gnat_body = Parent (gnat_body);
9439
9440 /* If body is available, elaborate its context. */
9441 if (Present (gnat_body))
9442 elaborate_all_entities (gnat_body);
9443 }
9444 }
9445
9446 if (Nkind (Unit (gnat_node)) == N_Package_Body)
9447 elaborate_all_entities (Library_Unit (gnat_node));
9448 }
9449 \f
9450 /* Do the processing of GNAT_NODE, an N_Freeze_Entity. */
9451
9452 static void
9453 process_freeze_entity (Node_Id gnat_node)
9454 {
9455 const Entity_Id gnat_entity = Entity (gnat_node);
9456 const Entity_Kind kind = Ekind (gnat_entity);
9457 tree gnu_old, gnu_new;
9458
9459 /* If this is a package, generate code for the package body, if any. */
9460 if (kind == E_Package)
9461 {
9462 const Node_Id gnat_decl = Parent (Declaration_Node (gnat_entity));
9463 if (Present (Corresponding_Body (gnat_decl)))
9464 insert_code_for (Parent (Corresponding_Body (gnat_decl)));
9465 return;
9466 }
9467
9468 /* Don't do anything for class-wide types as they are always transformed
9469 into their root type. */
9470 if (kind == E_Class_Wide_Type)
9471 return;
9472
9473 /* Check for an old definition if this isn't an object with address clause,
9474 since the saved GCC tree is the address expression in that case. */
9475 gnu_old
9476 = present_gnu_tree (gnat_entity) && No (Address_Clause (gnat_entity))
9477 ? get_gnu_tree (gnat_entity) : NULL_TREE;
9478
9479 /* Don't do anything for subprograms that may have been elaborated before
9480 their freeze nodes. This can happen, for example, because of an inner
9481 call in an instance body or because of previous compilation of a spec
9482 for inlining purposes. */
9483 if (gnu_old
9484 && ((TREE_CODE (gnu_old) == FUNCTION_DECL
9485 && (kind == E_Function || kind == E_Procedure))
9486 || (FUNC_OR_METHOD_TYPE_P (TREE_TYPE (gnu_old))
9487 && kind == E_Subprogram_Type)))
9488 return;
9489
9490 /* If we have a non-dummy type old tree, we have nothing to do, except for
9491 aborting, since this node was never delayed as it should have been. We
9492 let this happen for concurrent types and their Corresponding_Record_Type,
9493 however, because each might legitimately be elaborated before its own
9494 freeze node, e.g. while processing the other. */
9495 if (gnu_old
9496 && !(TREE_CODE (gnu_old) == TYPE_DECL
9497 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
9498 {
9499 gcc_assert (Is_Concurrent_Type (gnat_entity)
9500 || (Is_Record_Type (gnat_entity)
9501 && Is_Concurrent_Record_Type (gnat_entity)));
9502 return;
9503 }
9504
9505 /* Reset the saved tree, if any, and elaborate the object or type for real.
9506 If there is a full view, elaborate it and use the result. And, if this
9507 is the root type of a class-wide type, reuse it for the latter. */
9508 if (gnu_old)
9509 {
9510 save_gnu_tree (gnat_entity, NULL_TREE, false);
9511
9512 if (Is_Incomplete_Or_Private_Type (gnat_entity)
9513 && Present (Full_View (gnat_entity)))
9514 {
9515 Entity_Id full_view = Full_View (gnat_entity);
9516
9517 save_gnu_tree (full_view, NULL_TREE, false);
9518
9519 if (Is_Private_Type (full_view)
9520 && Present (Underlying_Full_View (full_view)))
9521 {
9522 full_view = Underlying_Full_View (full_view);
9523 save_gnu_tree (full_view, NULL_TREE, false);
9524 }
9525 }
9526
9527 if (Is_Type (gnat_entity)
9528 && Present (Class_Wide_Type (gnat_entity))
9529 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
9530 save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
9531 }
9532
9533 if (Is_Incomplete_Or_Private_Type (gnat_entity)
9534 && Present (Full_View (gnat_entity)))
9535 {
9536 Entity_Id full_view = Full_View (gnat_entity);
9537
9538 if (Is_Private_Type (full_view)
9539 && Present (Underlying_Full_View (full_view)))
9540 full_view = Underlying_Full_View (full_view);
9541
9542 gnu_new = gnat_to_gnu_entity (full_view, NULL_TREE, true);
9543
9544 /* Propagate back-annotations from full view to partial view. */
9545 if (Unknown_Alignment (gnat_entity))
9546 Set_Alignment (gnat_entity, Alignment (full_view));
9547
9548 if (Unknown_Esize (gnat_entity))
9549 Set_Esize (gnat_entity, Esize (full_view));
9550
9551 if (Unknown_RM_Size (gnat_entity))
9552 Set_RM_Size (gnat_entity, RM_Size (full_view));
9553
9554 /* The above call may have defined this entity (the simplest example
9555 of this is when we have a private enumeral type since the bounds
9556 will have the public view). */
9557 if (!present_gnu_tree (gnat_entity))
9558 save_gnu_tree (gnat_entity, gnu_new, false);
9559 }
9560 else
9561 {
9562 tree gnu_init
9563 = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
9564 && present_gnu_tree (Declaration_Node (gnat_entity)))
9565 ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
9566
9567 gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, true);
9568 }
9569
9570 if (Is_Type (gnat_entity)
9571 && Present (Class_Wide_Type (gnat_entity))
9572 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
9573 save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
9574
9575 /* If we have an old type and we've made pointers to this type, update those
9576 pointers. If this is a Taft amendment type in the main unit, we need to
9577 mark the type as used since other units referencing it don't see the full
9578 declaration and, therefore, cannot mark it as used themselves. */
9579 if (gnu_old)
9580 {
9581 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
9582 TREE_TYPE (gnu_new));
9583 if (TYPE_DUMMY_IN_PROFILE_P (TREE_TYPE (gnu_old)))
9584 update_profiles_with (TREE_TYPE (gnu_old));
9585 if (DECL_TAFT_TYPE_P (gnu_old))
9586 used_types_insert (TREE_TYPE (gnu_new));
9587 }
9588 }
9589 \f
9590 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
9591 We make two passes, one to elaborate anything other than bodies (but
9592 we declare a function if there was no spec). The second pass
9593 elaborates the bodies.
9594
9595 GNAT_END_LIST gives the element in the list past the end. Normally,
9596 this is Empty, but can be First_Real_Statement for a
9597 Handled_Sequence_Of_Statements.
9598
9599 We make a complete pass through both lists if PASS1P is true, then make
9600 the second pass over both lists if PASS2P is true. The lists usually
9601 correspond to the public and private parts of a package. */
9602
9603 static void
9604 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
9605 Node_Id gnat_end_list, bool pass1p, bool pass2p)
9606 {
9607 List_Id gnat_decl_array[2];
9608 Node_Id gnat_decl;
9609 int i;
9610
9611 gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
9612
9613 if (pass1p)
9614 for (i = 0; i <= 1; i++)
9615 if (Present (gnat_decl_array[i]))
9616 for (gnat_decl = First (gnat_decl_array[i]);
9617 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
9618 {
9619 /* For package specs, we recurse inside the declarations,
9620 thus taking the two pass approach inside the boundary. */
9621 if (Nkind (gnat_decl) == N_Package_Declaration
9622 && (Nkind (Specification (gnat_decl)
9623 == N_Package_Specification)))
9624 process_decls (Visible_Declarations (Specification (gnat_decl)),
9625 Private_Declarations (Specification (gnat_decl)),
9626 Empty, true, false);
9627
9628 /* Similarly for any declarations in the actions of a
9629 freeze node. */
9630 else if (Nkind (gnat_decl) == N_Freeze_Entity)
9631 {
9632 process_freeze_entity (gnat_decl);
9633 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
9634 }
9635
9636 /* Package bodies with freeze nodes get their elaboration deferred
9637 until the freeze node, but the code must be placed in the right
9638 place, so record the code position now. */
9639 else if (Nkind (gnat_decl) == N_Package_Body
9640 && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
9641 record_code_position (gnat_decl);
9642
9643 else if (Nkind (gnat_decl) == N_Package_Body_Stub
9644 && Present (Library_Unit (gnat_decl))
9645 && Present (Freeze_Node
9646 (Corresponding_Spec
9647 (Proper_Body (Unit
9648 (Library_Unit (gnat_decl)))))))
9649 record_code_position
9650 (Proper_Body (Unit (Library_Unit (gnat_decl))));
9651
9652 /* We defer most subprogram bodies to the second pass. */
9653 else if (Nkind (gnat_decl) == N_Subprogram_Body)
9654 {
9655 if (Acts_As_Spec (gnat_decl))
9656 {
9657 Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
9658
9659 if (Ekind (gnat_subprog_id) != E_Generic_Procedure
9660 && Ekind (gnat_subprog_id) != E_Generic_Function)
9661 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, true);
9662 }
9663 }
9664
9665 /* For bodies and stubs that act as their own specs, the entity
9666 itself must be elaborated in the first pass, because it may
9667 be used in other declarations. */
9668 else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
9669 {
9670 Node_Id gnat_subprog_id
9671 = Defining_Entity (Specification (gnat_decl));
9672
9673 if (Ekind (gnat_subprog_id) != E_Subprogram_Body
9674 && Ekind (gnat_subprog_id) != E_Generic_Procedure
9675 && Ekind (gnat_subprog_id) != E_Generic_Function)
9676 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, true);
9677 }
9678
9679 /* Concurrent stubs stand for the corresponding subprogram bodies,
9680 which are deferred like other bodies. */
9681 else if (Nkind (gnat_decl) == N_Task_Body_Stub
9682 || Nkind (gnat_decl) == N_Protected_Body_Stub)
9683 ;
9684
9685 /* Renamed subprograms may not be elaborated yet at this point
9686 since renamings do not trigger freezing. Wait for the second
9687 pass to take care of them. */
9688 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
9689 ;
9690
9691 else
9692 add_stmt (gnat_to_gnu (gnat_decl));
9693 }
9694
9695 /* Here we elaborate everything we deferred above except for package bodies,
9696 which are elaborated at their freeze nodes. Note that we must also
9697 go inside things (package specs and freeze nodes) the first pass did. */
9698 if (pass2p)
9699 for (i = 0; i <= 1; i++)
9700 if (Present (gnat_decl_array[i]))
9701 for (gnat_decl = First (gnat_decl_array[i]);
9702 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
9703 {
9704 if (Nkind (gnat_decl) == N_Subprogram_Body
9705 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
9706 || Nkind (gnat_decl) == N_Task_Body_Stub
9707 || Nkind (gnat_decl) == N_Protected_Body_Stub)
9708 add_stmt (gnat_to_gnu (gnat_decl));
9709
9710 else if (Nkind (gnat_decl) == N_Package_Declaration
9711 && (Nkind (Specification (gnat_decl)
9712 == N_Package_Specification)))
9713 process_decls (Visible_Declarations (Specification (gnat_decl)),
9714 Private_Declarations (Specification (gnat_decl)),
9715 Empty, false, true);
9716
9717 else if (Nkind (gnat_decl) == N_Freeze_Entity)
9718 process_decls (Actions (gnat_decl), Empty, Empty, false, true);
9719
9720 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
9721 add_stmt (gnat_to_gnu (gnat_decl));
9722 }
9723 }
9724 \f
9725 /* Make a unary operation of kind CODE using build_unary_op, but guard
9726 the operation by an overflow check. CODE can be one of NEGATE_EXPR
9727 or ABS_EXPR. GNU_TYPE is the type desired for the result. Usually
9728 the operation is to be performed in that type. GNAT_NODE is the gnat
9729 node conveying the source location for which the error should be
9730 signaled. */
9731
9732 static tree
9733 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
9734 Node_Id gnat_node)
9735 {
9736 gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
9737
9738 operand = gnat_protect_expr (operand);
9739
9740 return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
9741 operand, TYPE_MIN_VALUE (gnu_type)),
9742 build_unary_op (code, gnu_type, operand),
9743 CE_Overflow_Check_Failed, gnat_node);
9744 }
9745
9746 /* Make a binary operation of kind CODE using build_binary_op, but guard
9747 the operation by an overflow check. CODE can be one of PLUS_EXPR,
9748 MINUS_EXPR or MULT_EXPR. GNU_TYPE is the type desired for the result.
9749 Usually the operation is to be performed in that type. GNAT_NODE is
9750 the GNAT node conveying the source location for which the error should
9751 be signaled. */
9752
9753 static tree
9754 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
9755 tree right, Node_Id gnat_node)
9756 {
9757 const unsigned int precision = TYPE_PRECISION (gnu_type);
9758 tree lhs = gnat_protect_expr (left);
9759 tree rhs = gnat_protect_expr (right);
9760 tree type_max = TYPE_MAX_VALUE (gnu_type);
9761 tree type_min = TYPE_MIN_VALUE (gnu_type);
9762 tree gnu_expr, check;
9763 int sgn;
9764
9765 /* Assert that the precision is a power of 2. */
9766 gcc_assert ((precision & (precision - 1)) == 0);
9767
9768 /* Prefer a constant on the RHS to simplify checks. */
9769 if (TREE_CODE (rhs) != INTEGER_CST
9770 && TREE_CODE (lhs) == INTEGER_CST
9771 && (code == PLUS_EXPR || code == MULT_EXPR))
9772 {
9773 tree tmp = lhs;
9774 lhs = rhs;
9775 rhs = tmp;
9776 }
9777
9778 gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
9779
9780 /* If we can fold the expression to a constant, just return it.
9781 The caller will deal with overflow, no need to generate a check. */
9782 if (TREE_CODE (gnu_expr) == INTEGER_CST)
9783 return gnu_expr;
9784
9785 /* If no operand is a constant, we use the generic implementation. */
9786 if (TREE_CODE (lhs) != INTEGER_CST && TREE_CODE (rhs) != INTEGER_CST)
9787 {
9788 /* Never inline a 64-bit mult for a 32-bit target, it's way too long. */
9789 if (code == MULT_EXPR && precision == 64 && BITS_PER_WORD < 64)
9790 {
9791 tree int64 = gnat_type_for_size (64, 0);
9792 return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
9793 convert (int64, lhs),
9794 convert (int64, rhs)));
9795 }
9796
9797 enum internal_fn icode;
9798
9799 switch (code)
9800 {
9801 case PLUS_EXPR:
9802 icode = IFN_ADD_OVERFLOW;
9803 break;
9804 case MINUS_EXPR:
9805 icode = IFN_SUB_OVERFLOW;
9806 break;
9807 case MULT_EXPR:
9808 icode = IFN_MUL_OVERFLOW;
9809 break;
9810 default:
9811 gcc_unreachable ();
9812 }
9813
9814 tree gnu_ctype = build_complex_type (gnu_type);
9815 tree call
9816 = build_call_expr_internal_loc (UNKNOWN_LOCATION, icode, gnu_ctype, 2,
9817 lhs, rhs);
9818 tree tgt = save_expr (call);
9819 gnu_expr = build1 (REALPART_EXPR, gnu_type, tgt);
9820 check = fold_build2 (NE_EXPR, boolean_type_node,
9821 build1 (IMAGPART_EXPR, gnu_type, tgt),
9822 build_int_cst (gnu_type, 0));
9823 return
9824 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
9825 }
9826
9827 /* If one operand is a constant, we expose the overflow condition to enable
9828 a subsequent simplication or even elimination. */
9829 switch (code)
9830 {
9831 case PLUS_EXPR:
9832 sgn = tree_int_cst_sgn (rhs);
9833 if (sgn > 0)
9834 /* When rhs > 0, overflow when lhs > type_max - rhs. */
9835 check = build_binary_op (GT_EXPR, boolean_type_node, lhs,
9836 build_binary_op (MINUS_EXPR, gnu_type,
9837 type_max, rhs));
9838 else if (sgn < 0)
9839 /* When rhs < 0, overflow when lhs < type_min - rhs. */
9840 check = build_binary_op (LT_EXPR, boolean_type_node, lhs,
9841 build_binary_op (MINUS_EXPR, gnu_type,
9842 type_min, rhs));
9843 else
9844 return gnu_expr;
9845 break;
9846
9847 case MINUS_EXPR:
9848 if (TREE_CODE (lhs) == INTEGER_CST)
9849 {
9850 sgn = tree_int_cst_sgn (lhs);
9851 if (sgn > 0)
9852 /* When lhs > 0, overflow when rhs < lhs - type_max. */
9853 check = build_binary_op (LT_EXPR, boolean_type_node, rhs,
9854 build_binary_op (MINUS_EXPR, gnu_type,
9855 lhs, type_max));
9856 else if (sgn < 0)
9857 /* When lhs < 0, overflow when rhs > lhs - type_min. */
9858 check = build_binary_op (GT_EXPR, boolean_type_node, rhs,
9859 build_binary_op (MINUS_EXPR, gnu_type,
9860 lhs, type_min));
9861 else
9862 return gnu_expr;
9863 }
9864 else
9865 {
9866 sgn = tree_int_cst_sgn (rhs);
9867 if (sgn > 0)
9868 /* When rhs > 0, overflow when lhs < type_min + rhs. */
9869 check = build_binary_op (LT_EXPR, boolean_type_node, lhs,
9870 build_binary_op (PLUS_EXPR, gnu_type,
9871 type_min, rhs));
9872 else if (sgn < 0)
9873 /* When rhs < 0, overflow when lhs > type_max + rhs. */
9874 check = build_binary_op (GT_EXPR, boolean_type_node, lhs,
9875 build_binary_op (PLUS_EXPR, gnu_type,
9876 type_max, rhs));
9877 else
9878 return gnu_expr;
9879 }
9880 break;
9881
9882 case MULT_EXPR:
9883 sgn = tree_int_cst_sgn (rhs);
9884 if (sgn > 0)
9885 {
9886 if (integer_onep (rhs))
9887 return gnu_expr;
9888
9889 tree lb = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
9890 tree ub = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
9891
9892 /* When rhs > 1, overflow outside [type_min/rhs; type_max/rhs]. */
9893 check
9894 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9895 build_binary_op (LT_EXPR, boolean_type_node,
9896 lhs, lb),
9897 build_binary_op (GT_EXPR, boolean_type_node,
9898 lhs, ub));
9899 }
9900 else if (sgn < 0)
9901 {
9902 tree lb = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
9903 tree ub = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
9904
9905 if (integer_minus_onep (rhs))
9906 /* When rhs == -1, overflow if lhs == type_min. */
9907 check
9908 = build_binary_op (EQ_EXPR, boolean_type_node, lhs, type_min);
9909 else
9910 /* When rhs < -1, overflow outside [type_max/rhs; type_min/rhs]. */
9911 check
9912 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9913 build_binary_op (LT_EXPR, boolean_type_node,
9914 lhs, lb),
9915 build_binary_op (GT_EXPR, boolean_type_node,
9916 lhs, ub));
9917 }
9918 else
9919 return gnu_expr;
9920 break;
9921
9922 default:
9923 gcc_unreachable ();
9924 }
9925
9926 return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
9927 }
9928
9929 /* Emit code for a range check. GNU_EXPR is the expression to be checked,
9930 GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
9931 which we have to check. GNAT_NODE is the GNAT node conveying the source
9932 location for which the error should be signaled. */
9933
9934 static tree
9935 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type, Node_Id gnat_node)
9936 {
9937 tree gnu_range_type = get_unpadded_type (gnat_range_type);
9938 tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
9939
9940 /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
9941 This can for example happen when translating 'Val or 'Value. */
9942 if (gnu_compare_type == gnu_range_type)
9943 return gnu_expr;
9944
9945 /* Range checks can only be applied to types with ranges. */
9946 gcc_assert (INTEGRAL_TYPE_P (gnu_range_type)
9947 || SCALAR_FLOAT_TYPE_P (gnu_range_type));
9948
9949 /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
9950 we can't do anything since we might be truncating the bounds. No
9951 check is needed in this case. */
9952 if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
9953 && (TYPE_PRECISION (gnu_compare_type)
9954 < TYPE_PRECISION (get_base_type (gnu_range_type))))
9955 return gnu_expr;
9956
9957 /* Checked expressions must be evaluated only once. */
9958 gnu_expr = gnat_protect_expr (gnu_expr);
9959
9960 /* Note that the form of the check is
9961 (not (expr >= lo)) or (not (expr <= hi))
9962 the reason for this slightly convoluted form is that NaNs
9963 are not considered to be in range in the float case. */
9964 return emit_check
9965 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9966 invert_truthvalue
9967 (build_binary_op (GE_EXPR, boolean_type_node,
9968 convert (gnu_compare_type, gnu_expr),
9969 convert (gnu_compare_type,
9970 TYPE_MIN_VALUE
9971 (gnu_range_type)))),
9972 invert_truthvalue
9973 (build_binary_op (LE_EXPR, boolean_type_node,
9974 convert (gnu_compare_type, gnu_expr),
9975 convert (gnu_compare_type,
9976 TYPE_MAX_VALUE
9977 (gnu_range_type))))),
9978 gnu_expr, CE_Range_Check_Failed, gnat_node);
9979 }
9980 \f
9981 /* GNU_COND contains the condition corresponding to an index, overflow or
9982 range check of value GNU_EXPR. Build a COND_EXPR that returns GNU_EXPR
9983 if GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
9984 REASON is the code that says why the exception is raised. GNAT_NODE is
9985 the node conveying the source location for which the error should be
9986 signaled.
9987
9988 We used to propagate TREE_SIDE_EFFECTS from GNU_EXPR to the COND_EXPR,
9989 overwriting the setting inherited from the call statement, on the ground
9990 that the expression need not be evaluated just for the check. However
9991 that's incorrect because, in the GCC type system, its value is presumed
9992 to be valid so its comparison against the type bounds always yields true
9993 and, therefore, could be done without evaluating it; given that it can
9994 be a computation that overflows the bounds, the language may require the
9995 check to fail and thus the expression to be evaluated in this case. */
9996
9997 static tree
9998 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
9999 {
10000 tree gnu_call
10001 = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
10002 return
10003 fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
10004 build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
10005 SCALAR_FLOAT_TYPE_P (TREE_TYPE (gnu_expr))
10006 ? build_real (TREE_TYPE (gnu_expr), dconst0)
10007 : build_int_cst (TREE_TYPE (gnu_expr), 0)),
10008 gnu_expr);
10009 }
10010 \f
10011 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
10012 checks if OVERFLOW_P is true and range checks if RANGE_P is true.
10013 If TRUNCATE_P true, do a float-to-integer conversion with truncation,
10014 otherwise round. GNAT_NODE is the GNAT node conveying the source location
10015 for which the error should be signaled. */
10016
10017 static tree
10018 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflow_p,
10019 bool range_p, bool truncate_p, Node_Id gnat_node)
10020 {
10021 tree gnu_type = get_unpadded_type (gnat_type);
10022 tree gnu_base_type = get_base_type (gnu_type);
10023 tree gnu_in_type = TREE_TYPE (gnu_expr);
10024 tree gnu_in_base_type = get_base_type (gnu_in_type);
10025 tree gnu_result = gnu_expr;
10026
10027 /* If we are not doing any checks, the output is an integral type and the
10028 input is not a floating-point type, just do the conversion. This is
10029 required for packed array types and is simpler in all cases anyway. */
10030 if (!range_p
10031 && !overflow_p
10032 && INTEGRAL_TYPE_P (gnu_base_type)
10033 && !FLOAT_TYPE_P (gnu_in_base_type))
10034 return convert (gnu_type, gnu_expr);
10035
10036 /* If the mode of the input base type is larger, then converting to it below
10037 may pessimize the final conversion step, for example generate a libcall
10038 instead of a simple instruction, so use a narrower type in this case. */
10039 if (TYPE_MODE (gnu_in_base_type) != TYPE_MODE (gnu_in_type)
10040 && !(TREE_CODE (gnu_in_type) == INTEGER_TYPE
10041 && TYPE_BIASED_REPRESENTATION_P (gnu_in_type)))
10042 gnu_in_base_type = gnat_type_for_mode (TYPE_MODE (gnu_in_type),
10043 TYPE_UNSIGNED (gnu_in_type));
10044
10045 /* First convert the expression to the base type. This will never generate
10046 code, but makes the tests below simpler. But don't do this if converting
10047 from an integer type to an unconstrained array type since then we need to
10048 get the bounds from the original (unpacked) type. */
10049 if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
10050 gnu_result = convert (gnu_in_base_type, gnu_result);
10051
10052 /* If overflow checks are requested, we need to be sure the result will fit
10053 in the output base type. But don't do this if the input is integer and
10054 the output floating-point. */
10055 if (overflow_p
10056 && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_base_type)))
10057 {
10058 /* Ensure GNU_EXPR only gets evaluated once. */
10059 tree gnu_input = gnat_protect_expr (gnu_result);
10060 tree gnu_cond = boolean_false_node;
10061 tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_base_type);
10062 tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_base_type);
10063 tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
10064 tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
10065
10066 /* Convert the lower bounds to signed types, so we're sure we're
10067 comparing them properly. Likewise, convert the upper bounds
10068 to unsigned types. */
10069 if (INTEGRAL_TYPE_P (gnu_in_base_type)
10070 && TYPE_UNSIGNED (gnu_in_base_type))
10071 gnu_in_lb
10072 = convert (gnat_signed_type_for (gnu_in_base_type), gnu_in_lb);
10073
10074 if (INTEGRAL_TYPE_P (gnu_in_base_type)
10075 && !TYPE_UNSIGNED (gnu_in_base_type))
10076 gnu_in_ub
10077 = convert (gnat_unsigned_type_for (gnu_in_base_type), gnu_in_ub);
10078
10079 if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
10080 gnu_out_lb
10081 = convert (gnat_signed_type_for (gnu_base_type), gnu_out_lb);
10082
10083 if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
10084 gnu_out_ub
10085 = convert (gnat_unsigned_type_for (gnu_base_type), gnu_out_ub);
10086
10087 /* Check each bound separately and only if the result bound
10088 is tighter than the bound on the input type. Note that all the
10089 types are base types, so the bounds must be constant. Also,
10090 the comparison is done in the base type of the input, which
10091 always has the proper signedness. First check for input
10092 integer (which means output integer), output float (which means
10093 both float), or mixed, in which case we always compare.
10094 Note that we have to do the comparison which would *fail* in the
10095 case of an error since if it's an FP comparison and one of the
10096 values is a NaN or Inf, the comparison will fail. */
10097 if (INTEGRAL_TYPE_P (gnu_in_base_type)
10098 ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
10099 : (FLOAT_TYPE_P (gnu_base_type)
10100 ? real_less (&TREE_REAL_CST (gnu_in_lb),
10101 &TREE_REAL_CST (gnu_out_lb))
10102 : 1))
10103 gnu_cond
10104 = invert_truthvalue
10105 (build_binary_op (GE_EXPR, boolean_type_node,
10106 gnu_input, convert (gnu_in_base_type,
10107 gnu_out_lb)));
10108
10109 if (INTEGRAL_TYPE_P (gnu_in_base_type)
10110 ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
10111 : (FLOAT_TYPE_P (gnu_base_type)
10112 ? real_less (&TREE_REAL_CST (gnu_out_ub),
10113 &TREE_REAL_CST (gnu_in_ub))
10114 : 1))
10115 gnu_cond
10116 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
10117 invert_truthvalue
10118 (build_binary_op (LE_EXPR, boolean_type_node,
10119 gnu_input,
10120 convert (gnu_in_base_type,
10121 gnu_out_ub))));
10122
10123 if (!integer_zerop (gnu_cond))
10124 gnu_result = emit_check (gnu_cond, gnu_input,
10125 CE_Overflow_Check_Failed, gnat_node);
10126 }
10127
10128 /* Now convert to the result base type. If this is a non-truncating
10129 float-to-integer conversion, round. */
10130 if (INTEGRAL_TYPE_P (gnu_base_type)
10131 && FLOAT_TYPE_P (gnu_in_base_type)
10132 && !truncate_p)
10133 {
10134 REAL_VALUE_TYPE half_minus_pred_half, pred_half;
10135 tree gnu_conv, gnu_zero, gnu_comp, calc_type;
10136 tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
10137 const struct real_format *fmt;
10138
10139 /* The following calculations depend on proper rounding to even
10140 of each arithmetic operation. In order to prevent excess
10141 precision from spoiling this property, use the widest hardware
10142 floating-point type if FP_ARITH_MAY_WIDEN is true. */
10143 calc_type
10144 = fp_arith_may_widen ? longest_float_type_node : gnu_in_base_type;
10145
10146 /* Compute the exact value calc_type'Pred (0.5) at compile time. */
10147 fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
10148 real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
10149 real_arithmetic (&pred_half, MINUS_EXPR, &dconsthalf,
10150 &half_minus_pred_half);
10151 gnu_pred_half = build_real (calc_type, pred_half);
10152
10153 /* If the input is strictly negative, subtract this value
10154 and otherwise add it from the input. For 0.5, the result
10155 is exactly between 1.0 and the machine number preceding 1.0
10156 (for calc_type). Since the last bit of 1.0 is even, this 0.5
10157 will round to 1.0, while all other number with an absolute
10158 value less than 0.5 round to 0.0. For larger numbers exactly
10159 halfway between integers, rounding will always be correct as
10160 the true mathematical result will be closer to the higher
10161 integer compared to the lower one. So, this constant works
10162 for all floating-point numbers.
10163
10164 The reason to use the same constant with subtract/add instead
10165 of a positive and negative constant is to allow the comparison
10166 to be scheduled in parallel with retrieval of the constant and
10167 conversion of the input to the calc_type (if necessary). */
10168
10169 gnu_zero = build_real (gnu_in_base_type, dconst0);
10170 gnu_result = gnat_protect_expr (gnu_result);
10171 gnu_conv = convert (calc_type, gnu_result);
10172 gnu_comp
10173 = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
10174 gnu_add_pred_half
10175 = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
10176 gnu_subtract_pred_half
10177 = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
10178 gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
10179 gnu_add_pred_half, gnu_subtract_pred_half);
10180 }
10181
10182 if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
10183 && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
10184 && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
10185 gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
10186 else
10187 gnu_result = convert (gnu_base_type, gnu_result);
10188
10189 /* Finally, do the range check if requested. Note that if the result type
10190 is a modular type, the range check is actually an overflow check. */
10191 if (range_p
10192 || (overflow_p
10193 && TREE_CODE (gnu_base_type) == INTEGER_TYPE
10194 && TYPE_MODULAR_P (gnu_base_type)))
10195 gnu_result = emit_range_check (gnu_result, gnat_type, gnat_node);
10196
10197 return convert (gnu_type, gnu_result);
10198 }
10199 \f
10200 /* Return true if GNU_EXPR can be directly addressed. This is the case
10201 unless it is an expression involving computation or if it involves a
10202 reference to a bitfield or to an object not sufficiently aligned for
10203 its type. If GNU_TYPE is non-null, return true only if GNU_EXPR can
10204 be directly addressed as an object of this type.
10205
10206 *** Notes on addressability issues in the Ada compiler ***
10207
10208 This predicate is necessary in order to bridge the gap between Gigi
10209 and the middle-end about addressability of GENERIC trees. A tree
10210 is said to be addressable if it can be directly addressed, i.e. if
10211 its address can be taken, is a multiple of the type's alignment on
10212 strict-alignment architectures and returns the first storage unit
10213 assigned to the object represented by the tree.
10214
10215 In the C family of languages, everything is in practice addressable
10216 at the language level, except for bit-fields. This means that these
10217 compilers will take the address of any tree that doesn't represent
10218 a bit-field reference and expect the result to be the first storage
10219 unit assigned to the object. Even in cases where this will result
10220 in unaligned accesses at run time, nothing is supposed to be done
10221 and the program is considered as erroneous instead (see PR c/18287).
10222
10223 The implicit assumptions made in the middle-end are in keeping with
10224 the C viewpoint described above:
10225 - the address of a bit-field reference is supposed to be never
10226 taken; the compiler (generally) will stop on such a construct,
10227 - any other tree is addressable if it is formally addressable,
10228 i.e. if it is formally allowed to be the operand of ADDR_EXPR.
10229
10230 In Ada, the viewpoint is the opposite one: nothing is addressable
10231 at the language level unless explicitly declared so. This means
10232 that the compiler will both make sure that the trees representing
10233 references to addressable ("aliased" in Ada parlance) objects are
10234 addressable and make no real attempts at ensuring that the trees
10235 representing references to non-addressable objects are addressable.
10236
10237 In the first case, Ada is effectively equivalent to C and handing
10238 down the direct result of applying ADDR_EXPR to these trees to the
10239 middle-end works flawlessly. In the second case, Ada cannot afford
10240 to consider the program as erroneous if the address of trees that
10241 are not addressable is requested for technical reasons, unlike C;
10242 as a consequence, the Ada compiler must arrange for either making
10243 sure that this address is not requested in the middle-end or for
10244 compensating by inserting temporaries if it is requested in Gigi.
10245
10246 The first goal can be achieved because the middle-end should not
10247 request the address of non-addressable trees on its own; the only
10248 exception is for the invocation of low-level block operations like
10249 memcpy, for which the addressability requirements are lower since
10250 the type's alignment can be disregarded. In practice, this means
10251 that Gigi must make sure that such operations cannot be applied to
10252 non-BLKmode bit-fields.
10253
10254 The second goal is achieved by means of the addressable_p predicate,
10255 which computes whether a temporary must be inserted by Gigi when the
10256 address of a tree is requested; if so, the address of the temporary
10257 will be used in lieu of that of the original tree and some glue code
10258 generated to connect everything together. */
10259
10260 static bool
10261 addressable_p (tree gnu_expr, tree gnu_type)
10262 {
10263 /* For an integral type, the size of the actual type of the object may not
10264 be greater than that of the expected type, otherwise an indirect access
10265 in the latter type wouldn't correctly set all the bits of the object. */
10266 if (gnu_type
10267 && INTEGRAL_TYPE_P (gnu_type)
10268 && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
10269 return false;
10270
10271 /* The size of the actual type of the object may not be smaller than that
10272 of the expected type, otherwise an indirect access in the latter type
10273 would be larger than the object. But only record types need to be
10274 considered in practice for this case. */
10275 if (gnu_type
10276 && TREE_CODE (gnu_type) == RECORD_TYPE
10277 && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
10278 return false;
10279
10280 switch (TREE_CODE (gnu_expr))
10281 {
10282 case VAR_DECL:
10283 case PARM_DECL:
10284 case FUNCTION_DECL:
10285 case RESULT_DECL:
10286 /* All DECLs are addressable: if they are in a register, we can force
10287 them to memory. */
10288 return true;
10289
10290 case UNCONSTRAINED_ARRAY_REF:
10291 case INDIRECT_REF:
10292 /* Taking the address of a dereference yields the original pointer. */
10293 return true;
10294
10295 case STRING_CST:
10296 case INTEGER_CST:
10297 /* Taking the address yields a pointer to the constant pool. */
10298 return true;
10299
10300 case CONSTRUCTOR:
10301 /* Taking the address of a static constructor yields a pointer to the
10302 tree constant pool. */
10303 return TREE_STATIC (gnu_expr) ? true : false;
10304
10305 case NULL_EXPR:
10306 case SAVE_EXPR:
10307 case CALL_EXPR:
10308 case PLUS_EXPR:
10309 case MINUS_EXPR:
10310 case BIT_IOR_EXPR:
10311 case BIT_XOR_EXPR:
10312 case BIT_AND_EXPR:
10313 case BIT_NOT_EXPR:
10314 /* All rvalues are deemed addressable since taking their address will
10315 force a temporary to be created by the middle-end. */
10316 return true;
10317
10318 case COMPOUND_EXPR:
10319 /* The address of a compound expression is that of its 2nd operand. */
10320 return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
10321
10322 case COND_EXPR:
10323 /* We accept &COND_EXPR as soon as both operands are addressable and
10324 expect the outcome to be the address of the selected operand. */
10325 return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
10326 && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
10327
10328 case COMPONENT_REF:
10329 return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
10330 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
10331 the field is sufficiently aligned, in case it is subject
10332 to a pragma Component_Alignment. But we don't need to
10333 check the alignment of the containing record, as it is
10334 guaranteed to be not smaller than that of its most
10335 aligned field that is not a bit-field. */
10336 && (!STRICT_ALIGNMENT
10337 || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
10338 >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
10339 /* The field of a padding record is always addressable. */
10340 || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
10341 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
10342
10343 case ARRAY_REF: case ARRAY_RANGE_REF:
10344 case REALPART_EXPR: case IMAGPART_EXPR:
10345 case NOP_EXPR:
10346 return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
10347
10348 case CONVERT_EXPR:
10349 return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
10350 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
10351
10352 case VIEW_CONVERT_EXPR:
10353 {
10354 /* This is addressable if we can avoid a copy. */
10355 tree type = TREE_TYPE (gnu_expr);
10356 tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
10357 return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
10358 && (!STRICT_ALIGNMENT
10359 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
10360 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
10361 || ((TYPE_MODE (type) == BLKmode
10362 || TYPE_MODE (inner_type) == BLKmode)
10363 && (!STRICT_ALIGNMENT
10364 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
10365 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
10366 || TYPE_ALIGN_OK (type)
10367 || TYPE_ALIGN_OK (inner_type))))
10368 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
10369 }
10370
10371 default:
10372 return false;
10373 }
10374 }
10375 \f
10376 /* Do the processing for the declaration of a GNAT_ENTITY, a type or subtype.
10377 If a Freeze node exists for the entity, delay the bulk of the processing.
10378 Otherwise make a GCC type for GNAT_ENTITY and set up the correspondence. */
10379
10380 void
10381 process_type (Entity_Id gnat_entity)
10382 {
10383 tree gnu_old
10384 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
10385
10386 /* If we are to delay elaboration of this type, just do any elaboration
10387 needed for expressions within the declaration and make a dummy node
10388 for it and its Full_View (if any), in case something points to it.
10389 Do not do this if it has already been done (the only way that can
10390 happen is if the private completion is also delayed). */
10391 if (Present (Freeze_Node (gnat_entity)))
10392 {
10393 elaborate_entity (gnat_entity);
10394
10395 if (!gnu_old)
10396 {
10397 tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
10398 save_gnu_tree (gnat_entity, gnu_decl, false);
10399 if (Is_Incomplete_Or_Private_Type (gnat_entity)
10400 && Present (Full_View (gnat_entity)))
10401 {
10402 if (Has_Completion_In_Body (gnat_entity))
10403 DECL_TAFT_TYPE_P (gnu_decl) = 1;
10404 save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
10405 }
10406 }
10407
10408 return;
10409 }
10410
10411 /* If we saved away a dummy type for this node, it means that this made the
10412 type that corresponds to the full type of an incomplete type. Clear that
10413 type for now and then update the type in the pointers below. But, if the
10414 saved type is not dummy, it very likely means that we have a use before
10415 declaration for the type in the tree, what we really cannot handle. */
10416 if (gnu_old)
10417 {
10418 gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
10419 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
10420
10421 save_gnu_tree (gnat_entity, NULL_TREE, false);
10422 }
10423
10424 /* Now fully elaborate the type. */
10425 tree gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, true);
10426 gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
10427
10428 /* If we have an old type and we've made pointers to this type, update those
10429 pointers. If this is a Taft amendment type in the main unit, we need to
10430 mark the type as used since other units referencing it don't see the full
10431 declaration and, therefore, cannot mark it as used themselves. */
10432 if (gnu_old)
10433 {
10434 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
10435 TREE_TYPE (gnu_new));
10436 if (DECL_TAFT_TYPE_P (gnu_old))
10437 used_types_insert (TREE_TYPE (gnu_new));
10438 }
10439
10440 /* If this is a record type corresponding to a task or protected type
10441 that is a completion of an incomplete type, perform a similar update
10442 on the type. ??? Including protected types here is a guess. */
10443 if (Is_Record_Type (gnat_entity)
10444 && Is_Concurrent_Record_Type (gnat_entity)
10445 && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
10446 {
10447 tree gnu_task_old
10448 = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
10449
10450 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
10451 NULL_TREE, false);
10452 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
10453 gnu_new, false);
10454
10455 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
10456 TREE_TYPE (gnu_new));
10457 }
10458 }
10459 \f
10460 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
10461 some of which are from RECORD_TYPE. Return a CONSTRUCTOR consisting of the
10462 associations that are from RECORD_TYPE. If we see an internal record, make
10463 a recursive call to fill it in as well. */
10464
10465 static tree
10466 extract_values (tree values, tree record_type)
10467 {
10468 vec<constructor_elt, va_gc> *v = NULL;
10469 tree field;
10470
10471 for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
10472 {
10473 tree tem, value = NULL_TREE;
10474
10475 /* _Parent is an internal field, but may have values in the aggregate,
10476 so check for values first. */
10477 if ((tem = purpose_member (field, values)))
10478 {
10479 value = TREE_VALUE (tem);
10480 TREE_ADDRESSABLE (tem) = 1;
10481 }
10482
10483 else if (DECL_INTERNAL_P (field))
10484 {
10485 value = extract_values (values, TREE_TYPE (field));
10486 if (TREE_CODE (value) == CONSTRUCTOR
10487 && vec_safe_is_empty (CONSTRUCTOR_ELTS (value)))
10488 value = NULL_TREE;
10489 }
10490 else
10491 /* If we have a record subtype, the names will match, but not the
10492 actual FIELD_DECLs. */
10493 for (tem = values; tem; tem = TREE_CHAIN (tem))
10494 if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
10495 {
10496 value = convert (TREE_TYPE (field), TREE_VALUE (tem));
10497 TREE_ADDRESSABLE (tem) = 1;
10498 }
10499
10500 if (!value)
10501 continue;
10502
10503 CONSTRUCTOR_APPEND_ELT (v, field, value);
10504 }
10505
10506 return gnat_build_constructor (record_type, v);
10507 }
10508
10509 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
10510 front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
10511 GCC type of the corresponding record type. Return the CONSTRUCTOR. */
10512
10513 static tree
10514 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
10515 {
10516 tree gnu_list = NULL_TREE, gnu_result;
10517
10518 /* We test for GNU_FIELD being empty in the case where a variant
10519 was the last thing since we don't take things off GNAT_ASSOC in
10520 that case. We check GNAT_ASSOC in case we have a variant, but it
10521 has no fields. */
10522
10523 for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
10524 {
10525 Node_Id gnat_field = First (Choices (gnat_assoc));
10526 tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
10527 tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
10528
10529 /* The expander is supposed to put a single component selector name
10530 in every record component association. */
10531 gcc_assert (No (Next (gnat_field)));
10532
10533 /* Ignore discriminants that have Corresponding_Discriminants in tagged
10534 types since we'll be setting those fields in the parent subtype. */
10535 if (Ekind (Entity (gnat_field)) == E_Discriminant
10536 && Present (Corresponding_Discriminant (Entity (gnat_field)))
10537 && Is_Tagged_Type (Scope (Entity (gnat_field))))
10538 continue;
10539
10540 /* Also ignore discriminants of Unchecked_Unions. */
10541 if (Ekind (Entity (gnat_field)) == E_Discriminant
10542 && Is_Unchecked_Union (gnat_entity))
10543 continue;
10544
10545 /* Before assigning a value in an aggregate make sure range checks
10546 are done if required. Then convert to the type of the field. */
10547 if (Do_Range_Check (Expression (gnat_assoc)))
10548 gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field), Empty);
10549
10550 gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
10551
10552 /* Add the field and expression to the list. */
10553 gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
10554 }
10555
10556 gnu_result = extract_values (gnu_list, gnu_type);
10557
10558 if (flag_checking)
10559 {
10560 /* Verify that every entry in GNU_LIST was used. */
10561 for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
10562 gcc_assert (TREE_ADDRESSABLE (gnu_list));
10563 }
10564
10565 return gnu_result;
10566 }
10567
10568 /* Build a possibly nested constructor for array aggregates. GNAT_EXPR is
10569 the first element of an array aggregate. It may itself be an aggregate.
10570 GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate.
10571 GNAT_COMPONENT_TYPE is the type of the array component; it is needed
10572 for range checking. */
10573
10574 static tree
10575 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
10576 Entity_Id gnat_component_type)
10577 {
10578 tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
10579 vec<constructor_elt, va_gc> *gnu_expr_vec = NULL;
10580
10581 for (; Present (gnat_expr); gnat_expr = Next (gnat_expr))
10582 {
10583 tree gnu_expr;
10584
10585 /* If the expression is itself an array aggregate then first build the
10586 innermost constructor if it is part of our array (multi-dimensional
10587 case). */
10588 if (Nkind (gnat_expr) == N_Aggregate
10589 && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
10590 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
10591 gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
10592 TREE_TYPE (gnu_array_type),
10593 gnat_component_type);
10594 else
10595 {
10596 /* If the expression is a conversion to an unconstrained array type,
10597 skip it to avoid spilling to memory. */
10598 if (Nkind (gnat_expr) == N_Type_Conversion
10599 && Is_Array_Type (Etype (gnat_expr))
10600 && !Is_Constrained (Etype (gnat_expr)))
10601 gnu_expr = gnat_to_gnu (Expression (gnat_expr));
10602 else
10603 gnu_expr = gnat_to_gnu (gnat_expr);
10604
10605 /* Before assigning the element to the array, make sure it is
10606 in range. */
10607 if (Do_Range_Check (gnat_expr))
10608 gnu_expr = emit_range_check (gnu_expr, gnat_component_type, Empty);
10609 }
10610
10611 CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
10612 convert (TREE_TYPE (gnu_array_type), gnu_expr));
10613
10614 gnu_index = int_const_binop (PLUS_EXPR, gnu_index,
10615 convert (TREE_TYPE (gnu_index),
10616 integer_one_node));
10617 }
10618
10619 return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
10620 }
10621 \f
10622 /* Process a N_Validate_Unchecked_Conversion node. */
10623
10624 static void
10625 validate_unchecked_conversion (Node_Id gnat_node)
10626 {
10627 tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
10628 tree gnu_target_type = gnat_to_gnu_type (Target_Type (gnat_node));
10629
10630 /* If the target is a pointer type, see if we are either converting from a
10631 non-pointer or from a pointer to a type with a different alias set and
10632 warn if so, unless the pointer has been marked to alias everything. */
10633 if (POINTER_TYPE_P (gnu_target_type)
10634 && !TYPE_REF_CAN_ALIAS_ALL (gnu_target_type))
10635 {
10636 tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
10637 ? TREE_TYPE (gnu_source_type)
10638 : NULL_TREE;
10639 tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
10640 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
10641
10642 if (target_alias_set != 0
10643 && (!POINTER_TYPE_P (gnu_source_type)
10644 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
10645 target_alias_set)))
10646 {
10647 post_error_ne ("?possible aliasing problem for type&",
10648 gnat_node, Target_Type (gnat_node));
10649 post_error ("\\?use -fno-strict-aliasing switch for references",
10650 gnat_node);
10651 post_error_ne ("\\?or use `pragma No_Strict_Aliasing (&);`",
10652 gnat_node, Target_Type (gnat_node));
10653 }
10654 }
10655
10656 /* Likewise if the target is a fat pointer type, but we have no mechanism to
10657 mitigate the problem in this case, so we unconditionally warn. */
10658 else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
10659 {
10660 tree gnu_source_desig_type
10661 = TYPE_IS_FAT_POINTER_P (gnu_source_type)
10662 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
10663 : NULL_TREE;
10664 tree gnu_target_desig_type
10665 = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
10666 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
10667
10668 if (target_alias_set != 0
10669 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
10670 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
10671 target_alias_set)))
10672 {
10673 post_error_ne ("?possible aliasing problem for type&",
10674 gnat_node, Target_Type (gnat_node));
10675 post_error ("\\?use -fno-strict-aliasing switch for references",
10676 gnat_node);
10677 }
10678 }
10679 }
10680 \f
10681 /* EXP is to be used in a context where access objects are implicitly
10682 dereferenced. Handle the cases when it is an access object. */
10683
10684 static Node_Id
10685 adjust_for_implicit_deref (Node_Id exp)
10686 {
10687 Entity_Id type = Underlying_Type (Etype (exp));
10688
10689 /* Make sure the designated type is complete before dereferencing. */
10690 if (Is_Access_Type (type))
10691 gnat_to_gnu_entity (Designated_Type (type), NULL_TREE, false);
10692
10693 return exp;
10694 }
10695
10696 /* EXP is to be treated as an array or record. Handle the cases when it is
10697 an access object and perform the required dereferences. */
10698
10699 static tree
10700 maybe_implicit_deref (tree exp)
10701 {
10702 /* If the type is a pointer, dereference it. */
10703 if (POINTER_TYPE_P (TREE_TYPE (exp))
10704 || TYPE_IS_FAT_POINTER_P (TREE_TYPE (exp)))
10705 exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
10706
10707 /* If we got a padded type, remove it too. */
10708 if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
10709 exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
10710
10711 return exp;
10712 }
10713 \f
10714 /* Convert SLOC into LOCUS. Return true if SLOC corresponds to a
10715 source code location and false if it doesn't. If CLEAR_COLUMN is
10716 true, set the column information to 0. If DECL is given and SLOC
10717 refers to a File with an instance, map DECL to that instance. */
10718
10719 bool
10720 Sloc_to_locus (Source_Ptr Sloc, location_t *locus, bool clear_column,
10721 const_tree decl)
10722 {
10723 if (Sloc == No_Location)
10724 return false;
10725
10726 if (Sloc <= Standard_Location)
10727 {
10728 *locus = BUILTINS_LOCATION;
10729 return false;
10730 }
10731
10732 Source_File_Index file = Get_Source_File_Index (Sloc);
10733 Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
10734 Column_Number column = (clear_column ? 0 : Get_Column_Number (Sloc));
10735 line_map_ordinary *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
10736
10737 /* We can have zero if pragma Source_Reference is in effect. */
10738 if (line < 1)
10739 line = 1;
10740
10741 /* Translate the location. */
10742 *locus
10743 = linemap_position_for_line_and_column (line_table, map, line, column);
10744
10745 if (file_map && file_map[file - 1].Instance)
10746 decl_to_instance_map->put (decl, file_map[file - 1].Instance);
10747
10748 return true;
10749 }
10750
10751 /* Return whether GNAT_NODE is a defining identifier for a renaming that comes
10752 from the parameter association for the instantiation of a generic. We do
10753 not want to emit source location for them: the code generated for their
10754 initialization is likely to disturb debugging. */
10755
10756 bool
10757 renaming_from_instantiation_p (Node_Id gnat_node)
10758 {
10759 if (Nkind (gnat_node) != N_Defining_Identifier
10760 || !Is_Object (gnat_node)
10761 || Comes_From_Source (gnat_node)
10762 || !Present (Renamed_Object (gnat_node)))
10763 return false;
10764
10765 /* Get the object declaration of the renamed object, if any and if the
10766 renamed object is a mere identifier. */
10767 gnat_node = Renamed_Object (gnat_node);
10768 if (Nkind (gnat_node) != N_Identifier)
10769 return false;
10770
10771 gnat_node = Parent (Entity (gnat_node));
10772 return (Present (gnat_node)
10773 && Nkind (gnat_node) == N_Object_Declaration
10774 && Present (Corresponding_Generic_Association (gnat_node)));
10775 }
10776
10777 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
10778 don't do anything if it doesn't correspond to a source location. And,
10779 if CLEAR_COLUMN is true, set the column information to 0. */
10780
10781 static void
10782 set_expr_location_from_node (tree node, Node_Id gnat_node, bool clear_column)
10783 {
10784 location_t locus;
10785
10786 /* Do not set a location for constructs likely to disturb debugging. */
10787 if (Nkind (gnat_node) == N_Defining_Identifier)
10788 {
10789 if (Is_Type (gnat_node) && Is_Actual_Subtype (gnat_node))
10790 return;
10791
10792 if (renaming_from_instantiation_p (gnat_node))
10793 return;
10794 }
10795
10796 if (!Sloc_to_locus (Sloc (gnat_node), &locus, clear_column))
10797 return;
10798
10799 SET_EXPR_LOCATION (node, locus);
10800 }
10801
10802 /* More elaborate version of set_expr_location_from_node to be used in more
10803 general contexts, for example the result of the translation of a generic
10804 GNAT node. */
10805
10806 static void
10807 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
10808 {
10809 /* Set the location information on the node if it is a real expression.
10810 References can be reused for multiple GNAT nodes and they would get
10811 the location information of their last use. Also make sure not to
10812 overwrite an existing location as it is probably more precise. */
10813
10814 switch (TREE_CODE (node))
10815 {
10816 CASE_CONVERT:
10817 case NON_LVALUE_EXPR:
10818 case SAVE_EXPR:
10819 break;
10820
10821 case COMPOUND_EXPR:
10822 if (EXPR_P (TREE_OPERAND (node, 1)))
10823 set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
10824
10825 /* ... fall through ... */
10826
10827 default:
10828 if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
10829 {
10830 set_expr_location_from_node (node, gnat_node);
10831 set_end_locus_from_node (node, gnat_node);
10832 }
10833 break;
10834 }
10835 }
10836
10837 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
10838 location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
10839 most sense. Return true if a sensible assignment was performed. */
10840
10841 static bool
10842 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
10843 {
10844 Node_Id gnat_end_label;
10845 location_t end_locus;
10846
10847 /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
10848 end_locus when there is one. We consider only GNAT nodes with a possible
10849 End_Label attached. If the End_Label actually was unassigned, fallback
10850 on the original node. We'd better assign an explicit sloc associated with
10851 the outer construct in any case. */
10852
10853 switch (Nkind (gnat_node))
10854 {
10855 case N_Package_Body:
10856 case N_Subprogram_Body:
10857 case N_Block_Statement:
10858 gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
10859 break;
10860
10861 case N_Package_Declaration:
10862 gnat_end_label = End_Label (Specification (gnat_node));
10863 break;
10864
10865 default:
10866 return false;
10867 }
10868
10869 if (Present (gnat_end_label))
10870 gnat_node = gnat_end_label;
10871
10872 /* Some expanded subprograms have neither an End_Label nor a Sloc
10873 attached. Notify that to callers. For a block statement with no
10874 End_Label, clear column information, so that the tree for a
10875 transient block does not receive the sloc of a source condition. */
10876 if (!Sloc_to_locus (Sloc (gnat_node), &end_locus,
10877 No (gnat_end_label)
10878 && (Nkind (gnat_node) == N_Block_Statement)))
10879 return false;
10880
10881 switch (TREE_CODE (gnu_node))
10882 {
10883 case BIND_EXPR:
10884 BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
10885 return true;
10886
10887 case FUNCTION_DECL:
10888 DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
10889 return true;
10890
10891 default:
10892 return false;
10893 }
10894 }
10895 \f
10896 /* Return a colon-separated list of encodings contained in encoded Ada
10897 name. */
10898
10899 static const char *
10900 extract_encoding (const char *name)
10901 {
10902 char *encoding = (char *) ggc_alloc_atomic (strlen (name));
10903 get_encoding (name, encoding);
10904 return encoding;
10905 }
10906
10907 /* Extract the Ada name from an encoded name. */
10908
10909 static const char *
10910 decode_name (const char *name)
10911 {
10912 char *decoded = (char *) ggc_alloc_atomic (strlen (name) * 2 + 60);
10913 __gnat_decode (name, decoded, 0);
10914 return decoded;
10915 }
10916 \f
10917 /* Post an error message. MSG is the error message, properly annotated.
10918 NODE is the node at which to post the error and the node to use for the
10919 '&' substitution. */
10920
10921 void
10922 post_error (const char *msg, Node_Id node)
10923 {
10924 String_Template temp;
10925 String_Pointer sp;
10926
10927 if (No (node))
10928 return;
10929
10930 temp.Low_Bound = 1;
10931 temp.High_Bound = strlen (msg);
10932 sp.Bounds = &temp;
10933 sp.Array = msg;
10934 Error_Msg_N (sp, node);
10935 }
10936
10937 /* Similar to post_error, but NODE is the node at which to post the error and
10938 ENT is the node to use for the '&' substitution. */
10939
10940 void
10941 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
10942 {
10943 String_Template temp;
10944 String_Pointer sp;
10945
10946 if (No (node))
10947 return;
10948
10949 temp.Low_Bound = 1;
10950 temp.High_Bound = strlen (msg);
10951 sp.Bounds = &temp;
10952 sp.Array = msg;
10953 Error_Msg_NE (sp, node, ent);
10954 }
10955
10956 /* Similar to post_error_ne, but NUM is the number to use for the '^'. */
10957
10958 void
10959 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
10960 {
10961 Error_Msg_Uint_1 = UI_From_Int (num);
10962 post_error_ne (msg, node, ent);
10963 }
10964
10965 /* Similar to post_error_ne, but T is a GCC tree representing the number to
10966 write. If T represents a constant, the text inside curly brackets in
10967 MSG will be output (presumably including a '^'). Otherwise it will not
10968 be output and the text inside square brackets will be output instead. */
10969
10970 void
10971 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
10972 {
10973 char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
10974 char start_yes, end_yes, start_no, end_no;
10975 const char *p;
10976 char *q;
10977
10978 if (TREE_CODE (t) == INTEGER_CST)
10979 {
10980 Error_Msg_Uint_1 = UI_From_gnu (t);
10981 start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
10982 }
10983 else
10984 start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
10985
10986 for (p = msg, q = new_msg; *p; p++)
10987 {
10988 if (*p == start_yes)
10989 for (p++; *p != end_yes; p++)
10990 *q++ = *p;
10991 else if (*p == start_no)
10992 for (p++; *p != end_no; p++)
10993 ;
10994 else
10995 *q++ = *p;
10996 }
10997
10998 *q = 0;
10999
11000 post_error_ne (new_msg, node, ent);
11001 }
11002
11003 /* Similar to post_error_ne_tree, but NUM is a second integer to write. */
11004
11005 void
11006 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
11007 int num)
11008 {
11009 Error_Msg_Uint_2 = UI_From_Int (num);
11010 post_error_ne_tree (msg, node, ent, t);
11011 }
11012
11013 /* Return a label to branch to for the exception type in KIND or Empty
11014 if none. */
11015
11016 Entity_Id
11017 get_exception_label (char kind)
11018 {
11019 switch (kind)
11020 {
11021 case N_Raise_Constraint_Error:
11022 return gnu_constraint_error_label_stack.last ();
11023
11024 case N_Raise_Storage_Error:
11025 return gnu_storage_error_label_stack.last ();
11026
11027 case N_Raise_Program_Error:
11028 return gnu_program_error_label_stack.last ();
11029
11030 default:
11031 return Empty;
11032 }
11033
11034 gcc_unreachable ();
11035 }
11036
11037 /* Return the decl for the current elaboration procedure. */
11038
11039 static tree
11040 get_elaboration_procedure (void)
11041 {
11042 return gnu_elab_proc_stack->last ();
11043 }
11044
11045 /* Return the controlling type of a dispatching subprogram. */
11046
11047 static Entity_Id
11048 get_controlling_type (Entity_Id subprog)
11049 {
11050 /* This is modelled on Expand_Interface_Thunk. */
11051 Entity_Id controlling_type = Etype (First_Formal (subprog));
11052 if (Is_Access_Type (controlling_type))
11053 controlling_type = Directly_Designated_Type (controlling_type);
11054 controlling_type = Underlying_Type (controlling_type);
11055 if (Is_Concurrent_Type (controlling_type))
11056 controlling_type = Corresponding_Record_Type (controlling_type);
11057 controlling_type = Base_Type (controlling_type);
11058 return controlling_type;
11059 }
11060
11061 /* Return whether we should use an alias for the TARGET of a thunk
11062 in order to make the call generated in the thunk local. */
11063
11064 static bool
11065 use_alias_for_thunk_p (tree target)
11066 {
11067 /* We cannot generate a local call in this case. */
11068 if (DECL_EXTERNAL (target))
11069 return false;
11070
11071 /* The call is already local in this case. */
11072 if (TREE_CODE (DECL_CONTEXT (target)) == FUNCTION_DECL)
11073 return false;
11074
11075 return TARGET_USE_LOCAL_THUNK_ALIAS_P (target);
11076 }
11077
11078 static GTY(()) unsigned long thunk_labelno = 0;
11079
11080 /* Create an alias for TARGET to be used as the target of a thunk. */
11081
11082 static tree
11083 make_alias_for_thunk (tree target)
11084 {
11085 char buf[64];
11086 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno++);
11087
11088 tree alias = build_decl (DECL_SOURCE_LOCATION (target), TREE_CODE (target),
11089 get_identifier (buf), TREE_TYPE (target));
11090
11091 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (target);
11092 DECL_CONTEXT (alias) = DECL_CONTEXT (target);
11093 TREE_READONLY (alias) = TREE_READONLY (target);
11094 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (target);
11095 DECL_ARTIFICIAL (alias) = 1;
11096 DECL_INITIAL (alias) = error_mark_node;
11097 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (target));
11098 TREE_ADDRESSABLE (alias) = 1;
11099 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
11100
11101 cgraph_node *n = cgraph_node::create_same_body_alias (alias, target);
11102 gcc_assert (n);
11103
11104 return alias;
11105 }
11106
11107 /* Create the covariant part of the {GNAT,GNU}_THUNK. */
11108
11109 static tree
11110 make_covariant_thunk (Entity_Id gnat_thunk, tree gnu_thunk)
11111 {
11112 tree gnu_name = create_concat_name (gnat_thunk, "CV");
11113 tree gnu_cv_thunk
11114 = build_decl (DECL_SOURCE_LOCATION (gnu_thunk), TREE_CODE (gnu_thunk),
11115 gnu_name, TREE_TYPE (gnu_thunk));
11116
11117 DECL_ARGUMENTS (gnu_cv_thunk) = copy_list (DECL_ARGUMENTS (gnu_thunk));
11118 DECL_RESULT (gnu_cv_thunk) = copy_node (DECL_RESULT (gnu_thunk));
11119 DECL_CONTEXT (DECL_RESULT (gnu_cv_thunk)) = gnu_cv_thunk;
11120
11121 DECL_LANG_SPECIFIC (gnu_cv_thunk) = DECL_LANG_SPECIFIC (gnu_thunk);
11122 DECL_CONTEXT (gnu_cv_thunk) = DECL_CONTEXT (gnu_thunk);
11123 TREE_READONLY (gnu_cv_thunk) = TREE_READONLY (gnu_thunk);
11124 TREE_THIS_VOLATILE (gnu_cv_thunk) = TREE_THIS_VOLATILE (gnu_thunk);
11125 TREE_PUBLIC (gnu_cv_thunk) = TREE_PUBLIC (gnu_thunk);
11126 DECL_ARTIFICIAL (gnu_cv_thunk) = 1;
11127
11128 return gnu_cv_thunk;
11129 }
11130
11131 /* Try to create a GNU thunk for {GNAT,GNU}_THUNK and return true on success.
11132
11133 GNU thunks are more efficient than GNAT thunks because they don't call into
11134 the runtime to retrieve the offset used in the displacement operation, but
11135 they are tailored to C++ and thus too limited to support the full range of
11136 thunks generated in Ada. Here's the complete list of limitations:
11137
11138 1. Multi-controlling thunks, i.e thunks with more than one controlling
11139 parameter, are simply not supported.
11140
11141 2. Covariant thunks, i.e. thunks for which the result is also controlling,
11142 are split into a pair of (this, covariant-only) thunks.
11143
11144 3. Variable-offset thunks, i.e. thunks for which the offset depends on the
11145 object and not only on its type, are supported as 2nd class citizens.
11146
11147 4. External thunks, i.e. thunks for which the target is not declared in
11148 the same unit as the thunk, are supported as 2nd class citizens.
11149
11150 5. Local thunks, i.e. thunks generated for a local type, are supported as
11151 2nd class citizens. */
11152
11153 static bool
11154 maybe_make_gnu_thunk (Entity_Id gnat_thunk, tree gnu_thunk)
11155 {
11156 const Entity_Id gnat_target = Thunk_Entity (gnat_thunk);
11157
11158 /* Check that the first formal of the target is the only controlling one. */
11159 Entity_Id gnat_formal = First_Formal (gnat_target);
11160 if (!Is_Controlling_Formal (gnat_formal))
11161 return false;
11162 for (gnat_formal = Next_Formal (gnat_formal);
11163 Present (gnat_formal);
11164 gnat_formal = Next_Formal (gnat_formal))
11165 if (Is_Controlling_Formal (gnat_formal))
11166 return false;
11167
11168 /* Look for the types that control the target and the thunk. */
11169 const Entity_Id gnat_controlling_type = get_controlling_type (gnat_target);
11170 const Entity_Id gnat_interface_type = get_controlling_type (gnat_thunk);
11171
11172 /* Now compute whether the former covers the latter. */
11173 const Entity_Id gnat_interface_tag
11174 = Is_Interface (gnat_interface_type)
11175 ? Find_Interface_Tag (gnat_controlling_type, gnat_interface_type)
11176 : Empty;
11177 tree gnu_interface_tag
11178 = Present (gnat_interface_tag)
11179 ? gnat_to_gnu_field_decl (gnat_interface_tag)
11180 : NULL_TREE;
11181 tree gnu_interface_offset
11182 = gnu_interface_tag ? byte_position (gnu_interface_tag) : NULL_TREE;
11183
11184 /* There are three ways to retrieve the offset between the interface view
11185 and the base object. Either the controlling type covers the interface
11186 type and the offset of the corresponding tag is fixed, in which case it
11187 can be statically encoded in the thunk (see FIXED_OFFSET below). Or the
11188 controlling type doesn't cover the interface type but is of fixed size,
11189 in which case the offset is stored in the dispatch table, two pointers
11190 above the dispatch table address (see VIRTUAL_VALUE below). Otherwise,
11191 the offset is variable and is stored right after the tag in every object
11192 (see INDIRECT_OFFSET below). See also a-tags.ads for more details. */
11193 HOST_WIDE_INT fixed_offset, virtual_value, indirect_offset;
11194 tree virtual_offset;
11195
11196 if (gnu_interface_offset && TREE_CODE (gnu_interface_offset) == INTEGER_CST)
11197 {
11198 fixed_offset = - tree_to_shwi (gnu_interface_offset);
11199 virtual_value = 0;
11200 virtual_offset = NULL_TREE;
11201 indirect_offset = 0;
11202 }
11203 else if (!gnu_interface_offset
11204 && !Is_Variable_Size_Record (gnat_controlling_type))
11205 {
11206 fixed_offset = 0;
11207 virtual_value = - 2 * (HOST_WIDE_INT) (POINTER_SIZE / BITS_PER_UNIT);
11208 virtual_offset = build_int_cst (integer_type_node, virtual_value);
11209 indirect_offset = 0;
11210 }
11211 else
11212 {
11213 /* Covariant thunks with variable offset are not supported. */
11214 if (Has_Controlling_Result (gnat_target))
11215 return false;
11216
11217 fixed_offset = 0;
11218 virtual_value = 0;
11219 virtual_offset = NULL_TREE;
11220 indirect_offset = (HOST_WIDE_INT) (POINTER_SIZE / BITS_PER_UNIT);
11221 }
11222
11223 tree gnu_target = gnat_to_gnu_entity (gnat_target, NULL_TREE, false);
11224
11225 /* Thunk and target must have the same nesting level, if any. */
11226 gcc_assert (DECL_CONTEXT (gnu_thunk) == DECL_CONTEXT (gnu_target));
11227
11228 /* If the target returns by invisible reference and is external, apply the
11229 same transformation as Subprogram_Body_to_gnu here. */
11230 if (TREE_ADDRESSABLE (TREE_TYPE (gnu_target))
11231 && DECL_EXTERNAL (gnu_target)
11232 && !POINTER_TYPE_P (TREE_TYPE (DECL_RESULT (gnu_target))))
11233 {
11234 TREE_TYPE (DECL_RESULT (gnu_target))
11235 = build_reference_type (TREE_TYPE (DECL_RESULT (gnu_target)));
11236 relayout_decl (DECL_RESULT (gnu_target));
11237 }
11238
11239 /* The thunk expander requires the return types of thunk and target to be
11240 compatible, which is not fully the case with the CICO mechanism. */
11241 if (TYPE_CI_CO_LIST (TREE_TYPE (gnu_thunk)))
11242 {
11243 tree gnu_target_type = TREE_TYPE (gnu_target);
11244 gcc_assert (TYPE_CI_CO_LIST (gnu_target_type));
11245 TYPE_CANONICAL (TREE_TYPE (TREE_TYPE (gnu_thunk)))
11246 = TYPE_CANONICAL (TREE_TYPE (gnu_target_type));
11247 }
11248
11249 cgraph_node *target_node = cgraph_node::get_create (gnu_target);
11250
11251 /* If the return type of the target is a controlling type, then we need
11252 both an usual this thunk and a covariant thunk in this order:
11253
11254 this thunk --> covariant thunk --> target
11255
11256 For covariant thunks, we can only handle a fixed offset. */
11257 if (Has_Controlling_Result (gnat_target))
11258 {
11259 gcc_assert (fixed_offset < 0);
11260 tree gnu_cv_thunk = make_covariant_thunk (gnat_thunk, gnu_thunk);
11261 target_node->create_thunk (gnu_cv_thunk, gnu_target, false,
11262 - fixed_offset, 0, 0,
11263 NULL_TREE, gnu_target);
11264
11265 gnu_target = gnu_cv_thunk;
11266 }
11267
11268 /* We may also need to create an alias for the target in order to make
11269 the call local, depending on the linkage of the target. */
11270 tree gnu_alias = use_alias_for_thunk_p (gnu_target)
11271 ? make_alias_for_thunk (gnu_target)
11272 : gnu_target;
11273
11274 target_node->create_thunk (gnu_thunk, gnu_target, true,
11275 fixed_offset, virtual_value, indirect_offset,
11276 virtual_offset, gnu_alias);
11277
11278 return true;
11279 }
11280
11281 /* Initialize the table that maps GNAT codes to GCC codes for simple
11282 binary and unary operations. */
11283
11284 static void
11285 init_code_table (void)
11286 {
11287 gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
11288 gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
11289 gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
11290 gnu_codes[N_Op_Eq] = EQ_EXPR;
11291 gnu_codes[N_Op_Ne] = NE_EXPR;
11292 gnu_codes[N_Op_Lt] = LT_EXPR;
11293 gnu_codes[N_Op_Le] = LE_EXPR;
11294 gnu_codes[N_Op_Gt] = GT_EXPR;
11295 gnu_codes[N_Op_Ge] = GE_EXPR;
11296 gnu_codes[N_Op_Add] = PLUS_EXPR;
11297 gnu_codes[N_Op_Subtract] = MINUS_EXPR;
11298 gnu_codes[N_Op_Multiply] = MULT_EXPR;
11299 gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
11300 gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
11301 gnu_codes[N_Op_Minus] = NEGATE_EXPR;
11302 gnu_codes[N_Op_Abs] = ABS_EXPR;
11303 gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
11304 gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
11305 gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
11306 gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
11307 gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
11308 gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
11309 gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
11310 gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
11311 }
11312
11313 #include "gt-ada-trans.h"