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