cgraph.c (cgraph_turn_edge_to_speculative): Return newly introduced edge; fix typo...
[gcc.git] / gcc / tree-sra.c
1 /* Scalar Replacement of Aggregates (SRA) converts some structure
2 references into scalar references, exposing them to the scalar
3 optimizers.
4 Copyright (C) 2008-2013 Free Software Foundation, Inc.
5 Contributed by Martin Jambor <mjambor@suse.cz>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
22
23 /* This file implements Scalar Reduction of Aggregates (SRA). SRA is run
24 twice, once in the early stages of compilation (early SRA) and once in the
25 late stages (late SRA). The aim of both is to turn references to scalar
26 parts of aggregates into uses of independent scalar variables.
27
28 The two passes are nearly identical, the only difference is that early SRA
29 does not scalarize unions which are used as the result in a GIMPLE_RETURN
30 statement because together with inlining this can lead to weird type
31 conversions.
32
33 Both passes operate in four stages:
34
35 1. The declarations that have properties which make them candidates for
36 scalarization are identified in function find_var_candidates(). The
37 candidates are stored in candidate_bitmap.
38
39 2. The function body is scanned. In the process, declarations which are
40 used in a manner that prevent their scalarization are removed from the
41 candidate bitmap. More importantly, for every access into an aggregate,
42 an access structure (struct access) is created by create_access() and
43 stored in a vector associated with the aggregate. Among other
44 information, the aggregate declaration, the offset and size of the access
45 and its type are stored in the structure.
46
47 On a related note, assign_link structures are created for every assign
48 statement between candidate aggregates and attached to the related
49 accesses.
50
51 3. The vectors of accesses are analyzed. They are first sorted according to
52 their offset and size and then scanned for partially overlapping accesses
53 (i.e. those which overlap but one is not entirely within another). Such
54 an access disqualifies the whole aggregate from being scalarized.
55
56 If there is no such inhibiting overlap, a representative access structure
57 is chosen for every unique combination of offset and size. Afterwards,
58 the pass builds a set of trees from these structures, in which children
59 of an access are within their parent (in terms of offset and size).
60
61 Then accesses are propagated whenever possible (i.e. in cases when it
62 does not create a partially overlapping access) across assign_links from
63 the right hand side to the left hand side.
64
65 Then the set of trees for each declaration is traversed again and those
66 accesses which should be replaced by a scalar are identified.
67
68 4. The function is traversed again, and for every reference into an
69 aggregate that has some component which is about to be scalarized,
70 statements are amended and new statements are created as necessary.
71 Finally, if a parameter got scalarized, the scalar replacements are
72 initialized with values from respective parameter aggregates. */
73
74 #include "config.h"
75 #include "system.h"
76 #include "coretypes.h"
77 #include "hash-table.h"
78 #include "alloc-pool.h"
79 #include "tm.h"
80 #include "tree.h"
81 #include "gimple.h"
82 #include "cgraph.h"
83 #include "tree-flow.h"
84 #include "tree-pass.h"
85 #include "ipa-prop.h"
86 #include "statistics.h"
87 #include "params.h"
88 #include "target.h"
89 #include "flags.h"
90 #include "dbgcnt.h"
91 #include "tree-inline.h"
92 #include "gimple-pretty-print.h"
93 #include "ipa-inline.h"
94
95 /* Enumeration of all aggregate reductions we can do. */
96 enum sra_mode { SRA_MODE_EARLY_IPA, /* early call regularization */
97 SRA_MODE_EARLY_INTRA, /* early intraprocedural SRA */
98 SRA_MODE_INTRA }; /* late intraprocedural SRA */
99
100 /* Global variable describing which aggregate reduction we are performing at
101 the moment. */
102 static enum sra_mode sra_mode;
103
104 struct assign_link;
105
106 /* ACCESS represents each access to an aggregate variable (as a whole or a
107 part). It can also represent a group of accesses that refer to exactly the
108 same fragment of an aggregate (i.e. those that have exactly the same offset
109 and size). Such representatives for a single aggregate, once determined,
110 are linked in a linked list and have the group fields set.
111
112 Moreover, when doing intraprocedural SRA, a tree is built from those
113 representatives (by the means of first_child and next_sibling pointers), in
114 which all items in a subtree are "within" the root, i.e. their offset is
115 greater or equal to offset of the root and offset+size is smaller or equal
116 to offset+size of the root. Children of an access are sorted by offset.
117
118 Note that accesses to parts of vector and complex number types always
119 represented by an access to the whole complex number or a vector. It is a
120 duty of the modifying functions to replace them appropriately. */
121
122 struct access
123 {
124 /* Values returned by `get_ref_base_and_extent' for each component reference
125 If EXPR isn't a component reference just set `BASE = EXPR', `OFFSET = 0',
126 `SIZE = TREE_SIZE (TREE_TYPE (expr))'. */
127 HOST_WIDE_INT offset;
128 HOST_WIDE_INT size;
129 tree base;
130
131 /* Expression. It is context dependent so do not use it to create new
132 expressions to access the original aggregate. See PR 42154 for a
133 testcase. */
134 tree expr;
135 /* Type. */
136 tree type;
137
138 /* The statement this access belongs to. */
139 gimple stmt;
140
141 /* Next group representative for this aggregate. */
142 struct access *next_grp;
143
144 /* Pointer to the group representative. Pointer to itself if the struct is
145 the representative. */
146 struct access *group_representative;
147
148 /* If this access has any children (in terms of the definition above), this
149 points to the first one. */
150 struct access *first_child;
151
152 /* In intraprocedural SRA, pointer to the next sibling in the access tree as
153 described above. In IPA-SRA this is a pointer to the next access
154 belonging to the same group (having the same representative). */
155 struct access *next_sibling;
156
157 /* Pointers to the first and last element in the linked list of assign
158 links. */
159 struct assign_link *first_link, *last_link;
160
161 /* Pointer to the next access in the work queue. */
162 struct access *next_queued;
163
164 /* Replacement variable for this access "region." Never to be accessed
165 directly, always only by the means of get_access_replacement() and only
166 when grp_to_be_replaced flag is set. */
167 tree replacement_decl;
168
169 /* Is this particular access write access? */
170 unsigned write : 1;
171
172 /* Is this access an access to a non-addressable field? */
173 unsigned non_addressable : 1;
174
175 /* Is this access currently in the work queue? */
176 unsigned grp_queued : 1;
177
178 /* Does this group contain a write access? This flag is propagated down the
179 access tree. */
180 unsigned grp_write : 1;
181
182 /* Does this group contain a read access? This flag is propagated down the
183 access tree. */
184 unsigned grp_read : 1;
185
186 /* Does this group contain a read access that comes from an assignment
187 statement? This flag is propagated down the access tree. */
188 unsigned grp_assignment_read : 1;
189
190 /* Does this group contain a write access that comes from an assignment
191 statement? This flag is propagated down the access tree. */
192 unsigned grp_assignment_write : 1;
193
194 /* Does this group contain a read access through a scalar type? This flag is
195 not propagated in the access tree in any direction. */
196 unsigned grp_scalar_read : 1;
197
198 /* Does this group contain a write access through a scalar type? This flag
199 is not propagated in the access tree in any direction. */
200 unsigned grp_scalar_write : 1;
201
202 /* Is this access an artificial one created to scalarize some record
203 entirely? */
204 unsigned grp_total_scalarization : 1;
205
206 /* Other passes of the analysis use this bit to make function
207 analyze_access_subtree create scalar replacements for this group if
208 possible. */
209 unsigned grp_hint : 1;
210
211 /* Is the subtree rooted in this access fully covered by scalar
212 replacements? */
213 unsigned grp_covered : 1;
214
215 /* If set to true, this access and all below it in an access tree must not be
216 scalarized. */
217 unsigned grp_unscalarizable_region : 1;
218
219 /* Whether data have been written to parts of the aggregate covered by this
220 access which is not to be scalarized. This flag is propagated up in the
221 access tree. */
222 unsigned grp_unscalarized_data : 1;
223
224 /* Does this access and/or group contain a write access through a
225 BIT_FIELD_REF? */
226 unsigned grp_partial_lhs : 1;
227
228 /* Set when a scalar replacement should be created for this variable. */
229 unsigned grp_to_be_replaced : 1;
230
231 /* Set when we want a replacement for the sole purpose of having it in
232 generated debug statements. */
233 unsigned grp_to_be_debug_replaced : 1;
234
235 /* Should TREE_NO_WARNING of a replacement be set? */
236 unsigned grp_no_warning : 1;
237
238 /* Is it possible that the group refers to data which might be (directly or
239 otherwise) modified? */
240 unsigned grp_maybe_modified : 1;
241
242 /* Set when this is a representative of a pointer to scalar (i.e. by
243 reference) parameter which we consider for turning into a plain scalar
244 (i.e. a by value parameter). */
245 unsigned grp_scalar_ptr : 1;
246
247 /* Set when we discover that this pointer is not safe to dereference in the
248 caller. */
249 unsigned grp_not_necessarilly_dereferenced : 1;
250 };
251
252 typedef struct access *access_p;
253
254
255 /* Alloc pool for allocating access structures. */
256 static alloc_pool access_pool;
257
258 /* A structure linking lhs and rhs accesses from an aggregate assignment. They
259 are used to propagate subaccesses from rhs to lhs as long as they don't
260 conflict with what is already there. */
261 struct assign_link
262 {
263 struct access *lacc, *racc;
264 struct assign_link *next;
265 };
266
267 /* Alloc pool for allocating assign link structures. */
268 static alloc_pool link_pool;
269
270 /* Base (tree) -> Vector (vec<access_p> *) map. */
271 static struct pointer_map_t *base_access_vec;
272
273 /* Candidate hash table helpers. */
274
275 struct uid_decl_hasher : typed_noop_remove <tree_node>
276 {
277 typedef tree_node value_type;
278 typedef tree_node compare_type;
279 static inline hashval_t hash (const value_type *);
280 static inline bool equal (const value_type *, const compare_type *);
281 };
282
283 /* Hash a tree in a uid_decl_map. */
284
285 inline hashval_t
286 uid_decl_hasher::hash (const value_type *item)
287 {
288 return item->decl_minimal.uid;
289 }
290
291 /* Return true if the DECL_UID in both trees are equal. */
292
293 inline bool
294 uid_decl_hasher::equal (const value_type *a, const compare_type *b)
295 {
296 return (a->decl_minimal.uid == b->decl_minimal.uid);
297 }
298
299 /* Set of candidates. */
300 static bitmap candidate_bitmap;
301 static hash_table <uid_decl_hasher> candidates;
302
303 /* For a candidate UID return the candidates decl. */
304
305 static inline tree
306 candidate (unsigned uid)
307 {
308 tree_node t;
309 t.decl_minimal.uid = uid;
310 return candidates.find_with_hash (&t, static_cast <hashval_t> (uid));
311 }
312
313 /* Bitmap of candidates which we should try to entirely scalarize away and
314 those which cannot be (because they are and need be used as a whole). */
315 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
316
317 /* Obstack for creation of fancy names. */
318 static struct obstack name_obstack;
319
320 /* Head of a linked list of accesses that need to have its subaccesses
321 propagated to their assignment counterparts. */
322 static struct access *work_queue_head;
323
324 /* Number of parameters of the analyzed function when doing early ipa SRA. */
325 static int func_param_count;
326
327 /* scan_function sets the following to true if it encounters a call to
328 __builtin_apply_args. */
329 static bool encountered_apply_args;
330
331 /* Set by scan_function when it finds a recursive call. */
332 static bool encountered_recursive_call;
333
334 /* Set by scan_function when it finds a recursive call with less actual
335 arguments than formal parameters.. */
336 static bool encountered_unchangable_recursive_call;
337
338 /* This is a table in which for each basic block and parameter there is a
339 distance (offset + size) in that parameter which is dereferenced and
340 accessed in that BB. */
341 static HOST_WIDE_INT *bb_dereferences;
342 /* Bitmap of BBs that can cause the function to "stop" progressing by
343 returning, throwing externally, looping infinitely or calling a function
344 which might abort etc.. */
345 static bitmap final_bbs;
346
347 /* Representative of no accesses at all. */
348 static struct access no_accesses_representant;
349
350 /* Predicate to test the special value. */
351
352 static inline bool
353 no_accesses_p (struct access *access)
354 {
355 return access == &no_accesses_representant;
356 }
357
358 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
359 representative fields are dumped, otherwise those which only describe the
360 individual access are. */
361
362 static struct
363 {
364 /* Number of processed aggregates is readily available in
365 analyze_all_variable_accesses and so is not stored here. */
366
367 /* Number of created scalar replacements. */
368 int replacements;
369
370 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
371 expression. */
372 int exprs;
373
374 /* Number of statements created by generate_subtree_copies. */
375 int subtree_copies;
376
377 /* Number of statements created by load_assign_lhs_subreplacements. */
378 int subreplacements;
379
380 /* Number of times sra_modify_assign has deleted a statement. */
381 int deleted;
382
383 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
384 RHS reparately due to type conversions or nonexistent matching
385 references. */
386 int separate_lhs_rhs_handling;
387
388 /* Number of parameters that were removed because they were unused. */
389 int deleted_unused_parameters;
390
391 /* Number of scalars passed as parameters by reference that have been
392 converted to be passed by value. */
393 int scalar_by_ref_to_by_val;
394
395 /* Number of aggregate parameters that were replaced by one or more of their
396 components. */
397 int aggregate_params_reduced;
398
399 /* Numbber of components created when splitting aggregate parameters. */
400 int param_reductions_created;
401 } sra_stats;
402
403 static void
404 dump_access (FILE *f, struct access *access, bool grp)
405 {
406 fprintf (f, "access { ");
407 fprintf (f, "base = (%d)'", DECL_UID (access->base));
408 print_generic_expr (f, access->base, 0);
409 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
410 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
411 fprintf (f, ", expr = ");
412 print_generic_expr (f, access->expr, 0);
413 fprintf (f, ", type = ");
414 print_generic_expr (f, access->type, 0);
415 if (grp)
416 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
417 "grp_assignment_write = %d, grp_scalar_read = %d, "
418 "grp_scalar_write = %d, grp_total_scalarization = %d, "
419 "grp_hint = %d, grp_covered = %d, "
420 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
421 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
422 "grp_to_be_debug_replaced = %d, grp_maybe_modified = %d, "
423 "grp_not_necessarilly_dereferenced = %d\n",
424 access->grp_read, access->grp_write, access->grp_assignment_read,
425 access->grp_assignment_write, access->grp_scalar_read,
426 access->grp_scalar_write, access->grp_total_scalarization,
427 access->grp_hint, access->grp_covered,
428 access->grp_unscalarizable_region, access->grp_unscalarized_data,
429 access->grp_partial_lhs, access->grp_to_be_replaced,
430 access->grp_to_be_debug_replaced, access->grp_maybe_modified,
431 access->grp_not_necessarilly_dereferenced);
432 else
433 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
434 "grp_partial_lhs = %d\n",
435 access->write, access->grp_total_scalarization,
436 access->grp_partial_lhs);
437 }
438
439 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
440
441 static void
442 dump_access_tree_1 (FILE *f, struct access *access, int level)
443 {
444 do
445 {
446 int i;
447
448 for (i = 0; i < level; i++)
449 fputs ("* ", dump_file);
450
451 dump_access (f, access, true);
452
453 if (access->first_child)
454 dump_access_tree_1 (f, access->first_child, level + 1);
455
456 access = access->next_sibling;
457 }
458 while (access);
459 }
460
461 /* Dump all access trees for a variable, given the pointer to the first root in
462 ACCESS. */
463
464 static void
465 dump_access_tree (FILE *f, struct access *access)
466 {
467 for (; access; access = access->next_grp)
468 dump_access_tree_1 (f, access, 0);
469 }
470
471 /* Return true iff ACC is non-NULL and has subaccesses. */
472
473 static inline bool
474 access_has_children_p (struct access *acc)
475 {
476 return acc && acc->first_child;
477 }
478
479 /* Return true iff ACC is (partly) covered by at least one replacement. */
480
481 static bool
482 access_has_replacements_p (struct access *acc)
483 {
484 struct access *child;
485 if (acc->grp_to_be_replaced)
486 return true;
487 for (child = acc->first_child; child; child = child->next_sibling)
488 if (access_has_replacements_p (child))
489 return true;
490 return false;
491 }
492
493 /* Return a vector of pointers to accesses for the variable given in BASE or
494 NULL if there is none. */
495
496 static vec<access_p> *
497 get_base_access_vector (tree base)
498 {
499 void **slot;
500
501 slot = pointer_map_contains (base_access_vec, base);
502 if (!slot)
503 return NULL;
504 else
505 return *(vec<access_p> **) slot;
506 }
507
508 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
509 in ACCESS. Return NULL if it cannot be found. */
510
511 static struct access *
512 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
513 HOST_WIDE_INT size)
514 {
515 while (access && (access->offset != offset || access->size != size))
516 {
517 struct access *child = access->first_child;
518
519 while (child && (child->offset + child->size <= offset))
520 child = child->next_sibling;
521 access = child;
522 }
523
524 return access;
525 }
526
527 /* Return the first group representative for DECL or NULL if none exists. */
528
529 static struct access *
530 get_first_repr_for_decl (tree base)
531 {
532 vec<access_p> *access_vec;
533
534 access_vec = get_base_access_vector (base);
535 if (!access_vec)
536 return NULL;
537
538 return (*access_vec)[0];
539 }
540
541 /* Find an access representative for the variable BASE and given OFFSET and
542 SIZE. Requires that access trees have already been built. Return NULL if
543 it cannot be found. */
544
545 static struct access *
546 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
547 HOST_WIDE_INT size)
548 {
549 struct access *access;
550
551 access = get_first_repr_for_decl (base);
552 while (access && (access->offset + access->size <= offset))
553 access = access->next_grp;
554 if (!access)
555 return NULL;
556
557 return find_access_in_subtree (access, offset, size);
558 }
559
560 /* Add LINK to the linked list of assign links of RACC. */
561 static void
562 add_link_to_rhs (struct access *racc, struct assign_link *link)
563 {
564 gcc_assert (link->racc == racc);
565
566 if (!racc->first_link)
567 {
568 gcc_assert (!racc->last_link);
569 racc->first_link = link;
570 }
571 else
572 racc->last_link->next = link;
573
574 racc->last_link = link;
575 link->next = NULL;
576 }
577
578 /* Move all link structures in their linked list in OLD_RACC to the linked list
579 in NEW_RACC. */
580 static void
581 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
582 {
583 if (!old_racc->first_link)
584 {
585 gcc_assert (!old_racc->last_link);
586 return;
587 }
588
589 if (new_racc->first_link)
590 {
591 gcc_assert (!new_racc->last_link->next);
592 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
593
594 new_racc->last_link->next = old_racc->first_link;
595 new_racc->last_link = old_racc->last_link;
596 }
597 else
598 {
599 gcc_assert (!new_racc->last_link);
600
601 new_racc->first_link = old_racc->first_link;
602 new_racc->last_link = old_racc->last_link;
603 }
604 old_racc->first_link = old_racc->last_link = NULL;
605 }
606
607 /* Add ACCESS to the work queue (which is actually a stack). */
608
609 static void
610 add_access_to_work_queue (struct access *access)
611 {
612 if (!access->grp_queued)
613 {
614 gcc_assert (!access->next_queued);
615 access->next_queued = work_queue_head;
616 access->grp_queued = 1;
617 work_queue_head = access;
618 }
619 }
620
621 /* Pop an access from the work queue, and return it, assuming there is one. */
622
623 static struct access *
624 pop_access_from_work_queue (void)
625 {
626 struct access *access = work_queue_head;
627
628 work_queue_head = access->next_queued;
629 access->next_queued = NULL;
630 access->grp_queued = 0;
631 return access;
632 }
633
634
635 /* Allocate necessary structures. */
636
637 static void
638 sra_initialize (void)
639 {
640 candidate_bitmap = BITMAP_ALLOC (NULL);
641 candidates.create (vec_safe_length (cfun->local_decls) / 2);
642 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
643 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
644 gcc_obstack_init (&name_obstack);
645 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
646 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
647 base_access_vec = pointer_map_create ();
648 memset (&sra_stats, 0, sizeof (sra_stats));
649 encountered_apply_args = false;
650 encountered_recursive_call = false;
651 encountered_unchangable_recursive_call = false;
652 }
653
654 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
655
656 static bool
657 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
658 void *data ATTRIBUTE_UNUSED)
659 {
660 vec<access_p> *access_vec = (vec<access_p> *) *value;
661 vec_free (access_vec);
662 return true;
663 }
664
665 /* Deallocate all general structures. */
666
667 static void
668 sra_deinitialize (void)
669 {
670 BITMAP_FREE (candidate_bitmap);
671 candidates.dispose ();
672 BITMAP_FREE (should_scalarize_away_bitmap);
673 BITMAP_FREE (cannot_scalarize_away_bitmap);
674 free_alloc_pool (access_pool);
675 free_alloc_pool (link_pool);
676 obstack_free (&name_obstack, NULL);
677
678 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
679 pointer_map_destroy (base_access_vec);
680 }
681
682 /* Remove DECL from candidates for SRA and write REASON to the dump file if
683 there is one. */
684 static void
685 disqualify_candidate (tree decl, const char *reason)
686 {
687 if (bitmap_clear_bit (candidate_bitmap, DECL_UID (decl)))
688 candidates.clear_slot (candidates.find_slot_with_hash (decl,
689 DECL_UID (decl),
690 NO_INSERT));
691
692 if (dump_file && (dump_flags & TDF_DETAILS))
693 {
694 fprintf (dump_file, "! Disqualifying ");
695 print_generic_expr (dump_file, decl, 0);
696 fprintf (dump_file, " - %s\n", reason);
697 }
698 }
699
700 /* Return true iff the type contains a field or an element which does not allow
701 scalarization. */
702
703 static bool
704 type_internals_preclude_sra_p (tree type, const char **msg)
705 {
706 tree fld;
707 tree et;
708
709 switch (TREE_CODE (type))
710 {
711 case RECORD_TYPE:
712 case UNION_TYPE:
713 case QUAL_UNION_TYPE:
714 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
715 if (TREE_CODE (fld) == FIELD_DECL)
716 {
717 tree ft = TREE_TYPE (fld);
718
719 if (TREE_THIS_VOLATILE (fld))
720 {
721 *msg = "volatile structure field";
722 return true;
723 }
724 if (!DECL_FIELD_OFFSET (fld))
725 {
726 *msg = "no structure field offset";
727 return true;
728 }
729 if (!DECL_SIZE (fld))
730 {
731 *msg = "zero structure field size";
732 return true;
733 }
734 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
735 {
736 *msg = "structure field offset not fixed";
737 return true;
738 }
739 if (!host_integerp (DECL_SIZE (fld), 1))
740 {
741 *msg = "structure field size not fixed";
742 return true;
743 }
744 if (!host_integerp (bit_position (fld), 0))
745 {
746 *msg = "structure field size too big";
747 return true;
748 }
749 if (AGGREGATE_TYPE_P (ft)
750 && int_bit_position (fld) % BITS_PER_UNIT != 0)
751 {
752 *msg = "structure field is bit field";
753 return true;
754 }
755
756 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
757 return true;
758 }
759
760 return false;
761
762 case ARRAY_TYPE:
763 et = TREE_TYPE (type);
764
765 if (TYPE_VOLATILE (et))
766 {
767 *msg = "element type is volatile";
768 return true;
769 }
770
771 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
772 return true;
773
774 return false;
775
776 default:
777 return false;
778 }
779 }
780
781 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
782 base variable if it is. Return T if it is not an SSA_NAME. */
783
784 static tree
785 get_ssa_base_param (tree t)
786 {
787 if (TREE_CODE (t) == SSA_NAME)
788 {
789 if (SSA_NAME_IS_DEFAULT_DEF (t))
790 return SSA_NAME_VAR (t);
791 else
792 return NULL_TREE;
793 }
794 return t;
795 }
796
797 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
798 belongs to, unless the BB has already been marked as a potentially
799 final. */
800
801 static void
802 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
803 {
804 basic_block bb = gimple_bb (stmt);
805 int idx, parm_index = 0;
806 tree parm;
807
808 if (bitmap_bit_p (final_bbs, bb->index))
809 return;
810
811 for (parm = DECL_ARGUMENTS (current_function_decl);
812 parm && parm != base;
813 parm = DECL_CHAIN (parm))
814 parm_index++;
815
816 gcc_assert (parm_index < func_param_count);
817
818 idx = bb->index * func_param_count + parm_index;
819 if (bb_dereferences[idx] < dist)
820 bb_dereferences[idx] = dist;
821 }
822
823 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
824 the three fields. Also add it to the vector of accesses corresponding to
825 the base. Finally, return the new access. */
826
827 static struct access *
828 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
829 {
830 vec<access_p> *v;
831 struct access *access;
832 void **slot;
833
834 access = (struct access *) pool_alloc (access_pool);
835 memset (access, 0, sizeof (struct access));
836 access->base = base;
837 access->offset = offset;
838 access->size = size;
839
840 slot = pointer_map_contains (base_access_vec, base);
841 if (slot)
842 v = (vec<access_p> *) *slot;
843 else
844 vec_alloc (v, 32);
845
846 v->safe_push (access);
847
848 *((vec<access_p> **)
849 pointer_map_insert (base_access_vec, base)) = v;
850
851 return access;
852 }
853
854 /* Create and insert access for EXPR. Return created access, or NULL if it is
855 not possible. */
856
857 static struct access *
858 create_access (tree expr, gimple stmt, bool write)
859 {
860 struct access *access;
861 HOST_WIDE_INT offset, size, max_size;
862 tree base = expr;
863 bool ptr, unscalarizable_region = false;
864
865 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
866
867 if (sra_mode == SRA_MODE_EARLY_IPA
868 && TREE_CODE (base) == MEM_REF)
869 {
870 base = get_ssa_base_param (TREE_OPERAND (base, 0));
871 if (!base)
872 return NULL;
873 ptr = true;
874 }
875 else
876 ptr = false;
877
878 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
879 return NULL;
880
881 if (sra_mode == SRA_MODE_EARLY_IPA)
882 {
883 if (size < 0 || size != max_size)
884 {
885 disqualify_candidate (base, "Encountered a variable sized access.");
886 return NULL;
887 }
888 if (TREE_CODE (expr) == COMPONENT_REF
889 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
890 {
891 disqualify_candidate (base, "Encountered a bit-field access.");
892 return NULL;
893 }
894 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
895
896 if (ptr)
897 mark_parm_dereference (base, offset + size, stmt);
898 }
899 else
900 {
901 if (size != max_size)
902 {
903 size = max_size;
904 unscalarizable_region = true;
905 }
906 if (size < 0)
907 {
908 disqualify_candidate (base, "Encountered an unconstrained access.");
909 return NULL;
910 }
911 }
912
913 access = create_access_1 (base, offset, size);
914 access->expr = expr;
915 access->type = TREE_TYPE (expr);
916 access->write = write;
917 access->grp_unscalarizable_region = unscalarizable_region;
918 access->stmt = stmt;
919
920 if (TREE_CODE (expr) == COMPONENT_REF
921 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
922 access->non_addressable = 1;
923
924 return access;
925 }
926
927
928 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
929 register types or (recursively) records with only these two kinds of fields.
930 It also returns false if any of these records contains a bit-field. */
931
932 static bool
933 type_consists_of_records_p (tree type)
934 {
935 tree fld;
936
937 if (TREE_CODE (type) != RECORD_TYPE)
938 return false;
939
940 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
941 if (TREE_CODE (fld) == FIELD_DECL)
942 {
943 tree ft = TREE_TYPE (fld);
944
945 if (DECL_BIT_FIELD (fld))
946 return false;
947
948 if (!is_gimple_reg_type (ft)
949 && !type_consists_of_records_p (ft))
950 return false;
951 }
952
953 return true;
954 }
955
956 /* Create total_scalarization accesses for all scalar type fields in DECL that
957 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
958 must be the top-most VAR_DECL representing the variable, OFFSET must be the
959 offset of DECL within BASE. REF must be the memory reference expression for
960 the given decl. */
961
962 static void
963 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
964 tree ref)
965 {
966 tree fld, decl_type = TREE_TYPE (decl);
967
968 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
969 if (TREE_CODE (fld) == FIELD_DECL)
970 {
971 HOST_WIDE_INT pos = offset + int_bit_position (fld);
972 tree ft = TREE_TYPE (fld);
973 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
974 NULL_TREE);
975
976 if (is_gimple_reg_type (ft))
977 {
978 struct access *access;
979 HOST_WIDE_INT size;
980
981 size = tree_low_cst (DECL_SIZE (fld), 1);
982 access = create_access_1 (base, pos, size);
983 access->expr = nref;
984 access->type = ft;
985 access->grp_total_scalarization = 1;
986 /* Accesses for intraprocedural SRA can have their stmt NULL. */
987 }
988 else
989 completely_scalarize_record (base, fld, pos, nref);
990 }
991 }
992
993 /* Create total_scalarization accesses for all scalar type fields in VAR and
994 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
995 type_consists_of_records_p. */
996
997 static void
998 completely_scalarize_var (tree var)
999 {
1000 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
1001 struct access *access;
1002
1003 access = create_access_1 (var, 0, size);
1004 access->expr = var;
1005 access->type = TREE_TYPE (var);
1006 access->grp_total_scalarization = 1;
1007
1008 completely_scalarize_record (var, var, 0, var);
1009 }
1010
1011 /* Search the given tree for a declaration by skipping handled components and
1012 exclude it from the candidates. */
1013
1014 static void
1015 disqualify_base_of_expr (tree t, const char *reason)
1016 {
1017 t = get_base_address (t);
1018 if (sra_mode == SRA_MODE_EARLY_IPA
1019 && TREE_CODE (t) == MEM_REF)
1020 t = get_ssa_base_param (TREE_OPERAND (t, 0));
1021
1022 if (t && DECL_P (t))
1023 disqualify_candidate (t, reason);
1024 }
1025
1026 /* Scan expression EXPR and create access structures for all accesses to
1027 candidates for scalarization. Return the created access or NULL if none is
1028 created. */
1029
1030 static struct access *
1031 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
1032 {
1033 struct access *ret = NULL;
1034 bool partial_ref;
1035
1036 if (TREE_CODE (expr) == BIT_FIELD_REF
1037 || TREE_CODE (expr) == IMAGPART_EXPR
1038 || TREE_CODE (expr) == REALPART_EXPR)
1039 {
1040 expr = TREE_OPERAND (expr, 0);
1041 partial_ref = true;
1042 }
1043 else
1044 partial_ref = false;
1045
1046 /* We need to dive through V_C_Es in order to get the size of its parameter
1047 and not the result type. Ada produces such statements. We are also
1048 capable of handling the topmost V_C_E but not any of those buried in other
1049 handled components. */
1050 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1051 expr = TREE_OPERAND (expr, 0);
1052
1053 if (contains_view_convert_expr_p (expr))
1054 {
1055 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1056 "component.");
1057 return NULL;
1058 }
1059
1060 switch (TREE_CODE (expr))
1061 {
1062 case MEM_REF:
1063 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1064 && sra_mode != SRA_MODE_EARLY_IPA)
1065 return NULL;
1066 /* fall through */
1067 case VAR_DECL:
1068 case PARM_DECL:
1069 case RESULT_DECL:
1070 case COMPONENT_REF:
1071 case ARRAY_REF:
1072 case ARRAY_RANGE_REF:
1073 ret = create_access (expr, stmt, write);
1074 break;
1075
1076 default:
1077 break;
1078 }
1079
1080 if (write && partial_ref && ret)
1081 ret->grp_partial_lhs = 1;
1082
1083 return ret;
1084 }
1085
1086 /* Scan expression EXPR and create access structures for all accesses to
1087 candidates for scalarization. Return true if any access has been inserted.
1088 STMT must be the statement from which the expression is taken, WRITE must be
1089 true if the expression is a store and false otherwise. */
1090
1091 static bool
1092 build_access_from_expr (tree expr, gimple stmt, bool write)
1093 {
1094 struct access *access;
1095
1096 access = build_access_from_expr_1 (expr, stmt, write);
1097 if (access)
1098 {
1099 /* This means the aggregate is accesses as a whole in a way other than an
1100 assign statement and thus cannot be removed even if we had a scalar
1101 replacement for everything. */
1102 if (cannot_scalarize_away_bitmap)
1103 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1104 return true;
1105 }
1106 return false;
1107 }
1108
1109 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1110 modes in which it matters, return true iff they have been disqualified. RHS
1111 may be NULL, in that case ignore it. If we scalarize an aggregate in
1112 intra-SRA we may need to add statements after each statement. This is not
1113 possible if a statement unconditionally has to end the basic block. */
1114 static bool
1115 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1116 {
1117 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1118 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1119 {
1120 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1121 if (rhs)
1122 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1123 return true;
1124 }
1125 return false;
1126 }
1127
1128 /* Scan expressions occurring in STMT, create access structures for all accesses
1129 to candidates for scalarization and remove those candidates which occur in
1130 statements or expressions that prevent them from being split apart. Return
1131 true if any access has been inserted. */
1132
1133 static bool
1134 build_accesses_from_assign (gimple stmt)
1135 {
1136 tree lhs, rhs;
1137 struct access *lacc, *racc;
1138
1139 if (!gimple_assign_single_p (stmt)
1140 /* Scope clobbers don't influence scalarization. */
1141 || gimple_clobber_p (stmt))
1142 return false;
1143
1144 lhs = gimple_assign_lhs (stmt);
1145 rhs = gimple_assign_rhs1 (stmt);
1146
1147 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1148 return false;
1149
1150 racc = build_access_from_expr_1 (rhs, stmt, false);
1151 lacc = build_access_from_expr_1 (lhs, stmt, true);
1152
1153 if (lacc)
1154 lacc->grp_assignment_write = 1;
1155
1156 if (racc)
1157 {
1158 racc->grp_assignment_read = 1;
1159 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1160 && !is_gimple_reg_type (racc->type))
1161 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1162 }
1163
1164 if (lacc && racc
1165 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1166 && !lacc->grp_unscalarizable_region
1167 && !racc->grp_unscalarizable_region
1168 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1169 && lacc->size == racc->size
1170 && useless_type_conversion_p (lacc->type, racc->type))
1171 {
1172 struct assign_link *link;
1173
1174 link = (struct assign_link *) pool_alloc (link_pool);
1175 memset (link, 0, sizeof (struct assign_link));
1176
1177 link->lacc = lacc;
1178 link->racc = racc;
1179
1180 add_link_to_rhs (racc, link);
1181 }
1182
1183 return lacc || racc;
1184 }
1185
1186 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1187 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1188
1189 static bool
1190 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1191 void *data ATTRIBUTE_UNUSED)
1192 {
1193 op = get_base_address (op);
1194 if (op
1195 && DECL_P (op))
1196 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1197
1198 return false;
1199 }
1200
1201 /* Return true iff callsite CALL has at least as many actual arguments as there
1202 are formal parameters of the function currently processed by IPA-SRA. */
1203
1204 static inline bool
1205 callsite_has_enough_arguments_p (gimple call)
1206 {
1207 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1208 }
1209
1210 /* Scan function and look for interesting expressions and create access
1211 structures for them. Return true iff any access is created. */
1212
1213 static bool
1214 scan_function (void)
1215 {
1216 basic_block bb;
1217 bool ret = false;
1218
1219 FOR_EACH_BB (bb)
1220 {
1221 gimple_stmt_iterator gsi;
1222 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1223 {
1224 gimple stmt = gsi_stmt (gsi);
1225 tree t;
1226 unsigned i;
1227
1228 if (final_bbs && stmt_can_throw_external (stmt))
1229 bitmap_set_bit (final_bbs, bb->index);
1230 switch (gimple_code (stmt))
1231 {
1232 case GIMPLE_RETURN:
1233 t = gimple_return_retval (stmt);
1234 if (t != NULL_TREE)
1235 ret |= build_access_from_expr (t, stmt, false);
1236 if (final_bbs)
1237 bitmap_set_bit (final_bbs, bb->index);
1238 break;
1239
1240 case GIMPLE_ASSIGN:
1241 ret |= build_accesses_from_assign (stmt);
1242 break;
1243
1244 case GIMPLE_CALL:
1245 for (i = 0; i < gimple_call_num_args (stmt); i++)
1246 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1247 stmt, false);
1248
1249 if (sra_mode == SRA_MODE_EARLY_IPA)
1250 {
1251 tree dest = gimple_call_fndecl (stmt);
1252 int flags = gimple_call_flags (stmt);
1253
1254 if (dest)
1255 {
1256 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1257 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1258 encountered_apply_args = true;
1259 if (cgraph_get_node (dest)
1260 == cgraph_get_node (current_function_decl))
1261 {
1262 encountered_recursive_call = true;
1263 if (!callsite_has_enough_arguments_p (stmt))
1264 encountered_unchangable_recursive_call = true;
1265 }
1266 }
1267
1268 if (final_bbs
1269 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1270 bitmap_set_bit (final_bbs, bb->index);
1271 }
1272
1273 t = gimple_call_lhs (stmt);
1274 if (t && !disqualify_ops_if_throwing_stmt (stmt, t, NULL))
1275 ret |= build_access_from_expr (t, stmt, true);
1276 break;
1277
1278 case GIMPLE_ASM:
1279 walk_stmt_load_store_addr_ops (stmt, NULL, NULL, NULL,
1280 asm_visit_addr);
1281 if (final_bbs)
1282 bitmap_set_bit (final_bbs, bb->index);
1283
1284 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1285 {
1286 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1287 ret |= build_access_from_expr (t, stmt, false);
1288 }
1289 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1290 {
1291 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1292 ret |= build_access_from_expr (t, stmt, true);
1293 }
1294 break;
1295
1296 default:
1297 break;
1298 }
1299 }
1300 }
1301
1302 return ret;
1303 }
1304
1305 /* Helper of QSORT function. There are pointers to accesses in the array. An
1306 access is considered smaller than another if it has smaller offset or if the
1307 offsets are the same but is size is bigger. */
1308
1309 static int
1310 compare_access_positions (const void *a, const void *b)
1311 {
1312 const access_p *fp1 = (const access_p *) a;
1313 const access_p *fp2 = (const access_p *) b;
1314 const access_p f1 = *fp1;
1315 const access_p f2 = *fp2;
1316
1317 if (f1->offset != f2->offset)
1318 return f1->offset < f2->offset ? -1 : 1;
1319
1320 if (f1->size == f2->size)
1321 {
1322 if (f1->type == f2->type)
1323 return 0;
1324 /* Put any non-aggregate type before any aggregate type. */
1325 else if (!is_gimple_reg_type (f1->type)
1326 && is_gimple_reg_type (f2->type))
1327 return 1;
1328 else if (is_gimple_reg_type (f1->type)
1329 && !is_gimple_reg_type (f2->type))
1330 return -1;
1331 /* Put any complex or vector type before any other scalar type. */
1332 else if (TREE_CODE (f1->type) != COMPLEX_TYPE
1333 && TREE_CODE (f1->type) != VECTOR_TYPE
1334 && (TREE_CODE (f2->type) == COMPLEX_TYPE
1335 || TREE_CODE (f2->type) == VECTOR_TYPE))
1336 return 1;
1337 else if ((TREE_CODE (f1->type) == COMPLEX_TYPE
1338 || TREE_CODE (f1->type) == VECTOR_TYPE)
1339 && TREE_CODE (f2->type) != COMPLEX_TYPE
1340 && TREE_CODE (f2->type) != VECTOR_TYPE)
1341 return -1;
1342 /* Put the integral type with the bigger precision first. */
1343 else if (INTEGRAL_TYPE_P (f1->type)
1344 && INTEGRAL_TYPE_P (f2->type))
1345 return TYPE_PRECISION (f2->type) - TYPE_PRECISION (f1->type);
1346 /* Put any integral type with non-full precision last. */
1347 else if (INTEGRAL_TYPE_P (f1->type)
1348 && (TREE_INT_CST_LOW (TYPE_SIZE (f1->type))
1349 != TYPE_PRECISION (f1->type)))
1350 return 1;
1351 else if (INTEGRAL_TYPE_P (f2->type)
1352 && (TREE_INT_CST_LOW (TYPE_SIZE (f2->type))
1353 != TYPE_PRECISION (f2->type)))
1354 return -1;
1355 /* Stabilize the sort. */
1356 return TYPE_UID (f1->type) - TYPE_UID (f2->type);
1357 }
1358
1359 /* We want the bigger accesses first, thus the opposite operator in the next
1360 line: */
1361 return f1->size > f2->size ? -1 : 1;
1362 }
1363
1364
1365 /* Append a name of the declaration to the name obstack. A helper function for
1366 make_fancy_name. */
1367
1368 static void
1369 make_fancy_decl_name (tree decl)
1370 {
1371 char buffer[32];
1372
1373 tree name = DECL_NAME (decl);
1374 if (name)
1375 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1376 IDENTIFIER_LENGTH (name));
1377 else
1378 {
1379 sprintf (buffer, "D%u", DECL_UID (decl));
1380 obstack_grow (&name_obstack, buffer, strlen (buffer));
1381 }
1382 }
1383
1384 /* Helper for make_fancy_name. */
1385
1386 static void
1387 make_fancy_name_1 (tree expr)
1388 {
1389 char buffer[32];
1390 tree index;
1391
1392 if (DECL_P (expr))
1393 {
1394 make_fancy_decl_name (expr);
1395 return;
1396 }
1397
1398 switch (TREE_CODE (expr))
1399 {
1400 case COMPONENT_REF:
1401 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1402 obstack_1grow (&name_obstack, '$');
1403 make_fancy_decl_name (TREE_OPERAND (expr, 1));
1404 break;
1405
1406 case ARRAY_REF:
1407 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1408 obstack_1grow (&name_obstack, '$');
1409 /* Arrays with only one element may not have a constant as their
1410 index. */
1411 index = TREE_OPERAND (expr, 1);
1412 if (TREE_CODE (index) != INTEGER_CST)
1413 break;
1414 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (index));
1415 obstack_grow (&name_obstack, buffer, strlen (buffer));
1416 break;
1417
1418 case ADDR_EXPR:
1419 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1420 break;
1421
1422 case MEM_REF:
1423 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1424 if (!integer_zerop (TREE_OPERAND (expr, 1)))
1425 {
1426 obstack_1grow (&name_obstack, '$');
1427 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC,
1428 TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
1429 obstack_grow (&name_obstack, buffer, strlen (buffer));
1430 }
1431 break;
1432
1433 case BIT_FIELD_REF:
1434 case REALPART_EXPR:
1435 case IMAGPART_EXPR:
1436 gcc_unreachable (); /* we treat these as scalars. */
1437 break;
1438 default:
1439 break;
1440 }
1441 }
1442
1443 /* Create a human readable name for replacement variable of ACCESS. */
1444
1445 static char *
1446 make_fancy_name (tree expr)
1447 {
1448 make_fancy_name_1 (expr);
1449 obstack_1grow (&name_obstack, '\0');
1450 return XOBFINISH (&name_obstack, char *);
1451 }
1452
1453 /* Construct a MEM_REF that would reference a part of aggregate BASE of type
1454 EXP_TYPE at the given OFFSET. If BASE is something for which
1455 get_addr_base_and_unit_offset returns NULL, gsi must be non-NULL and is used
1456 to insert new statements either before or below the current one as specified
1457 by INSERT_AFTER. This function is not capable of handling bitfields.
1458
1459 BASE must be either a declaration or a memory reference that has correct
1460 alignment ifformation embeded in it (e.g. a pre-existing one in SRA). */
1461
1462 tree
1463 build_ref_for_offset (location_t loc, tree base, HOST_WIDE_INT offset,
1464 tree exp_type, gimple_stmt_iterator *gsi,
1465 bool insert_after)
1466 {
1467 tree prev_base = base;
1468 tree off;
1469 HOST_WIDE_INT base_offset;
1470 unsigned HOST_WIDE_INT misalign;
1471 unsigned int align;
1472
1473 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1474 get_object_alignment_1 (base, &align, &misalign);
1475 base = get_addr_base_and_unit_offset (base, &base_offset);
1476
1477 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1478 offset such as array[var_index]. */
1479 if (!base)
1480 {
1481 gimple stmt;
1482 tree tmp, addr;
1483
1484 gcc_checking_assert (gsi);
1485 tmp = make_ssa_name (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1486 addr = build_fold_addr_expr (unshare_expr (prev_base));
1487 STRIP_USELESS_TYPE_CONVERSION (addr);
1488 stmt = gimple_build_assign (tmp, addr);
1489 gimple_set_location (stmt, loc);
1490 if (insert_after)
1491 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1492 else
1493 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1494
1495 off = build_int_cst (reference_alias_ptr_type (prev_base),
1496 offset / BITS_PER_UNIT);
1497 base = tmp;
1498 }
1499 else if (TREE_CODE (base) == MEM_REF)
1500 {
1501 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1502 base_offset + offset / BITS_PER_UNIT);
1503 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1504 base = unshare_expr (TREE_OPERAND (base, 0));
1505 }
1506 else
1507 {
1508 off = build_int_cst (reference_alias_ptr_type (base),
1509 base_offset + offset / BITS_PER_UNIT);
1510 base = build_fold_addr_expr (unshare_expr (base));
1511 }
1512
1513 misalign = (misalign + offset) & (align - 1);
1514 if (misalign != 0)
1515 align = (misalign & -misalign);
1516 if (align < TYPE_ALIGN (exp_type))
1517 exp_type = build_aligned_type (exp_type, align);
1518
1519 return fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1520 }
1521
1522 /* Construct a memory reference to a part of an aggregate BASE at the given
1523 OFFSET and of the same type as MODEL. In case this is a reference to a
1524 bit-field, the function will replicate the last component_ref of model's
1525 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1526 build_ref_for_offset. */
1527
1528 static tree
1529 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1530 struct access *model, gimple_stmt_iterator *gsi,
1531 bool insert_after)
1532 {
1533 if (TREE_CODE (model->expr) == COMPONENT_REF
1534 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1535 {
1536 /* This access represents a bit-field. */
1537 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1538
1539 offset -= int_bit_position (fld);
1540 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1541 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1542 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1543 NULL_TREE);
1544 }
1545 else
1546 return build_ref_for_offset (loc, base, offset, model->type,
1547 gsi, insert_after);
1548 }
1549
1550 /* Attempt to build a memory reference that we could but into a gimple
1551 debug_bind statement. Similar to build_ref_for_model but punts if it has to
1552 create statements and return s NULL instead. This function also ignores
1553 alignment issues and so its results should never end up in non-debug
1554 statements. */
1555
1556 static tree
1557 build_debug_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1558 struct access *model)
1559 {
1560 HOST_WIDE_INT base_offset;
1561 tree off;
1562
1563 if (TREE_CODE (model->expr) == COMPONENT_REF
1564 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1565 return NULL_TREE;
1566
1567 base = get_addr_base_and_unit_offset (base, &base_offset);
1568 if (!base)
1569 return NULL_TREE;
1570 if (TREE_CODE (base) == MEM_REF)
1571 {
1572 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1573 base_offset + offset / BITS_PER_UNIT);
1574 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1575 base = unshare_expr (TREE_OPERAND (base, 0));
1576 }
1577 else
1578 {
1579 off = build_int_cst (reference_alias_ptr_type (base),
1580 base_offset + offset / BITS_PER_UNIT);
1581 base = build_fold_addr_expr (unshare_expr (base));
1582 }
1583
1584 return fold_build2_loc (loc, MEM_REF, model->type, base, off);
1585 }
1586
1587 /* Construct a memory reference consisting of component_refs and array_refs to
1588 a part of an aggregate *RES (which is of type TYPE). The requested part
1589 should have type EXP_TYPE at be the given OFFSET. This function might not
1590 succeed, it returns true when it does and only then *RES points to something
1591 meaningful. This function should be used only to build expressions that we
1592 might need to present to user (e.g. in warnings). In all other situations,
1593 build_ref_for_model or build_ref_for_offset should be used instead. */
1594
1595 static bool
1596 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1597 tree exp_type)
1598 {
1599 while (1)
1600 {
1601 tree fld;
1602 tree tr_size, index, minidx;
1603 HOST_WIDE_INT el_size;
1604
1605 if (offset == 0 && exp_type
1606 && types_compatible_p (exp_type, type))
1607 return true;
1608
1609 switch (TREE_CODE (type))
1610 {
1611 case UNION_TYPE:
1612 case QUAL_UNION_TYPE:
1613 case RECORD_TYPE:
1614 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1615 {
1616 HOST_WIDE_INT pos, size;
1617 tree tr_pos, expr, *expr_ptr;
1618
1619 if (TREE_CODE (fld) != FIELD_DECL)
1620 continue;
1621
1622 tr_pos = bit_position (fld);
1623 if (!tr_pos || !host_integerp (tr_pos, 1))
1624 continue;
1625 pos = TREE_INT_CST_LOW (tr_pos);
1626 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1627 tr_size = DECL_SIZE (fld);
1628 if (!tr_size || !host_integerp (tr_size, 1))
1629 continue;
1630 size = TREE_INT_CST_LOW (tr_size);
1631 if (size == 0)
1632 {
1633 if (pos != offset)
1634 continue;
1635 }
1636 else if (pos > offset || (pos + size) <= offset)
1637 continue;
1638
1639 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1640 NULL_TREE);
1641 expr_ptr = &expr;
1642 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1643 offset - pos, exp_type))
1644 {
1645 *res = expr;
1646 return true;
1647 }
1648 }
1649 return false;
1650
1651 case ARRAY_TYPE:
1652 tr_size = TYPE_SIZE (TREE_TYPE (type));
1653 if (!tr_size || !host_integerp (tr_size, 1))
1654 return false;
1655 el_size = tree_low_cst (tr_size, 1);
1656
1657 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1658 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1659 return false;
1660 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1661 if (!integer_zerop (minidx))
1662 index = int_const_binop (PLUS_EXPR, index, minidx);
1663 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1664 NULL_TREE, NULL_TREE);
1665 offset = offset % el_size;
1666 type = TREE_TYPE (type);
1667 break;
1668
1669 default:
1670 if (offset != 0)
1671 return false;
1672
1673 if (exp_type)
1674 return false;
1675 else
1676 return true;
1677 }
1678 }
1679 }
1680
1681 /* Return true iff TYPE is stdarg va_list type. */
1682
1683 static inline bool
1684 is_va_list_type (tree type)
1685 {
1686 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1687 }
1688
1689 /* Print message to dump file why a variable was rejected. */
1690
1691 static void
1692 reject (tree var, const char *msg)
1693 {
1694 if (dump_file && (dump_flags & TDF_DETAILS))
1695 {
1696 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1697 print_generic_expr (dump_file, var, 0);
1698 fprintf (dump_file, "\n");
1699 }
1700 }
1701
1702 /* Return true if VAR is a candidate for SRA. */
1703
1704 static bool
1705 maybe_add_sra_candidate (tree var)
1706 {
1707 tree type = TREE_TYPE (var);
1708 const char *msg;
1709 tree_node **slot;
1710
1711 if (!AGGREGATE_TYPE_P (type))
1712 {
1713 reject (var, "not aggregate");
1714 return false;
1715 }
1716 if (needs_to_live_in_memory (var))
1717 {
1718 reject (var, "needs to live in memory");
1719 return false;
1720 }
1721 if (TREE_THIS_VOLATILE (var))
1722 {
1723 reject (var, "is volatile");
1724 return false;
1725 }
1726 if (!COMPLETE_TYPE_P (type))
1727 {
1728 reject (var, "has incomplete type");
1729 return false;
1730 }
1731 if (!host_integerp (TYPE_SIZE (type), 1))
1732 {
1733 reject (var, "type size not fixed");
1734 return false;
1735 }
1736 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1737 {
1738 reject (var, "type size is zero");
1739 return false;
1740 }
1741 if (type_internals_preclude_sra_p (type, &msg))
1742 {
1743 reject (var, msg);
1744 return false;
1745 }
1746 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1747 we also want to schedule it rather late. Thus we ignore it in
1748 the early pass. */
1749 (sra_mode == SRA_MODE_EARLY_INTRA
1750 && is_va_list_type (type)))
1751 {
1752 reject (var, "is va_list");
1753 return false;
1754 }
1755
1756 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1757 slot = candidates.find_slot_with_hash (var, DECL_UID (var), INSERT);
1758 *slot = var;
1759
1760 if (dump_file && (dump_flags & TDF_DETAILS))
1761 {
1762 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1763 print_generic_expr (dump_file, var, 0);
1764 fprintf (dump_file, "\n");
1765 }
1766
1767 return true;
1768 }
1769
1770 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1771 those with type which is suitable for scalarization. */
1772
1773 static bool
1774 find_var_candidates (void)
1775 {
1776 tree var, parm;
1777 unsigned int i;
1778 bool ret = false;
1779
1780 for (parm = DECL_ARGUMENTS (current_function_decl);
1781 parm;
1782 parm = DECL_CHAIN (parm))
1783 ret |= maybe_add_sra_candidate (parm);
1784
1785 FOR_EACH_LOCAL_DECL (cfun, i, var)
1786 {
1787 if (TREE_CODE (var) != VAR_DECL)
1788 continue;
1789
1790 ret |= maybe_add_sra_candidate (var);
1791 }
1792
1793 return ret;
1794 }
1795
1796 /* Sort all accesses for the given variable, check for partial overlaps and
1797 return NULL if there are any. If there are none, pick a representative for
1798 each combination of offset and size and create a linked list out of them.
1799 Return the pointer to the first representative and make sure it is the first
1800 one in the vector of accesses. */
1801
1802 static struct access *
1803 sort_and_splice_var_accesses (tree var)
1804 {
1805 int i, j, access_count;
1806 struct access *res, **prev_acc_ptr = &res;
1807 vec<access_p> *access_vec;
1808 bool first = true;
1809 HOST_WIDE_INT low = -1, high = 0;
1810
1811 access_vec = get_base_access_vector (var);
1812 if (!access_vec)
1813 return NULL;
1814 access_count = access_vec->length ();
1815
1816 /* Sort by <OFFSET, SIZE>. */
1817 access_vec->qsort (compare_access_positions);
1818
1819 i = 0;
1820 while (i < access_count)
1821 {
1822 struct access *access = (*access_vec)[i];
1823 bool grp_write = access->write;
1824 bool grp_read = !access->write;
1825 bool grp_scalar_write = access->write
1826 && is_gimple_reg_type (access->type);
1827 bool grp_scalar_read = !access->write
1828 && is_gimple_reg_type (access->type);
1829 bool grp_assignment_read = access->grp_assignment_read;
1830 bool grp_assignment_write = access->grp_assignment_write;
1831 bool multiple_scalar_reads = false;
1832 bool total_scalarization = access->grp_total_scalarization;
1833 bool grp_partial_lhs = access->grp_partial_lhs;
1834 bool first_scalar = is_gimple_reg_type (access->type);
1835 bool unscalarizable_region = access->grp_unscalarizable_region;
1836
1837 if (first || access->offset >= high)
1838 {
1839 first = false;
1840 low = access->offset;
1841 high = access->offset + access->size;
1842 }
1843 else if (access->offset > low && access->offset + access->size > high)
1844 return NULL;
1845 else
1846 gcc_assert (access->offset >= low
1847 && access->offset + access->size <= high);
1848
1849 j = i + 1;
1850 while (j < access_count)
1851 {
1852 struct access *ac2 = (*access_vec)[j];
1853 if (ac2->offset != access->offset || ac2->size != access->size)
1854 break;
1855 if (ac2->write)
1856 {
1857 grp_write = true;
1858 grp_scalar_write = (grp_scalar_write
1859 || is_gimple_reg_type (ac2->type));
1860 }
1861 else
1862 {
1863 grp_read = true;
1864 if (is_gimple_reg_type (ac2->type))
1865 {
1866 if (grp_scalar_read)
1867 multiple_scalar_reads = true;
1868 else
1869 grp_scalar_read = true;
1870 }
1871 }
1872 grp_assignment_read |= ac2->grp_assignment_read;
1873 grp_assignment_write |= ac2->grp_assignment_write;
1874 grp_partial_lhs |= ac2->grp_partial_lhs;
1875 unscalarizable_region |= ac2->grp_unscalarizable_region;
1876 total_scalarization |= ac2->grp_total_scalarization;
1877 relink_to_new_repr (access, ac2);
1878
1879 /* If there are both aggregate-type and scalar-type accesses with
1880 this combination of size and offset, the comparison function
1881 should have put the scalars first. */
1882 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1883 ac2->group_representative = access;
1884 j++;
1885 }
1886
1887 i = j;
1888
1889 access->group_representative = access;
1890 access->grp_write = grp_write;
1891 access->grp_read = grp_read;
1892 access->grp_scalar_read = grp_scalar_read;
1893 access->grp_scalar_write = grp_scalar_write;
1894 access->grp_assignment_read = grp_assignment_read;
1895 access->grp_assignment_write = grp_assignment_write;
1896 access->grp_hint = multiple_scalar_reads || total_scalarization;
1897 access->grp_total_scalarization = total_scalarization;
1898 access->grp_partial_lhs = grp_partial_lhs;
1899 access->grp_unscalarizable_region = unscalarizable_region;
1900 if (access->first_link)
1901 add_access_to_work_queue (access);
1902
1903 *prev_acc_ptr = access;
1904 prev_acc_ptr = &access->next_grp;
1905 }
1906
1907 gcc_assert (res == (*access_vec)[0]);
1908 return res;
1909 }
1910
1911 /* Create a variable for the given ACCESS which determines the type, name and a
1912 few other properties. Return the variable declaration and store it also to
1913 ACCESS->replacement. */
1914
1915 static tree
1916 create_access_replacement (struct access *access)
1917 {
1918 tree repl;
1919
1920 if (access->grp_to_be_debug_replaced)
1921 {
1922 repl = create_tmp_var_raw (access->type, NULL);
1923 DECL_CONTEXT (repl) = current_function_decl;
1924 }
1925 else
1926 repl = create_tmp_var (access->type, "SR");
1927 if (TREE_CODE (access->type) == COMPLEX_TYPE
1928 || TREE_CODE (access->type) == VECTOR_TYPE)
1929 {
1930 if (!access->grp_partial_lhs)
1931 DECL_GIMPLE_REG_P (repl) = 1;
1932 }
1933 else if (access->grp_partial_lhs
1934 && is_gimple_reg_type (access->type))
1935 TREE_ADDRESSABLE (repl) = 1;
1936
1937 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1938 DECL_ARTIFICIAL (repl) = 1;
1939 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1940
1941 if (DECL_NAME (access->base)
1942 && !DECL_IGNORED_P (access->base)
1943 && !DECL_ARTIFICIAL (access->base))
1944 {
1945 char *pretty_name = make_fancy_name (access->expr);
1946 tree debug_expr = unshare_expr_without_location (access->expr), d;
1947 bool fail = false;
1948
1949 DECL_NAME (repl) = get_identifier (pretty_name);
1950 obstack_free (&name_obstack, pretty_name);
1951
1952 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1953 as DECL_DEBUG_EXPR isn't considered when looking for still
1954 used SSA_NAMEs and thus they could be freed. All debug info
1955 generation cares is whether something is constant or variable
1956 and that get_ref_base_and_extent works properly on the
1957 expression. It cannot handle accesses at a non-constant offset
1958 though, so just give up in those cases. */
1959 for (d = debug_expr;
1960 !fail && (handled_component_p (d) || TREE_CODE (d) == MEM_REF);
1961 d = TREE_OPERAND (d, 0))
1962 switch (TREE_CODE (d))
1963 {
1964 case ARRAY_REF:
1965 case ARRAY_RANGE_REF:
1966 if (TREE_OPERAND (d, 1)
1967 && TREE_CODE (TREE_OPERAND (d, 1)) != INTEGER_CST)
1968 fail = true;
1969 if (TREE_OPERAND (d, 3)
1970 && TREE_CODE (TREE_OPERAND (d, 3)) != INTEGER_CST)
1971 fail = true;
1972 /* FALLTHRU */
1973 case COMPONENT_REF:
1974 if (TREE_OPERAND (d, 2)
1975 && TREE_CODE (TREE_OPERAND (d, 2)) != INTEGER_CST)
1976 fail = true;
1977 break;
1978 case MEM_REF:
1979 if (TREE_CODE (TREE_OPERAND (d, 0)) != ADDR_EXPR)
1980 fail = true;
1981 else
1982 d = TREE_OPERAND (d, 0);
1983 break;
1984 default:
1985 break;
1986 }
1987 if (!fail)
1988 {
1989 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1990 DECL_HAS_DEBUG_EXPR_P (repl) = 1;
1991 }
1992 if (access->grp_no_warning)
1993 TREE_NO_WARNING (repl) = 1;
1994 else
1995 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
1996 }
1997 else
1998 TREE_NO_WARNING (repl) = 1;
1999
2000 if (dump_file)
2001 {
2002 if (access->grp_to_be_debug_replaced)
2003 {
2004 fprintf (dump_file, "Created a debug-only replacement for ");
2005 print_generic_expr (dump_file, access->base, 0);
2006 fprintf (dump_file, " offset: %u, size: %u\n",
2007 (unsigned) access->offset, (unsigned) access->size);
2008 }
2009 else
2010 {
2011 fprintf (dump_file, "Created a replacement for ");
2012 print_generic_expr (dump_file, access->base, 0);
2013 fprintf (dump_file, " offset: %u, size: %u: ",
2014 (unsigned) access->offset, (unsigned) access->size);
2015 print_generic_expr (dump_file, repl, 0);
2016 fprintf (dump_file, "\n");
2017 }
2018 }
2019 sra_stats.replacements++;
2020
2021 return repl;
2022 }
2023
2024 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
2025
2026 static inline tree
2027 get_access_replacement (struct access *access)
2028 {
2029 gcc_checking_assert (access->replacement_decl);
2030 return access->replacement_decl;
2031 }
2032
2033
2034 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
2035 linked list along the way. Stop when *ACCESS is NULL or the access pointed
2036 to it is not "within" the root. Return false iff some accesses partially
2037 overlap. */
2038
2039 static bool
2040 build_access_subtree (struct access **access)
2041 {
2042 struct access *root = *access, *last_child = NULL;
2043 HOST_WIDE_INT limit = root->offset + root->size;
2044
2045 *access = (*access)->next_grp;
2046 while (*access && (*access)->offset + (*access)->size <= limit)
2047 {
2048 if (!last_child)
2049 root->first_child = *access;
2050 else
2051 last_child->next_sibling = *access;
2052 last_child = *access;
2053
2054 if (!build_access_subtree (access))
2055 return false;
2056 }
2057
2058 if (*access && (*access)->offset < limit)
2059 return false;
2060
2061 return true;
2062 }
2063
2064 /* Build a tree of access representatives, ACCESS is the pointer to the first
2065 one, others are linked in a list by the next_grp field. Return false iff
2066 some accesses partially overlap. */
2067
2068 static bool
2069 build_access_trees (struct access *access)
2070 {
2071 while (access)
2072 {
2073 struct access *root = access;
2074
2075 if (!build_access_subtree (&access))
2076 return false;
2077 root->next_grp = access;
2078 }
2079 return true;
2080 }
2081
2082 /* Return true if expr contains some ARRAY_REFs into a variable bounded
2083 array. */
2084
2085 static bool
2086 expr_with_var_bounded_array_refs_p (tree expr)
2087 {
2088 while (handled_component_p (expr))
2089 {
2090 if (TREE_CODE (expr) == ARRAY_REF
2091 && !host_integerp (array_ref_low_bound (expr), 0))
2092 return true;
2093 expr = TREE_OPERAND (expr, 0);
2094 }
2095 return false;
2096 }
2097
2098 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2099 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2100 sorts of access flags appropriately along the way, notably always set
2101 grp_read and grp_assign_read according to MARK_READ and grp_write when
2102 MARK_WRITE is true.
2103
2104 Creating a replacement for a scalar access is considered beneficial if its
2105 grp_hint is set (this means we are either attempting total scalarization or
2106 there is more than one direct read access) or according to the following
2107 table:
2108
2109 Access written to through a scalar type (once or more times)
2110 |
2111 | Written to in an assignment statement
2112 | |
2113 | | Access read as scalar _once_
2114 | | |
2115 | | | Read in an assignment statement
2116 | | | |
2117 | | | | Scalarize Comment
2118 -----------------------------------------------------------------------------
2119 0 0 0 0 No access for the scalar
2120 0 0 0 1 No access for the scalar
2121 0 0 1 0 No Single read - won't help
2122 0 0 1 1 No The same case
2123 0 1 0 0 No access for the scalar
2124 0 1 0 1 No access for the scalar
2125 0 1 1 0 Yes s = *g; return s.i;
2126 0 1 1 1 Yes The same case as above
2127 1 0 0 0 No Won't help
2128 1 0 0 1 Yes s.i = 1; *g = s;
2129 1 0 1 0 Yes s.i = 5; g = s.i;
2130 1 0 1 1 Yes The same case as above
2131 1 1 0 0 No Won't help.
2132 1 1 0 1 Yes s.i = 1; *g = s;
2133 1 1 1 0 Yes s = *g; return s.i;
2134 1 1 1 1 Yes Any of the above yeses */
2135
2136 static bool
2137 analyze_access_subtree (struct access *root, struct access *parent,
2138 bool allow_replacements)
2139 {
2140 struct access *child;
2141 HOST_WIDE_INT limit = root->offset + root->size;
2142 HOST_WIDE_INT covered_to = root->offset;
2143 bool scalar = is_gimple_reg_type (root->type);
2144 bool hole = false, sth_created = false;
2145
2146 if (parent)
2147 {
2148 if (parent->grp_read)
2149 root->grp_read = 1;
2150 if (parent->grp_assignment_read)
2151 root->grp_assignment_read = 1;
2152 if (parent->grp_write)
2153 root->grp_write = 1;
2154 if (parent->grp_assignment_write)
2155 root->grp_assignment_write = 1;
2156 if (parent->grp_total_scalarization)
2157 root->grp_total_scalarization = 1;
2158 }
2159
2160 if (root->grp_unscalarizable_region)
2161 allow_replacements = false;
2162
2163 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2164 allow_replacements = false;
2165
2166 for (child = root->first_child; child; child = child->next_sibling)
2167 {
2168 hole |= covered_to < child->offset;
2169 sth_created |= analyze_access_subtree (child, root,
2170 allow_replacements && !scalar);
2171
2172 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2173 root->grp_total_scalarization &= child->grp_total_scalarization;
2174 if (child->grp_covered)
2175 covered_to += child->size;
2176 else
2177 hole = true;
2178 }
2179
2180 if (allow_replacements && scalar && !root->first_child
2181 && (root->grp_hint
2182 || ((root->grp_scalar_read || root->grp_assignment_read)
2183 && (root->grp_scalar_write || root->grp_assignment_write))))
2184 {
2185 /* Always create access replacements that cover the whole access.
2186 For integral types this means the precision has to match.
2187 Avoid assumptions based on the integral type kind, too. */
2188 if (INTEGRAL_TYPE_P (root->type)
2189 && (TREE_CODE (root->type) != INTEGER_TYPE
2190 || TYPE_PRECISION (root->type) != root->size)
2191 /* But leave bitfield accesses alone. */
2192 && (TREE_CODE (root->expr) != COMPONENT_REF
2193 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2194 {
2195 tree rt = root->type;
2196 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2197 && (root->size % BITS_PER_UNIT) == 0);
2198 root->type = build_nonstandard_integer_type (root->size,
2199 TYPE_UNSIGNED (rt));
2200 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2201 root->base, root->offset,
2202 root->type, NULL, false);
2203
2204 if (dump_file && (dump_flags & TDF_DETAILS))
2205 {
2206 fprintf (dump_file, "Changing the type of a replacement for ");
2207 print_generic_expr (dump_file, root->base, 0);
2208 fprintf (dump_file, " offset: %u, size: %u ",
2209 (unsigned) root->offset, (unsigned) root->size);
2210 fprintf (dump_file, " to an integer.\n");
2211 }
2212 }
2213
2214 root->grp_to_be_replaced = 1;
2215 root->replacement_decl = create_access_replacement (root);
2216 sth_created = true;
2217 hole = false;
2218 }
2219 else
2220 {
2221 if (allow_replacements
2222 && scalar && !root->first_child
2223 && (root->grp_scalar_write || root->grp_assignment_write)
2224 && !bitmap_bit_p (cannot_scalarize_away_bitmap,
2225 DECL_UID (root->base)))
2226 {
2227 gcc_checking_assert (!root->grp_scalar_read
2228 && !root->grp_assignment_read);
2229 sth_created = true;
2230 if (MAY_HAVE_DEBUG_STMTS)
2231 {
2232 root->grp_to_be_debug_replaced = 1;
2233 root->replacement_decl = create_access_replacement (root);
2234 }
2235 }
2236
2237 if (covered_to < limit)
2238 hole = true;
2239 if (scalar)
2240 root->grp_total_scalarization = 0;
2241 }
2242
2243 if (!hole || root->grp_total_scalarization)
2244 root->grp_covered = 1;
2245 else if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2246 root->grp_unscalarized_data = 1; /* not covered and written to */
2247 return sth_created;
2248 }
2249
2250 /* Analyze all access trees linked by next_grp by the means of
2251 analyze_access_subtree. */
2252 static bool
2253 analyze_access_trees (struct access *access)
2254 {
2255 bool ret = false;
2256
2257 while (access)
2258 {
2259 if (analyze_access_subtree (access, NULL, true))
2260 ret = true;
2261 access = access->next_grp;
2262 }
2263
2264 return ret;
2265 }
2266
2267 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2268 SIZE would conflict with an already existing one. If exactly such a child
2269 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2270
2271 static bool
2272 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2273 HOST_WIDE_INT size, struct access **exact_match)
2274 {
2275 struct access *child;
2276
2277 for (child = lacc->first_child; child; child = child->next_sibling)
2278 {
2279 if (child->offset == norm_offset && child->size == size)
2280 {
2281 *exact_match = child;
2282 return true;
2283 }
2284
2285 if (child->offset < norm_offset + size
2286 && child->offset + child->size > norm_offset)
2287 return true;
2288 }
2289
2290 return false;
2291 }
2292
2293 /* Create a new child access of PARENT, with all properties just like MODEL
2294 except for its offset and with its grp_write false and grp_read true.
2295 Return the new access or NULL if it cannot be created. Note that this access
2296 is created long after all splicing and sorting, it's not located in any
2297 access vector and is automatically a representative of its group. */
2298
2299 static struct access *
2300 create_artificial_child_access (struct access *parent, struct access *model,
2301 HOST_WIDE_INT new_offset)
2302 {
2303 struct access *access;
2304 struct access **child;
2305 tree expr = parent->base;
2306
2307 gcc_assert (!model->grp_unscalarizable_region);
2308
2309 access = (struct access *) pool_alloc (access_pool);
2310 memset (access, 0, sizeof (struct access));
2311 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2312 model->type))
2313 {
2314 access->grp_no_warning = true;
2315 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2316 new_offset, model, NULL, false);
2317 }
2318
2319 access->base = parent->base;
2320 access->expr = expr;
2321 access->offset = new_offset;
2322 access->size = model->size;
2323 access->type = model->type;
2324 access->grp_write = true;
2325 access->grp_read = false;
2326
2327 child = &parent->first_child;
2328 while (*child && (*child)->offset < new_offset)
2329 child = &(*child)->next_sibling;
2330
2331 access->next_sibling = *child;
2332 *child = access;
2333
2334 return access;
2335 }
2336
2337
2338 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2339 true if any new subaccess was created. Additionally, if RACC is a scalar
2340 access but LACC is not, change the type of the latter, if possible. */
2341
2342 static bool
2343 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2344 {
2345 struct access *rchild;
2346 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2347 bool ret = false;
2348
2349 if (is_gimple_reg_type (lacc->type)
2350 || lacc->grp_unscalarizable_region
2351 || racc->grp_unscalarizable_region)
2352 return false;
2353
2354 if (is_gimple_reg_type (racc->type))
2355 {
2356 if (!lacc->first_child && !racc->first_child)
2357 {
2358 tree t = lacc->base;
2359
2360 lacc->type = racc->type;
2361 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2362 lacc->offset, racc->type))
2363 lacc->expr = t;
2364 else
2365 {
2366 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2367 lacc->base, lacc->offset,
2368 racc, NULL, false);
2369 lacc->grp_no_warning = true;
2370 }
2371 }
2372 return false;
2373 }
2374
2375 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2376 {
2377 struct access *new_acc = NULL;
2378 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2379
2380 if (rchild->grp_unscalarizable_region)
2381 continue;
2382
2383 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2384 &new_acc))
2385 {
2386 if (new_acc)
2387 {
2388 rchild->grp_hint = 1;
2389 new_acc->grp_hint |= new_acc->grp_read;
2390 if (rchild->first_child)
2391 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2392 }
2393 continue;
2394 }
2395
2396 rchild->grp_hint = 1;
2397 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2398 if (new_acc)
2399 {
2400 ret = true;
2401 if (racc->first_child)
2402 propagate_subaccesses_across_link (new_acc, rchild);
2403 }
2404 }
2405
2406 return ret;
2407 }
2408
2409 /* Propagate all subaccesses across assignment links. */
2410
2411 static void
2412 propagate_all_subaccesses (void)
2413 {
2414 while (work_queue_head)
2415 {
2416 struct access *racc = pop_access_from_work_queue ();
2417 struct assign_link *link;
2418
2419 gcc_assert (racc->first_link);
2420
2421 for (link = racc->first_link; link; link = link->next)
2422 {
2423 struct access *lacc = link->lacc;
2424
2425 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2426 continue;
2427 lacc = lacc->group_representative;
2428 if (propagate_subaccesses_across_link (lacc, racc)
2429 && lacc->first_link)
2430 add_access_to_work_queue (lacc);
2431 }
2432 }
2433 }
2434
2435 /* Go through all accesses collected throughout the (intraprocedural) analysis
2436 stage, exclude overlapping ones, identify representatives and build trees
2437 out of them, making decisions about scalarization on the way. Return true
2438 iff there are any to-be-scalarized variables after this stage. */
2439
2440 static bool
2441 analyze_all_variable_accesses (void)
2442 {
2443 int res = 0;
2444 bitmap tmp = BITMAP_ALLOC (NULL);
2445 bitmap_iterator bi;
2446 unsigned i, max_total_scalarization_size;
2447
2448 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2449 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2450
2451 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2452 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2453 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2454 {
2455 tree var = candidate (i);
2456
2457 if (TREE_CODE (var) == VAR_DECL
2458 && type_consists_of_records_p (TREE_TYPE (var)))
2459 {
2460 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2461 <= max_total_scalarization_size)
2462 {
2463 completely_scalarize_var (var);
2464 if (dump_file && (dump_flags & TDF_DETAILS))
2465 {
2466 fprintf (dump_file, "Will attempt to totally scalarize ");
2467 print_generic_expr (dump_file, var, 0);
2468 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2469 }
2470 }
2471 else if (dump_file && (dump_flags & TDF_DETAILS))
2472 {
2473 fprintf (dump_file, "Too big to totally scalarize: ");
2474 print_generic_expr (dump_file, var, 0);
2475 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2476 }
2477 }
2478 }
2479
2480 bitmap_copy (tmp, candidate_bitmap);
2481 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2482 {
2483 tree var = candidate (i);
2484 struct access *access;
2485
2486 access = sort_and_splice_var_accesses (var);
2487 if (!access || !build_access_trees (access))
2488 disqualify_candidate (var,
2489 "No or inhibitingly overlapping accesses.");
2490 }
2491
2492 propagate_all_subaccesses ();
2493
2494 bitmap_copy (tmp, candidate_bitmap);
2495 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2496 {
2497 tree var = candidate (i);
2498 struct access *access = get_first_repr_for_decl (var);
2499
2500 if (analyze_access_trees (access))
2501 {
2502 res++;
2503 if (dump_file && (dump_flags & TDF_DETAILS))
2504 {
2505 fprintf (dump_file, "\nAccess trees for ");
2506 print_generic_expr (dump_file, var, 0);
2507 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2508 dump_access_tree (dump_file, access);
2509 fprintf (dump_file, "\n");
2510 }
2511 }
2512 else
2513 disqualify_candidate (var, "No scalar replacements to be created.");
2514 }
2515
2516 BITMAP_FREE (tmp);
2517
2518 if (res)
2519 {
2520 statistics_counter_event (cfun, "Scalarized aggregates", res);
2521 return true;
2522 }
2523 else
2524 return false;
2525 }
2526
2527 /* Generate statements copying scalar replacements of accesses within a subtree
2528 into or out of AGG. ACCESS, all its children, siblings and their children
2529 are to be processed. AGG is an aggregate type expression (can be a
2530 declaration but does not have to be, it can for example also be a mem_ref or
2531 a series of handled components). TOP_OFFSET is the offset of the processed
2532 subtree which has to be subtracted from offsets of individual accesses to
2533 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2534 replacements in the interval <start_offset, start_offset + chunk_size>,
2535 otherwise copy all. GSI is a statement iterator used to place the new
2536 statements. WRITE should be true when the statements should write from AGG
2537 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2538 statements will be added after the current statement in GSI, they will be
2539 added before the statement otherwise. */
2540
2541 static void
2542 generate_subtree_copies (struct access *access, tree agg,
2543 HOST_WIDE_INT top_offset,
2544 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2545 gimple_stmt_iterator *gsi, bool write,
2546 bool insert_after, location_t loc)
2547 {
2548 do
2549 {
2550 if (chunk_size && access->offset >= start_offset + chunk_size)
2551 return;
2552
2553 if (access->grp_to_be_replaced
2554 && (chunk_size == 0
2555 || access->offset + access->size > start_offset))
2556 {
2557 tree expr, repl = get_access_replacement (access);
2558 gimple stmt;
2559
2560 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2561 access, gsi, insert_after);
2562
2563 if (write)
2564 {
2565 if (access->grp_partial_lhs)
2566 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2567 !insert_after,
2568 insert_after ? GSI_NEW_STMT
2569 : GSI_SAME_STMT);
2570 stmt = gimple_build_assign (repl, expr);
2571 }
2572 else
2573 {
2574 TREE_NO_WARNING (repl) = 1;
2575 if (access->grp_partial_lhs)
2576 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2577 !insert_after,
2578 insert_after ? GSI_NEW_STMT
2579 : GSI_SAME_STMT);
2580 stmt = gimple_build_assign (expr, repl);
2581 }
2582 gimple_set_location (stmt, loc);
2583
2584 if (insert_after)
2585 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2586 else
2587 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2588 update_stmt (stmt);
2589 sra_stats.subtree_copies++;
2590 }
2591 else if (write
2592 && access->grp_to_be_debug_replaced
2593 && (chunk_size == 0
2594 || access->offset + access->size > start_offset))
2595 {
2596 gimple ds;
2597 tree drhs = build_debug_ref_for_model (loc, agg,
2598 access->offset - top_offset,
2599 access);
2600 ds = gimple_build_debug_bind (get_access_replacement (access),
2601 drhs, gsi_stmt (*gsi));
2602 if (insert_after)
2603 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2604 else
2605 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2606 }
2607
2608 if (access->first_child)
2609 generate_subtree_copies (access->first_child, agg, top_offset,
2610 start_offset, chunk_size, gsi,
2611 write, insert_after, loc);
2612
2613 access = access->next_sibling;
2614 }
2615 while (access);
2616 }
2617
2618 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2619 the root of the subtree to be processed. GSI is the statement iterator used
2620 for inserting statements which are added after the current statement if
2621 INSERT_AFTER is true or before it otherwise. */
2622
2623 static void
2624 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2625 bool insert_after, location_t loc)
2626
2627 {
2628 struct access *child;
2629
2630 if (access->grp_to_be_replaced)
2631 {
2632 gimple stmt;
2633
2634 stmt = gimple_build_assign (get_access_replacement (access),
2635 build_zero_cst (access->type));
2636 if (insert_after)
2637 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2638 else
2639 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2640 update_stmt (stmt);
2641 gimple_set_location (stmt, loc);
2642 }
2643 else if (access->grp_to_be_debug_replaced)
2644 {
2645 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2646 build_zero_cst (access->type),
2647 gsi_stmt (*gsi));
2648 if (insert_after)
2649 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2650 else
2651 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2652 }
2653
2654 for (child = access->first_child; child; child = child->next_sibling)
2655 init_subtree_with_zero (child, gsi, insert_after, loc);
2656 }
2657
2658 /* Search for an access representative for the given expression EXPR and
2659 return it or NULL if it cannot be found. */
2660
2661 static struct access *
2662 get_access_for_expr (tree expr)
2663 {
2664 HOST_WIDE_INT offset, size, max_size;
2665 tree base;
2666
2667 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2668 a different size than the size of its argument and we need the latter
2669 one. */
2670 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2671 expr = TREE_OPERAND (expr, 0);
2672
2673 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2674 if (max_size == -1 || !DECL_P (base))
2675 return NULL;
2676
2677 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2678 return NULL;
2679
2680 return get_var_base_offset_size_access (base, offset, max_size);
2681 }
2682
2683 /* Replace the expression EXPR with a scalar replacement if there is one and
2684 generate other statements to do type conversion or subtree copying if
2685 necessary. GSI is used to place newly created statements, WRITE is true if
2686 the expression is being written to (it is on a LHS of a statement or output
2687 in an assembly statement). */
2688
2689 static bool
2690 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2691 {
2692 location_t loc;
2693 struct access *access;
2694 tree type, bfr;
2695
2696 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2697 {
2698 bfr = *expr;
2699 expr = &TREE_OPERAND (*expr, 0);
2700 }
2701 else
2702 bfr = NULL_TREE;
2703
2704 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2705 expr = &TREE_OPERAND (*expr, 0);
2706 access = get_access_for_expr (*expr);
2707 if (!access)
2708 return false;
2709 type = TREE_TYPE (*expr);
2710
2711 loc = gimple_location (gsi_stmt (*gsi));
2712 if (access->grp_to_be_replaced)
2713 {
2714 tree repl = get_access_replacement (access);
2715 /* If we replace a non-register typed access simply use the original
2716 access expression to extract the scalar component afterwards.
2717 This happens if scalarizing a function return value or parameter
2718 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2719 gcc.c-torture/compile/20011217-1.c.
2720
2721 We also want to use this when accessing a complex or vector which can
2722 be accessed as a different type too, potentially creating a need for
2723 type conversion (see PR42196) and when scalarized unions are involved
2724 in assembler statements (see PR42398). */
2725 if (!useless_type_conversion_p (type, access->type))
2726 {
2727 tree ref;
2728
2729 ref = build_ref_for_model (loc, access->base, access->offset, access,
2730 NULL, false);
2731
2732 if (write)
2733 {
2734 gimple stmt;
2735
2736 if (access->grp_partial_lhs)
2737 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2738 false, GSI_NEW_STMT);
2739 stmt = gimple_build_assign (repl, ref);
2740 gimple_set_location (stmt, loc);
2741 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2742 }
2743 else
2744 {
2745 gimple stmt;
2746
2747 if (access->grp_partial_lhs)
2748 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2749 true, GSI_SAME_STMT);
2750 stmt = gimple_build_assign (ref, repl);
2751 gimple_set_location (stmt, loc);
2752 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2753 }
2754 }
2755 else
2756 *expr = repl;
2757 sra_stats.exprs++;
2758 }
2759 else if (write && access->grp_to_be_debug_replaced)
2760 {
2761 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2762 NULL_TREE,
2763 gsi_stmt (*gsi));
2764 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2765 }
2766
2767 if (access->first_child)
2768 {
2769 HOST_WIDE_INT start_offset, chunk_size;
2770 if (bfr
2771 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2772 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2773 {
2774 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2775 start_offset = access->offset
2776 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2777 }
2778 else
2779 start_offset = chunk_size = 0;
2780
2781 generate_subtree_copies (access->first_child, access->base, 0,
2782 start_offset, chunk_size, gsi, write, write,
2783 loc);
2784 }
2785 return true;
2786 }
2787
2788 /* Where scalar replacements of the RHS have been written to when a replacement
2789 of a LHS of an assigments cannot be direclty loaded from a replacement of
2790 the RHS. */
2791 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2792 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2793 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2794
2795 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2796 base aggregate if there are unscalarized data or directly to LHS of the
2797 statement that is pointed to by GSI otherwise. */
2798
2799 static enum unscalarized_data_handling
2800 handle_unscalarized_data_in_subtree (struct access *top_racc,
2801 gimple_stmt_iterator *gsi)
2802 {
2803 if (top_racc->grp_unscalarized_data)
2804 {
2805 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2806 gsi, false, false,
2807 gimple_location (gsi_stmt (*gsi)));
2808 return SRA_UDH_RIGHT;
2809 }
2810 else
2811 {
2812 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2813 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2814 0, 0, gsi, false, false,
2815 gimple_location (gsi_stmt (*gsi)));
2816 return SRA_UDH_LEFT;
2817 }
2818 }
2819
2820
2821 /* Try to generate statements to load all sub-replacements in an access subtree
2822 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2823 If that is not possible, refresh the TOP_RACC base aggregate and load the
2824 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2825 copied. NEW_GSI is stmt iterator used for statement insertions after the
2826 original assignment, OLD_GSI is used to insert statements before the
2827 assignment. *REFRESHED keeps the information whether we have needed to
2828 refresh replacements of the LHS and from which side of the assignments this
2829 takes place. */
2830
2831 static void
2832 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2833 HOST_WIDE_INT left_offset,
2834 gimple_stmt_iterator *old_gsi,
2835 gimple_stmt_iterator *new_gsi,
2836 enum unscalarized_data_handling *refreshed)
2837 {
2838 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2839 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2840 {
2841 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2842
2843 if (lacc->grp_to_be_replaced)
2844 {
2845 struct access *racc;
2846 gimple stmt;
2847 tree rhs;
2848
2849 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2850 if (racc && racc->grp_to_be_replaced)
2851 {
2852 rhs = get_access_replacement (racc);
2853 if (!useless_type_conversion_p (lacc->type, racc->type))
2854 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2855
2856 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2857 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2858 true, GSI_SAME_STMT);
2859 }
2860 else
2861 {
2862 /* No suitable access on the right hand side, need to load from
2863 the aggregate. See if we have to update it first... */
2864 if (*refreshed == SRA_UDH_NONE)
2865 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2866 old_gsi);
2867
2868 if (*refreshed == SRA_UDH_LEFT)
2869 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2870 new_gsi, true);
2871 else
2872 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2873 new_gsi, true);
2874 if (lacc->grp_partial_lhs)
2875 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2876 false, GSI_NEW_STMT);
2877 }
2878
2879 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2880 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2881 gimple_set_location (stmt, loc);
2882 update_stmt (stmt);
2883 sra_stats.subreplacements++;
2884 }
2885 else
2886 {
2887 if (*refreshed == SRA_UDH_NONE
2888 && lacc->grp_read && !lacc->grp_covered)
2889 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2890 old_gsi);
2891 if (lacc && lacc->grp_to_be_debug_replaced)
2892 {
2893 gimple ds;
2894 tree drhs;
2895 struct access *racc = find_access_in_subtree (top_racc, offset,
2896 lacc->size);
2897
2898 if (racc && racc->grp_to_be_replaced)
2899 {
2900 if (racc->grp_write)
2901 drhs = get_access_replacement (racc);
2902 else
2903 drhs = NULL;
2904 }
2905 else if (*refreshed == SRA_UDH_LEFT)
2906 drhs = build_debug_ref_for_model (loc, lacc->base, lacc->offset,
2907 lacc);
2908 else if (*refreshed == SRA_UDH_RIGHT)
2909 drhs = build_debug_ref_for_model (loc, top_racc->base, offset,
2910 lacc);
2911 else
2912 drhs = NULL_TREE;
2913 ds = gimple_build_debug_bind (get_access_replacement (lacc),
2914 drhs, gsi_stmt (*old_gsi));
2915 gsi_insert_after (new_gsi, ds, GSI_NEW_STMT);
2916 }
2917 }
2918
2919 if (lacc->first_child)
2920 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2921 old_gsi, new_gsi, refreshed);
2922 }
2923 }
2924
2925 /* Result code for SRA assignment modification. */
2926 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2927 SRA_AM_MODIFIED, /* stmt changed but not
2928 removed */
2929 SRA_AM_REMOVED }; /* stmt eliminated */
2930
2931 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2932 to the assignment and GSI is the statement iterator pointing at it. Returns
2933 the same values as sra_modify_assign. */
2934
2935 static enum assignment_mod_result
2936 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2937 {
2938 tree lhs = gimple_assign_lhs (*stmt);
2939 struct access *acc;
2940 location_t loc;
2941
2942 acc = get_access_for_expr (lhs);
2943 if (!acc)
2944 return SRA_AM_NONE;
2945
2946 if (gimple_clobber_p (*stmt))
2947 {
2948 /* Remove clobbers of fully scalarized variables, otherwise
2949 do nothing. */
2950 if (acc->grp_covered)
2951 {
2952 unlink_stmt_vdef (*stmt);
2953 gsi_remove (gsi, true);
2954 release_defs (*stmt);
2955 return SRA_AM_REMOVED;
2956 }
2957 else
2958 return SRA_AM_NONE;
2959 }
2960
2961 loc = gimple_location (*stmt);
2962 if (vec_safe_length (CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2963 {
2964 /* I have never seen this code path trigger but if it can happen the
2965 following should handle it gracefully. */
2966 if (access_has_children_p (acc))
2967 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2968 true, true, loc);
2969 return SRA_AM_MODIFIED;
2970 }
2971
2972 if (acc->grp_covered)
2973 {
2974 init_subtree_with_zero (acc, gsi, false, loc);
2975 unlink_stmt_vdef (*stmt);
2976 gsi_remove (gsi, true);
2977 release_defs (*stmt);
2978 return SRA_AM_REMOVED;
2979 }
2980 else
2981 {
2982 init_subtree_with_zero (acc, gsi, true, loc);
2983 return SRA_AM_MODIFIED;
2984 }
2985 }
2986
2987 /* Create and return a new suitable default definition SSA_NAME for RACC which
2988 is an access describing an uninitialized part of an aggregate that is being
2989 loaded. */
2990
2991 static tree
2992 get_repl_default_def_ssa_name (struct access *racc)
2993 {
2994 gcc_checking_assert (!racc->grp_to_be_replaced
2995 && !racc->grp_to_be_debug_replaced);
2996 if (!racc->replacement_decl)
2997 racc->replacement_decl = create_access_replacement (racc);
2998 return get_or_create_ssa_default_def (cfun, racc->replacement_decl);
2999 }
3000
3001 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3002 bit-field field declaration somewhere in it. */
3003
3004 static inline bool
3005 contains_vce_or_bfcref_p (const_tree ref)
3006 {
3007 while (handled_component_p (ref))
3008 {
3009 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3010 || (TREE_CODE (ref) == COMPONENT_REF
3011 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3012 return true;
3013 ref = TREE_OPERAND (ref, 0);
3014 }
3015
3016 return false;
3017 }
3018
3019 /* Examine both sides of the assignment statement pointed to by STMT, replace
3020 them with a scalare replacement if there is one and generate copying of
3021 replacements if scalarized aggregates have been used in the assignment. GSI
3022 is used to hold generated statements for type conversions and subtree
3023 copying. */
3024
3025 static enum assignment_mod_result
3026 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3027 {
3028 struct access *lacc, *racc;
3029 tree lhs, rhs;
3030 bool modify_this_stmt = false;
3031 bool force_gimple_rhs = false;
3032 location_t loc;
3033 gimple_stmt_iterator orig_gsi = *gsi;
3034
3035 if (!gimple_assign_single_p (*stmt))
3036 return SRA_AM_NONE;
3037 lhs = gimple_assign_lhs (*stmt);
3038 rhs = gimple_assign_rhs1 (*stmt);
3039
3040 if (TREE_CODE (rhs) == CONSTRUCTOR)
3041 return sra_modify_constructor_assign (stmt, gsi);
3042
3043 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3044 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3045 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3046 {
3047 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3048 gsi, false);
3049 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3050 gsi, true);
3051 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3052 }
3053
3054 lacc = get_access_for_expr (lhs);
3055 racc = get_access_for_expr (rhs);
3056 if (!lacc && !racc)
3057 return SRA_AM_NONE;
3058
3059 loc = gimple_location (*stmt);
3060 if (lacc && lacc->grp_to_be_replaced)
3061 {
3062 lhs = get_access_replacement (lacc);
3063 gimple_assign_set_lhs (*stmt, lhs);
3064 modify_this_stmt = true;
3065 if (lacc->grp_partial_lhs)
3066 force_gimple_rhs = true;
3067 sra_stats.exprs++;
3068 }
3069
3070 if (racc && racc->grp_to_be_replaced)
3071 {
3072 rhs = get_access_replacement (racc);
3073 modify_this_stmt = true;
3074 if (racc->grp_partial_lhs)
3075 force_gimple_rhs = true;
3076 sra_stats.exprs++;
3077 }
3078 else if (racc
3079 && !racc->grp_unscalarized_data
3080 && TREE_CODE (lhs) == SSA_NAME
3081 && !access_has_replacements_p (racc))
3082 {
3083 rhs = get_repl_default_def_ssa_name (racc);
3084 modify_this_stmt = true;
3085 sra_stats.exprs++;
3086 }
3087
3088 if (modify_this_stmt)
3089 {
3090 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3091 {
3092 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3093 ??? This should move to fold_stmt which we simply should
3094 call after building a VIEW_CONVERT_EXPR here. */
3095 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3096 && !contains_bitfld_component_ref_p (lhs))
3097 {
3098 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3099 gimple_assign_set_lhs (*stmt, lhs);
3100 }
3101 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3102 && !contains_vce_or_bfcref_p (rhs))
3103 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3104
3105 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3106 {
3107 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3108 rhs);
3109 if (is_gimple_reg_type (TREE_TYPE (lhs))
3110 && TREE_CODE (lhs) != SSA_NAME)
3111 force_gimple_rhs = true;
3112 }
3113 }
3114 }
3115
3116 if (lacc && lacc->grp_to_be_debug_replaced)
3117 {
3118 tree dlhs = get_access_replacement (lacc);
3119 tree drhs = unshare_expr (rhs);
3120 if (!useless_type_conversion_p (TREE_TYPE (dlhs), TREE_TYPE (drhs)))
3121 {
3122 if (AGGREGATE_TYPE_P (TREE_TYPE (drhs))
3123 && !contains_vce_or_bfcref_p (drhs))
3124 drhs = build_debug_ref_for_model (loc, drhs, 0, lacc);
3125 if (drhs
3126 && !useless_type_conversion_p (TREE_TYPE (dlhs),
3127 TREE_TYPE (drhs)))
3128 drhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR,
3129 TREE_TYPE (dlhs), drhs);
3130 }
3131 gimple ds = gimple_build_debug_bind (dlhs, drhs, *stmt);
3132 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3133 }
3134
3135 /* From this point on, the function deals with assignments in between
3136 aggregates when at least one has scalar reductions of some of its
3137 components. There are three possible scenarios: Both the LHS and RHS have
3138 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3139
3140 In the first case, we would like to load the LHS components from RHS
3141 components whenever possible. If that is not possible, we would like to
3142 read it directly from the RHS (after updating it by storing in it its own
3143 components). If there are some necessary unscalarized data in the LHS,
3144 those will be loaded by the original assignment too. If neither of these
3145 cases happen, the original statement can be removed. Most of this is done
3146 by load_assign_lhs_subreplacements.
3147
3148 In the second case, we would like to store all RHS scalarized components
3149 directly into LHS and if they cover the aggregate completely, remove the
3150 statement too. In the third case, we want the LHS components to be loaded
3151 directly from the RHS (DSE will remove the original statement if it
3152 becomes redundant).
3153
3154 This is a bit complex but manageable when types match and when unions do
3155 not cause confusion in a way that we cannot really load a component of LHS
3156 from the RHS or vice versa (the access representing this level can have
3157 subaccesses that are accessible only through a different union field at a
3158 higher level - different from the one used in the examined expression).
3159 Unions are fun.
3160
3161 Therefore, I specially handle a fourth case, happening when there is a
3162 specific type cast or it is impossible to locate a scalarized subaccess on
3163 the other side of the expression. If that happens, I simply "refresh" the
3164 RHS by storing in it is scalarized components leave the original statement
3165 there to do the copying and then load the scalar replacements of the LHS.
3166 This is what the first branch does. */
3167
3168 if (modify_this_stmt
3169 || gimple_has_volatile_ops (*stmt)
3170 || contains_vce_or_bfcref_p (rhs)
3171 || contains_vce_or_bfcref_p (lhs))
3172 {
3173 if (access_has_children_p (racc))
3174 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3175 gsi, false, false, loc);
3176 if (access_has_children_p (lacc))
3177 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3178 gsi, true, true, loc);
3179 sra_stats.separate_lhs_rhs_handling++;
3180
3181 /* This gimplification must be done after generate_subtree_copies,
3182 lest we insert the subtree copies in the middle of the gimplified
3183 sequence. */
3184 if (force_gimple_rhs)
3185 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3186 true, GSI_SAME_STMT);
3187 if (gimple_assign_rhs1 (*stmt) != rhs)
3188 {
3189 modify_this_stmt = true;
3190 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3191 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3192 }
3193
3194 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3195 }
3196 else
3197 {
3198 if (access_has_children_p (lacc)
3199 && access_has_children_p (racc)
3200 /* When an access represents an unscalarizable region, it usually
3201 represents accesses with variable offset and thus must not be used
3202 to generate new memory accesses. */
3203 && !lacc->grp_unscalarizable_region
3204 && !racc->grp_unscalarizable_region)
3205 {
3206 gimple_stmt_iterator orig_gsi = *gsi;
3207 enum unscalarized_data_handling refreshed;
3208
3209 if (lacc->grp_read && !lacc->grp_covered)
3210 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3211 else
3212 refreshed = SRA_UDH_NONE;
3213
3214 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3215 &orig_gsi, gsi, &refreshed);
3216 if (refreshed != SRA_UDH_RIGHT)
3217 {
3218 gsi_next (gsi);
3219 unlink_stmt_vdef (*stmt);
3220 gsi_remove (&orig_gsi, true);
3221 release_defs (*stmt);
3222 sra_stats.deleted++;
3223 return SRA_AM_REMOVED;
3224 }
3225 }
3226 else
3227 {
3228 if (access_has_children_p (racc)
3229 && !racc->grp_unscalarized_data)
3230 {
3231 if (dump_file)
3232 {
3233 fprintf (dump_file, "Removing load: ");
3234 print_gimple_stmt (dump_file, *stmt, 0, 0);
3235 }
3236 generate_subtree_copies (racc->first_child, lhs,
3237 racc->offset, 0, 0, gsi,
3238 false, false, loc);
3239 gcc_assert (*stmt == gsi_stmt (*gsi));
3240 unlink_stmt_vdef (*stmt);
3241 gsi_remove (gsi, true);
3242 release_defs (*stmt);
3243 sra_stats.deleted++;
3244 return SRA_AM_REMOVED;
3245 }
3246 /* Restore the aggregate RHS from its components so the
3247 prevailing aggregate copy does the right thing. */
3248 if (access_has_children_p (racc))
3249 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3250 gsi, false, false, loc);
3251 /* Re-load the components of the aggregate copy destination.
3252 But use the RHS aggregate to load from to expose more
3253 optimization opportunities. */
3254 if (access_has_children_p (lacc))
3255 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3256 0, 0, gsi, true, true, loc);
3257 }
3258
3259 return SRA_AM_NONE;
3260 }
3261 }
3262
3263 /* Traverse the function body and all modifications as decided in
3264 analyze_all_variable_accesses. Return true iff the CFG has been
3265 changed. */
3266
3267 static bool
3268 sra_modify_function_body (void)
3269 {
3270 bool cfg_changed = false;
3271 basic_block bb;
3272
3273 FOR_EACH_BB (bb)
3274 {
3275 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3276 while (!gsi_end_p (gsi))
3277 {
3278 gimple stmt = gsi_stmt (gsi);
3279 enum assignment_mod_result assign_result;
3280 bool modified = false, deleted = false;
3281 tree *t;
3282 unsigned i;
3283
3284 switch (gimple_code (stmt))
3285 {
3286 case GIMPLE_RETURN:
3287 t = gimple_return_retval_ptr (stmt);
3288 if (*t != NULL_TREE)
3289 modified |= sra_modify_expr (t, &gsi, false);
3290 break;
3291
3292 case GIMPLE_ASSIGN:
3293 assign_result = sra_modify_assign (&stmt, &gsi);
3294 modified |= assign_result == SRA_AM_MODIFIED;
3295 deleted = assign_result == SRA_AM_REMOVED;
3296 break;
3297
3298 case GIMPLE_CALL:
3299 /* Operands must be processed before the lhs. */
3300 for (i = 0; i < gimple_call_num_args (stmt); i++)
3301 {
3302 t = gimple_call_arg_ptr (stmt, i);
3303 modified |= sra_modify_expr (t, &gsi, false);
3304 }
3305
3306 if (gimple_call_lhs (stmt))
3307 {
3308 t = gimple_call_lhs_ptr (stmt);
3309 modified |= sra_modify_expr (t, &gsi, true);
3310 }
3311 break;
3312
3313 case GIMPLE_ASM:
3314 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3315 {
3316 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3317 modified |= sra_modify_expr (t, &gsi, false);
3318 }
3319 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3320 {
3321 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3322 modified |= sra_modify_expr (t, &gsi, true);
3323 }
3324 break;
3325
3326 default:
3327 break;
3328 }
3329
3330 if (modified)
3331 {
3332 update_stmt (stmt);
3333 if (maybe_clean_eh_stmt (stmt)
3334 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3335 cfg_changed = true;
3336 }
3337 if (!deleted)
3338 gsi_next (&gsi);
3339 }
3340 }
3341
3342 return cfg_changed;
3343 }
3344
3345 /* Generate statements initializing scalar replacements of parts of function
3346 parameters. */
3347
3348 static void
3349 initialize_parameter_reductions (void)
3350 {
3351 gimple_stmt_iterator gsi;
3352 gimple_seq seq = NULL;
3353 tree parm;
3354
3355 gsi = gsi_start (seq);
3356 for (parm = DECL_ARGUMENTS (current_function_decl);
3357 parm;
3358 parm = DECL_CHAIN (parm))
3359 {
3360 vec<access_p> *access_vec;
3361 struct access *access;
3362
3363 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3364 continue;
3365 access_vec = get_base_access_vector (parm);
3366 if (!access_vec)
3367 continue;
3368
3369 for (access = (*access_vec)[0];
3370 access;
3371 access = access->next_grp)
3372 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3373 EXPR_LOCATION (parm));
3374 }
3375
3376 seq = gsi_seq (gsi);
3377 if (seq)
3378 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3379 }
3380
3381 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3382 it reveals there are components of some aggregates to be scalarized, it runs
3383 the required transformations. */
3384 static unsigned int
3385 perform_intra_sra (void)
3386 {
3387 int ret = 0;
3388 sra_initialize ();
3389
3390 if (!find_var_candidates ())
3391 goto out;
3392
3393 if (!scan_function ())
3394 goto out;
3395
3396 if (!analyze_all_variable_accesses ())
3397 goto out;
3398
3399 if (sra_modify_function_body ())
3400 ret = TODO_update_ssa | TODO_cleanup_cfg;
3401 else
3402 ret = TODO_update_ssa;
3403 initialize_parameter_reductions ();
3404
3405 statistics_counter_event (cfun, "Scalar replacements created",
3406 sra_stats.replacements);
3407 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3408 statistics_counter_event (cfun, "Subtree copy stmts",
3409 sra_stats.subtree_copies);
3410 statistics_counter_event (cfun, "Subreplacement stmts",
3411 sra_stats.subreplacements);
3412 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3413 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3414 sra_stats.separate_lhs_rhs_handling);
3415
3416 out:
3417 sra_deinitialize ();
3418 return ret;
3419 }
3420
3421 /* Perform early intraprocedural SRA. */
3422 static unsigned int
3423 early_intra_sra (void)
3424 {
3425 sra_mode = SRA_MODE_EARLY_INTRA;
3426 return perform_intra_sra ();
3427 }
3428
3429 /* Perform "late" intraprocedural SRA. */
3430 static unsigned int
3431 late_intra_sra (void)
3432 {
3433 sra_mode = SRA_MODE_INTRA;
3434 return perform_intra_sra ();
3435 }
3436
3437
3438 static bool
3439 gate_intra_sra (void)
3440 {
3441 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3442 }
3443
3444
3445 namespace {
3446
3447 const pass_data pass_data_sra_early =
3448 {
3449 GIMPLE_PASS, /* type */
3450 "esra", /* name */
3451 OPTGROUP_NONE, /* optinfo_flags */
3452 true, /* has_gate */
3453 true, /* has_execute */
3454 TV_TREE_SRA, /* tv_id */
3455 ( PROP_cfg | PROP_ssa ), /* properties_required */
3456 0, /* properties_provided */
3457 0, /* properties_destroyed */
3458 0, /* todo_flags_start */
3459 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3460 };
3461
3462 class pass_sra_early : public gimple_opt_pass
3463 {
3464 public:
3465 pass_sra_early(gcc::context *ctxt)
3466 : gimple_opt_pass(pass_data_sra_early, ctxt)
3467 {}
3468
3469 /* opt_pass methods: */
3470 bool gate () { return gate_intra_sra (); }
3471 unsigned int execute () { return early_intra_sra (); }
3472
3473 }; // class pass_sra_early
3474
3475 } // anon namespace
3476
3477 gimple_opt_pass *
3478 make_pass_sra_early (gcc::context *ctxt)
3479 {
3480 return new pass_sra_early (ctxt);
3481 }
3482
3483 namespace {
3484
3485 const pass_data pass_data_sra =
3486 {
3487 GIMPLE_PASS, /* type */
3488 "sra", /* name */
3489 OPTGROUP_NONE, /* optinfo_flags */
3490 true, /* has_gate */
3491 true, /* has_execute */
3492 TV_TREE_SRA, /* tv_id */
3493 ( PROP_cfg | PROP_ssa ), /* properties_required */
3494 0, /* properties_provided */
3495 0, /* properties_destroyed */
3496 TODO_update_address_taken, /* todo_flags_start */
3497 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3498 };
3499
3500 class pass_sra : public gimple_opt_pass
3501 {
3502 public:
3503 pass_sra(gcc::context *ctxt)
3504 : gimple_opt_pass(pass_data_sra, ctxt)
3505 {}
3506
3507 /* opt_pass methods: */
3508 bool gate () { return gate_intra_sra (); }
3509 unsigned int execute () { return late_intra_sra (); }
3510
3511 }; // class pass_sra
3512
3513 } // anon namespace
3514
3515 gimple_opt_pass *
3516 make_pass_sra (gcc::context *ctxt)
3517 {
3518 return new pass_sra (ctxt);
3519 }
3520
3521
3522 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3523 parameter. */
3524
3525 static bool
3526 is_unused_scalar_param (tree parm)
3527 {
3528 tree name;
3529 return (is_gimple_reg (parm)
3530 && (!(name = ssa_default_def (cfun, parm))
3531 || has_zero_uses (name)));
3532 }
3533
3534 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3535 examine whether there are any direct or otherwise infeasible ones. If so,
3536 return true, otherwise return false. PARM must be a gimple register with a
3537 non-NULL default definition. */
3538
3539 static bool
3540 ptr_parm_has_direct_uses (tree parm)
3541 {
3542 imm_use_iterator ui;
3543 gimple stmt;
3544 tree name = ssa_default_def (cfun, parm);
3545 bool ret = false;
3546
3547 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3548 {
3549 int uses_ok = 0;
3550 use_operand_p use_p;
3551
3552 if (is_gimple_debug (stmt))
3553 continue;
3554
3555 /* Valid uses include dereferences on the lhs and the rhs. */
3556 if (gimple_has_lhs (stmt))
3557 {
3558 tree lhs = gimple_get_lhs (stmt);
3559 while (handled_component_p (lhs))
3560 lhs = TREE_OPERAND (lhs, 0);
3561 if (TREE_CODE (lhs) == MEM_REF
3562 && TREE_OPERAND (lhs, 0) == name
3563 && integer_zerop (TREE_OPERAND (lhs, 1))
3564 && types_compatible_p (TREE_TYPE (lhs),
3565 TREE_TYPE (TREE_TYPE (name)))
3566 && !TREE_THIS_VOLATILE (lhs))
3567 uses_ok++;
3568 }
3569 if (gimple_assign_single_p (stmt))
3570 {
3571 tree rhs = gimple_assign_rhs1 (stmt);
3572 while (handled_component_p (rhs))
3573 rhs = TREE_OPERAND (rhs, 0);
3574 if (TREE_CODE (rhs) == MEM_REF
3575 && TREE_OPERAND (rhs, 0) == name
3576 && integer_zerop (TREE_OPERAND (rhs, 1))
3577 && types_compatible_p (TREE_TYPE (rhs),
3578 TREE_TYPE (TREE_TYPE (name)))
3579 && !TREE_THIS_VOLATILE (rhs))
3580 uses_ok++;
3581 }
3582 else if (is_gimple_call (stmt))
3583 {
3584 unsigned i;
3585 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3586 {
3587 tree arg = gimple_call_arg (stmt, i);
3588 while (handled_component_p (arg))
3589 arg = TREE_OPERAND (arg, 0);
3590 if (TREE_CODE (arg) == MEM_REF
3591 && TREE_OPERAND (arg, 0) == name
3592 && integer_zerop (TREE_OPERAND (arg, 1))
3593 && types_compatible_p (TREE_TYPE (arg),
3594 TREE_TYPE (TREE_TYPE (name)))
3595 && !TREE_THIS_VOLATILE (arg))
3596 uses_ok++;
3597 }
3598 }
3599
3600 /* If the number of valid uses does not match the number of
3601 uses in this stmt there is an unhandled use. */
3602 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3603 --uses_ok;
3604
3605 if (uses_ok != 0)
3606 ret = true;
3607
3608 if (ret)
3609 BREAK_FROM_IMM_USE_STMT (ui);
3610 }
3611
3612 return ret;
3613 }
3614
3615 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3616 them in candidate_bitmap. Note that these do not necessarily include
3617 parameter which are unused and thus can be removed. Return true iff any
3618 such candidate has been found. */
3619
3620 static bool
3621 find_param_candidates (void)
3622 {
3623 tree parm;
3624 int count = 0;
3625 bool ret = false;
3626 const char *msg;
3627
3628 for (parm = DECL_ARGUMENTS (current_function_decl);
3629 parm;
3630 parm = DECL_CHAIN (parm))
3631 {
3632 tree type = TREE_TYPE (parm);
3633 tree_node **slot;
3634
3635 count++;
3636
3637 if (TREE_THIS_VOLATILE (parm)
3638 || TREE_ADDRESSABLE (parm)
3639 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3640 continue;
3641
3642 if (is_unused_scalar_param (parm))
3643 {
3644 ret = true;
3645 continue;
3646 }
3647
3648 if (POINTER_TYPE_P (type))
3649 {
3650 type = TREE_TYPE (type);
3651
3652 if (TREE_CODE (type) == FUNCTION_TYPE
3653 || TYPE_VOLATILE (type)
3654 || (TREE_CODE (type) == ARRAY_TYPE
3655 && TYPE_NONALIASED_COMPONENT (type))
3656 || !is_gimple_reg (parm)
3657 || is_va_list_type (type)
3658 || ptr_parm_has_direct_uses (parm))
3659 continue;
3660 }
3661 else if (!AGGREGATE_TYPE_P (type))
3662 continue;
3663
3664 if (!COMPLETE_TYPE_P (type)
3665 || !host_integerp (TYPE_SIZE (type), 1)
3666 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3667 || (AGGREGATE_TYPE_P (type)
3668 && type_internals_preclude_sra_p (type, &msg)))
3669 continue;
3670
3671 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3672 slot = candidates.find_slot_with_hash (parm, DECL_UID (parm), INSERT);
3673 *slot = parm;
3674
3675 ret = true;
3676 if (dump_file && (dump_flags & TDF_DETAILS))
3677 {
3678 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3679 print_generic_expr (dump_file, parm, 0);
3680 fprintf (dump_file, "\n");
3681 }
3682 }
3683
3684 func_param_count = count;
3685 return ret;
3686 }
3687
3688 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3689 maybe_modified. */
3690
3691 static bool
3692 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3693 void *data)
3694 {
3695 struct access *repr = (struct access *) data;
3696
3697 repr->grp_maybe_modified = 1;
3698 return true;
3699 }
3700
3701 /* Analyze what representatives (in linked lists accessible from
3702 REPRESENTATIVES) can be modified by side effects of statements in the
3703 current function. */
3704
3705 static void
3706 analyze_modified_params (vec<access_p> representatives)
3707 {
3708 int i;
3709
3710 for (i = 0; i < func_param_count; i++)
3711 {
3712 struct access *repr;
3713
3714 for (repr = representatives[i];
3715 repr;
3716 repr = repr->next_grp)
3717 {
3718 struct access *access;
3719 bitmap visited;
3720 ao_ref ar;
3721
3722 if (no_accesses_p (repr))
3723 continue;
3724 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3725 || repr->grp_maybe_modified)
3726 continue;
3727
3728 ao_ref_init (&ar, repr->expr);
3729 visited = BITMAP_ALLOC (NULL);
3730 for (access = repr; access; access = access->next_sibling)
3731 {
3732 /* All accesses are read ones, otherwise grp_maybe_modified would
3733 be trivially set. */
3734 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3735 mark_maybe_modified, repr, &visited);
3736 if (repr->grp_maybe_modified)
3737 break;
3738 }
3739 BITMAP_FREE (visited);
3740 }
3741 }
3742 }
3743
3744 /* Propagate distances in bb_dereferences in the opposite direction than the
3745 control flow edges, in each step storing the maximum of the current value
3746 and the minimum of all successors. These steps are repeated until the table
3747 stabilizes. Note that BBs which might terminate the functions (according to
3748 final_bbs bitmap) never updated in this way. */
3749
3750 static void
3751 propagate_dereference_distances (void)
3752 {
3753 vec<basic_block> queue;
3754 basic_block bb;
3755
3756 queue.create (last_basic_block_for_function (cfun));
3757 queue.quick_push (ENTRY_BLOCK_PTR);
3758 FOR_EACH_BB (bb)
3759 {
3760 queue.quick_push (bb);
3761 bb->aux = bb;
3762 }
3763
3764 while (!queue.is_empty ())
3765 {
3766 edge_iterator ei;
3767 edge e;
3768 bool change = false;
3769 int i;
3770
3771 bb = queue.pop ();
3772 bb->aux = NULL;
3773
3774 if (bitmap_bit_p (final_bbs, bb->index))
3775 continue;
3776
3777 for (i = 0; i < func_param_count; i++)
3778 {
3779 int idx = bb->index * func_param_count + i;
3780 bool first = true;
3781 HOST_WIDE_INT inh = 0;
3782
3783 FOR_EACH_EDGE (e, ei, bb->succs)
3784 {
3785 int succ_idx = e->dest->index * func_param_count + i;
3786
3787 if (e->src == EXIT_BLOCK_PTR)
3788 continue;
3789
3790 if (first)
3791 {
3792 first = false;
3793 inh = bb_dereferences [succ_idx];
3794 }
3795 else if (bb_dereferences [succ_idx] < inh)
3796 inh = bb_dereferences [succ_idx];
3797 }
3798
3799 if (!first && bb_dereferences[idx] < inh)
3800 {
3801 bb_dereferences[idx] = inh;
3802 change = true;
3803 }
3804 }
3805
3806 if (change && !bitmap_bit_p (final_bbs, bb->index))
3807 FOR_EACH_EDGE (e, ei, bb->preds)
3808 {
3809 if (e->src->aux)
3810 continue;
3811
3812 e->src->aux = e->src;
3813 queue.quick_push (e->src);
3814 }
3815 }
3816
3817 queue.release ();
3818 }
3819
3820 /* Dump a dereferences TABLE with heading STR to file F. */
3821
3822 static void
3823 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3824 {
3825 basic_block bb;
3826
3827 fprintf (dump_file, str);
3828 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3829 {
3830 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3831 if (bb != EXIT_BLOCK_PTR)
3832 {
3833 int i;
3834 for (i = 0; i < func_param_count; i++)
3835 {
3836 int idx = bb->index * func_param_count + i;
3837 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3838 }
3839 }
3840 fprintf (f, "\n");
3841 }
3842 fprintf (dump_file, "\n");
3843 }
3844
3845 /* Determine what (parts of) parameters passed by reference that are not
3846 assigned to are not certainly dereferenced in this function and thus the
3847 dereferencing cannot be safely moved to the caller without potentially
3848 introducing a segfault. Mark such REPRESENTATIVES as
3849 grp_not_necessarilly_dereferenced.
3850
3851 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3852 part is calculated rather than simple booleans are calculated for each
3853 pointer parameter to handle cases when only a fraction of the whole
3854 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3855 an example).
3856
3857 The maximum dereference distances for each pointer parameter and BB are
3858 already stored in bb_dereference. This routine simply propagates these
3859 values upwards by propagate_dereference_distances and then compares the
3860 distances of individual parameters in the ENTRY BB to the equivalent
3861 distances of each representative of a (fraction of a) parameter. */
3862
3863 static void
3864 analyze_caller_dereference_legality (vec<access_p> representatives)
3865 {
3866 int i;
3867
3868 if (dump_file && (dump_flags & TDF_DETAILS))
3869 dump_dereferences_table (dump_file,
3870 "Dereference table before propagation:\n",
3871 bb_dereferences);
3872
3873 propagate_dereference_distances ();
3874
3875 if (dump_file && (dump_flags & TDF_DETAILS))
3876 dump_dereferences_table (dump_file,
3877 "Dereference table after propagation:\n",
3878 bb_dereferences);
3879
3880 for (i = 0; i < func_param_count; i++)
3881 {
3882 struct access *repr = representatives[i];
3883 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3884
3885 if (!repr || no_accesses_p (repr))
3886 continue;
3887
3888 do
3889 {
3890 if ((repr->offset + repr->size) > bb_dereferences[idx])
3891 repr->grp_not_necessarilly_dereferenced = 1;
3892 repr = repr->next_grp;
3893 }
3894 while (repr);
3895 }
3896 }
3897
3898 /* Return the representative access for the parameter declaration PARM if it is
3899 a scalar passed by reference which is not written to and the pointer value
3900 is not used directly. Thus, if it is legal to dereference it in the caller
3901 and we can rule out modifications through aliases, such parameter should be
3902 turned into one passed by value. Return NULL otherwise. */
3903
3904 static struct access *
3905 unmodified_by_ref_scalar_representative (tree parm)
3906 {
3907 int i, access_count;
3908 struct access *repr;
3909 vec<access_p> *access_vec;
3910
3911 access_vec = get_base_access_vector (parm);
3912 gcc_assert (access_vec);
3913 repr = (*access_vec)[0];
3914 if (repr->write)
3915 return NULL;
3916 repr->group_representative = repr;
3917
3918 access_count = access_vec->length ();
3919 for (i = 1; i < access_count; i++)
3920 {
3921 struct access *access = (*access_vec)[i];
3922 if (access->write)
3923 return NULL;
3924 access->group_representative = repr;
3925 access->next_sibling = repr->next_sibling;
3926 repr->next_sibling = access;
3927 }
3928
3929 repr->grp_read = 1;
3930 repr->grp_scalar_ptr = 1;
3931 return repr;
3932 }
3933
3934 /* Return true iff this ACCESS precludes IPA-SRA of the parameter it is
3935 associated with. REQ_ALIGN is the minimum required alignment. */
3936
3937 static bool
3938 access_precludes_ipa_sra_p (struct access *access, unsigned int req_align)
3939 {
3940 unsigned int exp_align;
3941 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3942 is incompatible assign in a call statement (and possibly even in asm
3943 statements). This can be relaxed by using a new temporary but only for
3944 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3945 intraprocedural SRA we deal with this by keeping the old aggregate around,
3946 something we cannot do in IPA-SRA.) */
3947 if (access->write
3948 && (is_gimple_call (access->stmt)
3949 || gimple_code (access->stmt) == GIMPLE_ASM))
3950 return true;
3951
3952 exp_align = get_object_alignment (access->expr);
3953 if (exp_align < req_align)
3954 return true;
3955
3956 return false;
3957 }
3958
3959
3960 /* Sort collected accesses for parameter PARM, identify representatives for
3961 each accessed region and link them together. Return NULL if there are
3962 different but overlapping accesses, return the special ptr value meaning
3963 there are no accesses for this parameter if that is the case and return the
3964 first representative otherwise. Set *RO_GRP if there is a group of accesses
3965 with only read (i.e. no write) accesses. */
3966
3967 static struct access *
3968 splice_param_accesses (tree parm, bool *ro_grp)
3969 {
3970 int i, j, access_count, group_count;
3971 int agg_size, total_size = 0;
3972 struct access *access, *res, **prev_acc_ptr = &res;
3973 vec<access_p> *access_vec;
3974
3975 access_vec = get_base_access_vector (parm);
3976 if (!access_vec)
3977 return &no_accesses_representant;
3978 access_count = access_vec->length ();
3979
3980 access_vec->qsort (compare_access_positions);
3981
3982 i = 0;
3983 total_size = 0;
3984 group_count = 0;
3985 while (i < access_count)
3986 {
3987 bool modification;
3988 tree a1_alias_type;
3989 access = (*access_vec)[i];
3990 modification = access->write;
3991 if (access_precludes_ipa_sra_p (access, TYPE_ALIGN (access->type)))
3992 return NULL;
3993 a1_alias_type = reference_alias_ptr_type (access->expr);
3994
3995 /* Access is about to become group representative unless we find some
3996 nasty overlap which would preclude us from breaking this parameter
3997 apart. */
3998
3999 j = i + 1;
4000 while (j < access_count)
4001 {
4002 struct access *ac2 = (*access_vec)[j];
4003 if (ac2->offset != access->offset)
4004 {
4005 /* All or nothing law for parameters. */
4006 if (access->offset + access->size > ac2->offset)
4007 return NULL;
4008 else
4009 break;
4010 }
4011 else if (ac2->size != access->size)
4012 return NULL;
4013
4014 if (access_precludes_ipa_sra_p (ac2, TYPE_ALIGN (access->type))
4015 || (ac2->type != access->type
4016 && (TREE_ADDRESSABLE (ac2->type)
4017 || TREE_ADDRESSABLE (access->type)))
4018 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
4019 return NULL;
4020
4021 modification |= ac2->write;
4022 ac2->group_representative = access;
4023 ac2->next_sibling = access->next_sibling;
4024 access->next_sibling = ac2;
4025 j++;
4026 }
4027
4028 group_count++;
4029 access->grp_maybe_modified = modification;
4030 if (!modification)
4031 *ro_grp = true;
4032 *prev_acc_ptr = access;
4033 prev_acc_ptr = &access->next_grp;
4034 total_size += access->size;
4035 i = j;
4036 }
4037
4038 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4039 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4040 else
4041 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4042 if (total_size >= agg_size)
4043 return NULL;
4044
4045 gcc_assert (group_count > 0);
4046 return res;
4047 }
4048
4049 /* Decide whether parameters with representative accesses given by REPR should
4050 be reduced into components. */
4051
4052 static int
4053 decide_one_param_reduction (struct access *repr)
4054 {
4055 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4056 bool by_ref;
4057 tree parm;
4058
4059 parm = repr->base;
4060 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4061 gcc_assert (cur_parm_size > 0);
4062
4063 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4064 {
4065 by_ref = true;
4066 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4067 }
4068 else
4069 {
4070 by_ref = false;
4071 agg_size = cur_parm_size;
4072 }
4073
4074 if (dump_file)
4075 {
4076 struct access *acc;
4077 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4078 print_generic_expr (dump_file, parm, 0);
4079 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4080 for (acc = repr; acc; acc = acc->next_grp)
4081 dump_access (dump_file, acc, true);
4082 }
4083
4084 total_size = 0;
4085 new_param_count = 0;
4086
4087 for (; repr; repr = repr->next_grp)
4088 {
4089 gcc_assert (parm == repr->base);
4090
4091 /* Taking the address of a non-addressable field is verboten. */
4092 if (by_ref && repr->non_addressable)
4093 return 0;
4094
4095 /* Do not decompose a non-BLKmode param in a way that would
4096 create BLKmode params. Especially for by-reference passing
4097 (thus, pointer-type param) this is hardly worthwhile. */
4098 if (DECL_MODE (parm) != BLKmode
4099 && TYPE_MODE (repr->type) == BLKmode)
4100 return 0;
4101
4102 if (!by_ref || (!repr->grp_maybe_modified
4103 && !repr->grp_not_necessarilly_dereferenced))
4104 total_size += repr->size;
4105 else
4106 total_size += cur_parm_size;
4107
4108 new_param_count++;
4109 }
4110
4111 gcc_assert (new_param_count > 0);
4112
4113 if (optimize_function_for_size_p (cfun))
4114 parm_size_limit = cur_parm_size;
4115 else
4116 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4117 * cur_parm_size);
4118
4119 if (total_size < agg_size
4120 && total_size <= parm_size_limit)
4121 {
4122 if (dump_file)
4123 fprintf (dump_file, " ....will be split into %i components\n",
4124 new_param_count);
4125 return new_param_count;
4126 }
4127 else
4128 return 0;
4129 }
4130
4131 /* The order of the following enums is important, we need to do extra work for
4132 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4133 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4134 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4135
4136 /* Identify representatives of all accesses to all candidate parameters for
4137 IPA-SRA. Return result based on what representatives have been found. */
4138
4139 static enum ipa_splicing_result
4140 splice_all_param_accesses (vec<access_p> &representatives)
4141 {
4142 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4143 tree parm;
4144 struct access *repr;
4145
4146 representatives.create (func_param_count);
4147
4148 for (parm = DECL_ARGUMENTS (current_function_decl);
4149 parm;
4150 parm = DECL_CHAIN (parm))
4151 {
4152 if (is_unused_scalar_param (parm))
4153 {
4154 representatives.quick_push (&no_accesses_representant);
4155 if (result == NO_GOOD_ACCESS)
4156 result = UNUSED_PARAMS;
4157 }
4158 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4159 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4160 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4161 {
4162 repr = unmodified_by_ref_scalar_representative (parm);
4163 representatives.quick_push (repr);
4164 if (repr)
4165 result = UNMODIF_BY_REF_ACCESSES;
4166 }
4167 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4168 {
4169 bool ro_grp = false;
4170 repr = splice_param_accesses (parm, &ro_grp);
4171 representatives.quick_push (repr);
4172
4173 if (repr && !no_accesses_p (repr))
4174 {
4175 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4176 {
4177 if (ro_grp)
4178 result = UNMODIF_BY_REF_ACCESSES;
4179 else if (result < MODIF_BY_REF_ACCESSES)
4180 result = MODIF_BY_REF_ACCESSES;
4181 }
4182 else if (result < BY_VAL_ACCESSES)
4183 result = BY_VAL_ACCESSES;
4184 }
4185 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4186 result = UNUSED_PARAMS;
4187 }
4188 else
4189 representatives.quick_push (NULL);
4190 }
4191
4192 if (result == NO_GOOD_ACCESS)
4193 {
4194 representatives.release ();
4195 return NO_GOOD_ACCESS;
4196 }
4197
4198 return result;
4199 }
4200
4201 /* Return the index of BASE in PARMS. Abort if it is not found. */
4202
4203 static inline int
4204 get_param_index (tree base, vec<tree> parms)
4205 {
4206 int i, len;
4207
4208 len = parms.length ();
4209 for (i = 0; i < len; i++)
4210 if (parms[i] == base)
4211 return i;
4212 gcc_unreachable ();
4213 }
4214
4215 /* Convert the decisions made at the representative level into compact
4216 parameter adjustments. REPRESENTATIVES are pointers to first
4217 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4218 final number of adjustments. */
4219
4220 static ipa_parm_adjustment_vec
4221 turn_representatives_into_adjustments (vec<access_p> representatives,
4222 int adjustments_count)
4223 {
4224 vec<tree> parms;
4225 ipa_parm_adjustment_vec adjustments;
4226 tree parm;
4227 int i;
4228
4229 gcc_assert (adjustments_count > 0);
4230 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4231 adjustments.create (adjustments_count);
4232 parm = DECL_ARGUMENTS (current_function_decl);
4233 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4234 {
4235 struct access *repr = representatives[i];
4236
4237 if (!repr || no_accesses_p (repr))
4238 {
4239 struct ipa_parm_adjustment adj;
4240
4241 memset (&adj, 0, sizeof (adj));
4242 adj.base_index = get_param_index (parm, parms);
4243 adj.base = parm;
4244 if (!repr)
4245 adj.copy_param = 1;
4246 else
4247 adj.remove_param = 1;
4248 adjustments.quick_push (adj);
4249 }
4250 else
4251 {
4252 struct ipa_parm_adjustment adj;
4253 int index = get_param_index (parm, parms);
4254
4255 for (; repr; repr = repr->next_grp)
4256 {
4257 memset (&adj, 0, sizeof (adj));
4258 gcc_assert (repr->base == parm);
4259 adj.base_index = index;
4260 adj.base = repr->base;
4261 adj.type = repr->type;
4262 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4263 adj.offset = repr->offset;
4264 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4265 && (repr->grp_maybe_modified
4266 || repr->grp_not_necessarilly_dereferenced));
4267 adjustments.quick_push (adj);
4268 }
4269 }
4270 }
4271 parms.release ();
4272 return adjustments;
4273 }
4274
4275 /* Analyze the collected accesses and produce a plan what to do with the
4276 parameters in the form of adjustments, NULL meaning nothing. */
4277
4278 static ipa_parm_adjustment_vec
4279 analyze_all_param_acesses (void)
4280 {
4281 enum ipa_splicing_result repr_state;
4282 bool proceed = false;
4283 int i, adjustments_count = 0;
4284 vec<access_p> representatives;
4285 ipa_parm_adjustment_vec adjustments;
4286
4287 repr_state = splice_all_param_accesses (representatives);
4288 if (repr_state == NO_GOOD_ACCESS)
4289 return ipa_parm_adjustment_vec();
4290
4291 /* If there are any parameters passed by reference which are not modified
4292 directly, we need to check whether they can be modified indirectly. */
4293 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4294 {
4295 analyze_caller_dereference_legality (representatives);
4296 analyze_modified_params (representatives);
4297 }
4298
4299 for (i = 0; i < func_param_count; i++)
4300 {
4301 struct access *repr = representatives[i];
4302
4303 if (repr && !no_accesses_p (repr))
4304 {
4305 if (repr->grp_scalar_ptr)
4306 {
4307 adjustments_count++;
4308 if (repr->grp_not_necessarilly_dereferenced
4309 || repr->grp_maybe_modified)
4310 representatives[i] = NULL;
4311 else
4312 {
4313 proceed = true;
4314 sra_stats.scalar_by_ref_to_by_val++;
4315 }
4316 }
4317 else
4318 {
4319 int new_components = decide_one_param_reduction (repr);
4320
4321 if (new_components == 0)
4322 {
4323 representatives[i] = NULL;
4324 adjustments_count++;
4325 }
4326 else
4327 {
4328 adjustments_count += new_components;
4329 sra_stats.aggregate_params_reduced++;
4330 sra_stats.param_reductions_created += new_components;
4331 proceed = true;
4332 }
4333 }
4334 }
4335 else
4336 {
4337 if (no_accesses_p (repr))
4338 {
4339 proceed = true;
4340 sra_stats.deleted_unused_parameters++;
4341 }
4342 adjustments_count++;
4343 }
4344 }
4345
4346 if (!proceed && dump_file)
4347 fprintf (dump_file, "NOT proceeding to change params.\n");
4348
4349 if (proceed)
4350 adjustments = turn_representatives_into_adjustments (representatives,
4351 adjustments_count);
4352 else
4353 adjustments = ipa_parm_adjustment_vec();
4354
4355 representatives.release ();
4356 return adjustments;
4357 }
4358
4359 /* If a parameter replacement identified by ADJ does not yet exist in the form
4360 of declaration, create it and record it, otherwise return the previously
4361 created one. */
4362
4363 static tree
4364 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4365 {
4366 tree repl;
4367 if (!adj->new_ssa_base)
4368 {
4369 char *pretty_name = make_fancy_name (adj->base);
4370
4371 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4372 DECL_NAME (repl) = get_identifier (pretty_name);
4373 obstack_free (&name_obstack, pretty_name);
4374
4375 adj->new_ssa_base = repl;
4376 }
4377 else
4378 repl = adj->new_ssa_base;
4379 return repl;
4380 }
4381
4382 /* Find the first adjustment for a particular parameter BASE in a vector of
4383 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4384 adjustment. */
4385
4386 static struct ipa_parm_adjustment *
4387 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4388 {
4389 int i, len;
4390
4391 len = adjustments.length ();
4392 for (i = 0; i < len; i++)
4393 {
4394 struct ipa_parm_adjustment *adj;
4395
4396 adj = &adjustments[i];
4397 if (!adj->copy_param && adj->base == base)
4398 return adj;
4399 }
4400
4401 return NULL;
4402 }
4403
4404 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4405 removed because its value is not used, replace the SSA_NAME with a one
4406 relating to a created VAR_DECL together all of its uses and return true.
4407 ADJUSTMENTS is a pointer to an adjustments vector. */
4408
4409 static bool
4410 replace_removed_params_ssa_names (gimple stmt,
4411 ipa_parm_adjustment_vec adjustments)
4412 {
4413 struct ipa_parm_adjustment *adj;
4414 tree lhs, decl, repl, name;
4415
4416 if (gimple_code (stmt) == GIMPLE_PHI)
4417 lhs = gimple_phi_result (stmt);
4418 else if (is_gimple_assign (stmt))
4419 lhs = gimple_assign_lhs (stmt);
4420 else if (is_gimple_call (stmt))
4421 lhs = gimple_call_lhs (stmt);
4422 else
4423 gcc_unreachable ();
4424
4425 if (TREE_CODE (lhs) != SSA_NAME)
4426 return false;
4427
4428 decl = SSA_NAME_VAR (lhs);
4429 if (decl == NULL_TREE
4430 || TREE_CODE (decl) != PARM_DECL)
4431 return false;
4432
4433 adj = get_adjustment_for_base (adjustments, decl);
4434 if (!adj)
4435 return false;
4436
4437 repl = get_replaced_param_substitute (adj);
4438 name = make_ssa_name (repl, stmt);
4439
4440 if (dump_file)
4441 {
4442 fprintf (dump_file, "replacing an SSA name of a removed param ");
4443 print_generic_expr (dump_file, lhs, 0);
4444 fprintf (dump_file, " with ");
4445 print_generic_expr (dump_file, name, 0);
4446 fprintf (dump_file, "\n");
4447 }
4448
4449 if (is_gimple_assign (stmt))
4450 gimple_assign_set_lhs (stmt, name);
4451 else if (is_gimple_call (stmt))
4452 gimple_call_set_lhs (stmt, name);
4453 else
4454 gimple_phi_set_result (stmt, name);
4455
4456 replace_uses_by (lhs, name);
4457 release_ssa_name (lhs);
4458 return true;
4459 }
4460
4461 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4462 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4463 specifies whether the function should care about type incompatibility the
4464 current and new expressions. If it is false, the function will leave
4465 incompatibility issues to the caller. Return true iff the expression
4466 was modified. */
4467
4468 static bool
4469 sra_ipa_modify_expr (tree *expr, bool convert,
4470 ipa_parm_adjustment_vec adjustments)
4471 {
4472 int i, len;
4473 struct ipa_parm_adjustment *adj, *cand = NULL;
4474 HOST_WIDE_INT offset, size, max_size;
4475 tree base, src;
4476
4477 len = adjustments.length ();
4478
4479 if (TREE_CODE (*expr) == BIT_FIELD_REF
4480 || TREE_CODE (*expr) == IMAGPART_EXPR
4481 || TREE_CODE (*expr) == REALPART_EXPR)
4482 {
4483 expr = &TREE_OPERAND (*expr, 0);
4484 convert = true;
4485 }
4486
4487 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4488 if (!base || size == -1 || max_size == -1)
4489 return false;
4490
4491 if (TREE_CODE (base) == MEM_REF)
4492 {
4493 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4494 base = TREE_OPERAND (base, 0);
4495 }
4496
4497 base = get_ssa_base_param (base);
4498 if (!base || TREE_CODE (base) != PARM_DECL)
4499 return false;
4500
4501 for (i = 0; i < len; i++)
4502 {
4503 adj = &adjustments[i];
4504
4505 if (adj->base == base
4506 && (adj->offset == offset || adj->remove_param))
4507 {
4508 cand = adj;
4509 break;
4510 }
4511 }
4512 if (!cand || cand->copy_param || cand->remove_param)
4513 return false;
4514
4515 if (cand->by_ref)
4516 src = build_simple_mem_ref (cand->reduction);
4517 else
4518 src = cand->reduction;
4519
4520 if (dump_file && (dump_flags & TDF_DETAILS))
4521 {
4522 fprintf (dump_file, "About to replace expr ");
4523 print_generic_expr (dump_file, *expr, 0);
4524 fprintf (dump_file, " with ");
4525 print_generic_expr (dump_file, src, 0);
4526 fprintf (dump_file, "\n");
4527 }
4528
4529 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4530 {
4531 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4532 *expr = vce;
4533 }
4534 else
4535 *expr = src;
4536 return true;
4537 }
4538
4539 /* If the statement pointed to by STMT_PTR contains any expressions that need
4540 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4541 potential type incompatibilities (GSI is used to accommodate conversion
4542 statements and must point to the statement). Return true iff the statement
4543 was modified. */
4544
4545 static bool
4546 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4547 ipa_parm_adjustment_vec adjustments)
4548 {
4549 gimple stmt = *stmt_ptr;
4550 tree *lhs_p, *rhs_p;
4551 bool any;
4552
4553 if (!gimple_assign_single_p (stmt))
4554 return false;
4555
4556 rhs_p = gimple_assign_rhs1_ptr (stmt);
4557 lhs_p = gimple_assign_lhs_ptr (stmt);
4558
4559 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4560 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4561 if (any)
4562 {
4563 tree new_rhs = NULL_TREE;
4564
4565 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4566 {
4567 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4568 {
4569 /* V_C_Es of constructors can cause trouble (PR 42714). */
4570 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4571 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4572 else
4573 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4574 NULL);
4575 }
4576 else
4577 new_rhs = fold_build1_loc (gimple_location (stmt),
4578 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4579 *rhs_p);
4580 }
4581 else if (REFERENCE_CLASS_P (*rhs_p)
4582 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4583 && !is_gimple_reg (*lhs_p))
4584 /* This can happen when an assignment in between two single field
4585 structures is turned into an assignment in between two pointers to
4586 scalars (PR 42237). */
4587 new_rhs = *rhs_p;
4588
4589 if (new_rhs)
4590 {
4591 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4592 true, GSI_SAME_STMT);
4593
4594 gimple_assign_set_rhs_from_tree (gsi, tmp);
4595 }
4596
4597 return true;
4598 }
4599
4600 return false;
4601 }
4602
4603 /* Traverse the function body and all modifications as described in
4604 ADJUSTMENTS. Return true iff the CFG has been changed. */
4605
4606 static bool
4607 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4608 {
4609 bool cfg_changed = false;
4610 basic_block bb;
4611
4612 FOR_EACH_BB (bb)
4613 {
4614 gimple_stmt_iterator gsi;
4615
4616 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4617 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4618
4619 gsi = gsi_start_bb (bb);
4620 while (!gsi_end_p (gsi))
4621 {
4622 gimple stmt = gsi_stmt (gsi);
4623 bool modified = false;
4624 tree *t;
4625 unsigned i;
4626
4627 switch (gimple_code (stmt))
4628 {
4629 case GIMPLE_RETURN:
4630 t = gimple_return_retval_ptr (stmt);
4631 if (*t != NULL_TREE)
4632 modified |= sra_ipa_modify_expr (t, true, adjustments);
4633 break;
4634
4635 case GIMPLE_ASSIGN:
4636 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4637 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4638 break;
4639
4640 case GIMPLE_CALL:
4641 /* Operands must be processed before the lhs. */
4642 for (i = 0; i < gimple_call_num_args (stmt); i++)
4643 {
4644 t = gimple_call_arg_ptr (stmt, i);
4645 modified |= sra_ipa_modify_expr (t, true, adjustments);
4646 }
4647
4648 if (gimple_call_lhs (stmt))
4649 {
4650 t = gimple_call_lhs_ptr (stmt);
4651 modified |= sra_ipa_modify_expr (t, false, adjustments);
4652 modified |= replace_removed_params_ssa_names (stmt,
4653 adjustments);
4654 }
4655 break;
4656
4657 case GIMPLE_ASM:
4658 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4659 {
4660 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4661 modified |= sra_ipa_modify_expr (t, true, adjustments);
4662 }
4663 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4664 {
4665 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4666 modified |= sra_ipa_modify_expr (t, false, adjustments);
4667 }
4668 break;
4669
4670 default:
4671 break;
4672 }
4673
4674 if (modified)
4675 {
4676 update_stmt (stmt);
4677 if (maybe_clean_eh_stmt (stmt)
4678 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4679 cfg_changed = true;
4680 }
4681 gsi_next (&gsi);
4682 }
4683 }
4684
4685 return cfg_changed;
4686 }
4687
4688 /* Call gimple_debug_bind_reset_value on all debug statements describing
4689 gimple register parameters that are being removed or replaced. */
4690
4691 static void
4692 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4693 {
4694 int i, len;
4695 gimple_stmt_iterator *gsip = NULL, gsi;
4696
4697 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4698 {
4699 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4700 gsip = &gsi;
4701 }
4702 len = adjustments.length ();
4703 for (i = 0; i < len; i++)
4704 {
4705 struct ipa_parm_adjustment *adj;
4706 imm_use_iterator ui;
4707 gimple stmt, def_temp;
4708 tree name, vexpr, copy = NULL_TREE;
4709 use_operand_p use_p;
4710
4711 adj = &adjustments[i];
4712 if (adj->copy_param || !is_gimple_reg (adj->base))
4713 continue;
4714 name = ssa_default_def (cfun, adj->base);
4715 vexpr = NULL;
4716 if (name)
4717 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4718 {
4719 if (gimple_clobber_p (stmt))
4720 {
4721 gimple_stmt_iterator cgsi = gsi_for_stmt (stmt);
4722 unlink_stmt_vdef (stmt);
4723 gsi_remove (&cgsi, true);
4724 release_defs (stmt);
4725 continue;
4726 }
4727 /* All other users must have been removed by
4728 ipa_sra_modify_function_body. */
4729 gcc_assert (is_gimple_debug (stmt));
4730 if (vexpr == NULL && gsip != NULL)
4731 {
4732 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4733 vexpr = make_node (DEBUG_EXPR_DECL);
4734 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4735 NULL);
4736 DECL_ARTIFICIAL (vexpr) = 1;
4737 TREE_TYPE (vexpr) = TREE_TYPE (name);
4738 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4739 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4740 }
4741 if (vexpr)
4742 {
4743 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4744 SET_USE (use_p, vexpr);
4745 }
4746 else
4747 gimple_debug_bind_reset_value (stmt);
4748 update_stmt (stmt);
4749 }
4750 /* Create a VAR_DECL for debug info purposes. */
4751 if (!DECL_IGNORED_P (adj->base))
4752 {
4753 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4754 VAR_DECL, DECL_NAME (adj->base),
4755 TREE_TYPE (adj->base));
4756 if (DECL_PT_UID_SET_P (adj->base))
4757 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4758 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4759 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4760 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4761 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4762 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4763 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4764 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4765 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4766 SET_DECL_RTL (copy, 0);
4767 TREE_USED (copy) = 1;
4768 DECL_CONTEXT (copy) = current_function_decl;
4769 add_local_decl (cfun, copy);
4770 DECL_CHAIN (copy) =
4771 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4772 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4773 }
4774 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4775 {
4776 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4777 if (vexpr)
4778 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4779 else
4780 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4781 NULL);
4782 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4783 }
4784 }
4785 }
4786
4787 /* Return false iff all callers have at least as many actual arguments as there
4788 are formal parameters in the current function. */
4789
4790 static bool
4791 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4792 void *data ATTRIBUTE_UNUSED)
4793 {
4794 struct cgraph_edge *cs;
4795 for (cs = node->callers; cs; cs = cs->next_caller)
4796 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4797 return true;
4798
4799 return false;
4800 }
4801
4802 /* Convert all callers of NODE. */
4803
4804 static bool
4805 convert_callers_for_node (struct cgraph_node *node,
4806 void *data)
4807 {
4808 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4809 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4810 struct cgraph_edge *cs;
4811
4812 for (cs = node->callers; cs; cs = cs->next_caller)
4813 {
4814 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4815
4816 if (dump_file)
4817 fprintf (dump_file, "Adjusting call %s/%i -> %s/%i\n",
4818 xstrdup (cgraph_node_name (cs->caller)),
4819 cs->caller->symbol.order,
4820 xstrdup (cgraph_node_name (cs->callee)),
4821 cs->callee->symbol.order);
4822
4823 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4824
4825 pop_cfun ();
4826 }
4827
4828 for (cs = node->callers; cs; cs = cs->next_caller)
4829 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4830 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4831 compute_inline_parameters (cs->caller, true);
4832 BITMAP_FREE (recomputed_callers);
4833
4834 return true;
4835 }
4836
4837 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4838
4839 static void
4840 convert_callers (struct cgraph_node *node, tree old_decl,
4841 ipa_parm_adjustment_vec adjustments)
4842 {
4843 basic_block this_block;
4844
4845 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4846 &adjustments, false);
4847
4848 if (!encountered_recursive_call)
4849 return;
4850
4851 FOR_EACH_BB (this_block)
4852 {
4853 gimple_stmt_iterator gsi;
4854
4855 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4856 {
4857 gimple stmt = gsi_stmt (gsi);
4858 tree call_fndecl;
4859 if (gimple_code (stmt) != GIMPLE_CALL)
4860 continue;
4861 call_fndecl = gimple_call_fndecl (stmt);
4862 if (call_fndecl == old_decl)
4863 {
4864 if (dump_file)
4865 fprintf (dump_file, "Adjusting recursive call");
4866 gimple_call_set_fndecl (stmt, node->symbol.decl);
4867 ipa_modify_call_arguments (NULL, stmt, adjustments);
4868 }
4869 }
4870 }
4871
4872 return;
4873 }
4874
4875 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4876 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4877
4878 static bool
4879 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4880 {
4881 struct cgraph_node *new_node;
4882 bool cfg_changed;
4883 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4884
4885 rebuild_cgraph_edges ();
4886 free_dominance_info (CDI_DOMINATORS);
4887 pop_cfun ();
4888
4889 new_node = cgraph_function_versioning (node, redirect_callers,
4890 NULL,
4891 NULL, false, NULL, NULL, "isra");
4892 redirect_callers.release ();
4893
4894 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4895 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4896 cfg_changed = ipa_sra_modify_function_body (adjustments);
4897 sra_ipa_reset_debug_stmts (adjustments);
4898 convert_callers (new_node, node->symbol.decl, adjustments);
4899 cgraph_make_node_local (new_node);
4900 return cfg_changed;
4901 }
4902
4903 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4904 attributes, return true otherwise. NODE is the cgraph node of the current
4905 function. */
4906
4907 static bool
4908 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4909 {
4910 if (!cgraph_node_can_be_local_p (node))
4911 {
4912 if (dump_file)
4913 fprintf (dump_file, "Function not local to this compilation unit.\n");
4914 return false;
4915 }
4916
4917 if (!node->local.can_change_signature)
4918 {
4919 if (dump_file)
4920 fprintf (dump_file, "Function can not change signature.\n");
4921 return false;
4922 }
4923
4924 if (!tree_versionable_function_p (node->symbol.decl))
4925 {
4926 if (dump_file)
4927 fprintf (dump_file, "Function is not versionable.\n");
4928 return false;
4929 }
4930
4931 if (DECL_VIRTUAL_P (current_function_decl))
4932 {
4933 if (dump_file)
4934 fprintf (dump_file, "Function is a virtual method.\n");
4935 return false;
4936 }
4937
4938 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4939 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4940 {
4941 if (dump_file)
4942 fprintf (dump_file, "Function too big to be made truly local.\n");
4943 return false;
4944 }
4945
4946 if (!node->callers)
4947 {
4948 if (dump_file)
4949 fprintf (dump_file,
4950 "Function has no callers in this compilation unit.\n");
4951 return false;
4952 }
4953
4954 if (cfun->stdarg)
4955 {
4956 if (dump_file)
4957 fprintf (dump_file, "Function uses stdarg. \n");
4958 return false;
4959 }
4960
4961 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4962 return false;
4963
4964 return true;
4965 }
4966
4967 /* Perform early interprocedural SRA. */
4968
4969 static unsigned int
4970 ipa_early_sra (void)
4971 {
4972 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4973 ipa_parm_adjustment_vec adjustments;
4974 int ret = 0;
4975
4976 if (!ipa_sra_preliminary_function_checks (node))
4977 return 0;
4978
4979 sra_initialize ();
4980 sra_mode = SRA_MODE_EARLY_IPA;
4981
4982 if (!find_param_candidates ())
4983 {
4984 if (dump_file)
4985 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4986 goto simple_out;
4987 }
4988
4989 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4990 NULL, true))
4991 {
4992 if (dump_file)
4993 fprintf (dump_file, "There are callers with insufficient number of "
4994 "arguments.\n");
4995 goto simple_out;
4996 }
4997
4998 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4999 func_param_count
5000 * last_basic_block_for_function (cfun));
5001 final_bbs = BITMAP_ALLOC (NULL);
5002
5003 scan_function ();
5004 if (encountered_apply_args)
5005 {
5006 if (dump_file)
5007 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
5008 goto out;
5009 }
5010
5011 if (encountered_unchangable_recursive_call)
5012 {
5013 if (dump_file)
5014 fprintf (dump_file, "Function calls itself with insufficient "
5015 "number of arguments.\n");
5016 goto out;
5017 }
5018
5019 adjustments = analyze_all_param_acesses ();
5020 if (!adjustments.exists ())
5021 goto out;
5022 if (dump_file)
5023 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
5024
5025 if (modify_function (node, adjustments))
5026 ret = TODO_update_ssa | TODO_cleanup_cfg;
5027 else
5028 ret = TODO_update_ssa;
5029 adjustments.release ();
5030
5031 statistics_counter_event (cfun, "Unused parameters deleted",
5032 sra_stats.deleted_unused_parameters);
5033 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
5034 sra_stats.scalar_by_ref_to_by_val);
5035 statistics_counter_event (cfun, "Aggregate parameters broken up",
5036 sra_stats.aggregate_params_reduced);
5037 statistics_counter_event (cfun, "Aggregate parameter components created",
5038 sra_stats.param_reductions_created);
5039
5040 out:
5041 BITMAP_FREE (final_bbs);
5042 free (bb_dereferences);
5043 simple_out:
5044 sra_deinitialize ();
5045 return ret;
5046 }
5047
5048 /* Return if early ipa sra shall be performed. */
5049 static bool
5050 ipa_early_sra_gate (void)
5051 {
5052 return flag_ipa_sra && dbg_cnt (eipa_sra);
5053 }
5054
5055 namespace {
5056
5057 const pass_data pass_data_early_ipa_sra =
5058 {
5059 GIMPLE_PASS, /* type */
5060 "eipa_sra", /* name */
5061 OPTGROUP_NONE, /* optinfo_flags */
5062 true, /* has_gate */
5063 true, /* has_execute */
5064 TV_IPA_SRA, /* tv_id */
5065 0, /* properties_required */
5066 0, /* properties_provided */
5067 0, /* properties_destroyed */
5068 0, /* todo_flags_start */
5069 TODO_dump_symtab, /* todo_flags_finish */
5070 };
5071
5072 class pass_early_ipa_sra : public gimple_opt_pass
5073 {
5074 public:
5075 pass_early_ipa_sra(gcc::context *ctxt)
5076 : gimple_opt_pass(pass_data_early_ipa_sra, ctxt)
5077 {}
5078
5079 /* opt_pass methods: */
5080 bool gate () { return ipa_early_sra_gate (); }
5081 unsigned int execute () { return ipa_early_sra (); }
5082
5083 }; // class pass_early_ipa_sra
5084
5085 } // anon namespace
5086
5087 gimple_opt_pass *
5088 make_pass_early_ipa_sra (gcc::context *ctxt)
5089 {
5090 return new pass_early_ipa_sra (ctxt);
5091 }