vectorizer cost model enhancement
[official-gcc.git] / gcc / tree-sra.c
blob58c7565dcf6b7017a3b5b12b6489dc18243914f2
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>
7 This file is part of GCC.
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.
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.
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/>. */
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.
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.
33 Both passes operate in four stages:
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.
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.
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.
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.
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).
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.
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.
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. */
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-ssa.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 #include "ipa-utils.h"
96 /* Enumeration of all aggregate reductions we can do. */
97 enum sra_mode { SRA_MODE_EARLY_IPA, /* early call regularization */
98 SRA_MODE_EARLY_INTRA, /* early intraprocedural SRA */
99 SRA_MODE_INTRA }; /* late intraprocedural SRA */
101 /* Global variable describing which aggregate reduction we are performing at
102 the moment. */
103 static enum sra_mode sra_mode;
105 struct assign_link;
107 /* ACCESS represents each access to an aggregate variable (as a whole or a
108 part). It can also represent a group of accesses that refer to exactly the
109 same fragment of an aggregate (i.e. those that have exactly the same offset
110 and size). Such representatives for a single aggregate, once determined,
111 are linked in a linked list and have the group fields set.
113 Moreover, when doing intraprocedural SRA, a tree is built from those
114 representatives (by the means of first_child and next_sibling pointers), in
115 which all items in a subtree are "within" the root, i.e. their offset is
116 greater or equal to offset of the root and offset+size is smaller or equal
117 to offset+size of the root. Children of an access are sorted by offset.
119 Note that accesses to parts of vector and complex number types always
120 represented by an access to the whole complex number or a vector. It is a
121 duty of the modifying functions to replace them appropriately. */
123 struct access
125 /* Values returned by `get_ref_base_and_extent' for each component reference
126 If EXPR isn't a component reference just set `BASE = EXPR', `OFFSET = 0',
127 `SIZE = TREE_SIZE (TREE_TYPE (expr))'. */
128 HOST_WIDE_INT offset;
129 HOST_WIDE_INT size;
130 tree base;
132 /* Expression. It is context dependent so do not use it to create new
133 expressions to access the original aggregate. See PR 42154 for a
134 testcase. */
135 tree expr;
136 /* Type. */
137 tree type;
139 /* The statement this access belongs to. */
140 gimple stmt;
142 /* Next group representative for this aggregate. */
143 struct access *next_grp;
145 /* Pointer to the group representative. Pointer to itself if the struct is
146 the representative. */
147 struct access *group_representative;
149 /* If this access has any children (in terms of the definition above), this
150 points to the first one. */
151 struct access *first_child;
153 /* In intraprocedural SRA, pointer to the next sibling in the access tree as
154 described above. In IPA-SRA this is a pointer to the next access
155 belonging to the same group (having the same representative). */
156 struct access *next_sibling;
158 /* Pointers to the first and last element in the linked list of assign
159 links. */
160 struct assign_link *first_link, *last_link;
162 /* Pointer to the next access in the work queue. */
163 struct access *next_queued;
165 /* Replacement variable for this access "region." Never to be accessed
166 directly, always only by the means of get_access_replacement() and only
167 when grp_to_be_replaced flag is set. */
168 tree replacement_decl;
170 /* Is this particular access write access? */
171 unsigned write : 1;
173 /* Is this access an access to a non-addressable field? */
174 unsigned non_addressable : 1;
176 /* Is this access currently in the work queue? */
177 unsigned grp_queued : 1;
179 /* Does this group contain a write access? This flag is propagated down the
180 access tree. */
181 unsigned grp_write : 1;
183 /* Does this group contain a read access? This flag is propagated down the
184 access tree. */
185 unsigned grp_read : 1;
187 /* Does this group contain a read access that comes from an assignment
188 statement? This flag is propagated down the access tree. */
189 unsigned grp_assignment_read : 1;
191 /* Does this group contain a write access that comes from an assignment
192 statement? This flag is propagated down the access tree. */
193 unsigned grp_assignment_write : 1;
195 /* Does this group contain a read access through a scalar type? This flag is
196 not propagated in the access tree in any direction. */
197 unsigned grp_scalar_read : 1;
199 /* Does this group contain a write access through a scalar type? This flag
200 is not propagated in the access tree in any direction. */
201 unsigned grp_scalar_write : 1;
203 /* Is this access an artificial one created to scalarize some record
204 entirely? */
205 unsigned grp_total_scalarization : 1;
207 /* Other passes of the analysis use this bit to make function
208 analyze_access_subtree create scalar replacements for this group if
209 possible. */
210 unsigned grp_hint : 1;
212 /* Is the subtree rooted in this access fully covered by scalar
213 replacements? */
214 unsigned grp_covered : 1;
216 /* If set to true, this access and all below it in an access tree must not be
217 scalarized. */
218 unsigned grp_unscalarizable_region : 1;
220 /* Whether data have been written to parts of the aggregate covered by this
221 access which is not to be scalarized. This flag is propagated up in the
222 access tree. */
223 unsigned grp_unscalarized_data : 1;
225 /* Does this access and/or group contain a write access through a
226 BIT_FIELD_REF? */
227 unsigned grp_partial_lhs : 1;
229 /* Set when a scalar replacement should be created for this variable. */
230 unsigned grp_to_be_replaced : 1;
232 /* Set when we want a replacement for the sole purpose of having it in
233 generated debug statements. */
234 unsigned grp_to_be_debug_replaced : 1;
236 /* Should TREE_NO_WARNING of a replacement be set? */
237 unsigned grp_no_warning : 1;
239 /* Is it possible that the group refers to data which might be (directly or
240 otherwise) modified? */
241 unsigned grp_maybe_modified : 1;
243 /* Set when this is a representative of a pointer to scalar (i.e. by
244 reference) parameter which we consider for turning into a plain scalar
245 (i.e. a by value parameter). */
246 unsigned grp_scalar_ptr : 1;
248 /* Set when we discover that this pointer is not safe to dereference in the
249 caller. */
250 unsigned grp_not_necessarilly_dereferenced : 1;
253 typedef struct access *access_p;
256 /* Alloc pool for allocating access structures. */
257 static alloc_pool access_pool;
259 /* A structure linking lhs and rhs accesses from an aggregate assignment. They
260 are used to propagate subaccesses from rhs to lhs as long as they don't
261 conflict with what is already there. */
262 struct assign_link
264 struct access *lacc, *racc;
265 struct assign_link *next;
268 /* Alloc pool for allocating assign link structures. */
269 static alloc_pool link_pool;
271 /* Base (tree) -> Vector (vec<access_p> *) map. */
272 static struct pointer_map_t *base_access_vec;
274 /* Candidate hash table helpers. */
276 struct uid_decl_hasher : typed_noop_remove <tree_node>
278 typedef tree_node value_type;
279 typedef tree_node compare_type;
280 static inline hashval_t hash (const value_type *);
281 static inline bool equal (const value_type *, const compare_type *);
284 /* Hash a tree in a uid_decl_map. */
286 inline hashval_t
287 uid_decl_hasher::hash (const value_type *item)
289 return item->decl_minimal.uid;
292 /* Return true if the DECL_UID in both trees are equal. */
294 inline bool
295 uid_decl_hasher::equal (const value_type *a, const compare_type *b)
297 return (a->decl_minimal.uid == b->decl_minimal.uid);
300 /* Set of candidates. */
301 static bitmap candidate_bitmap;
302 static hash_table <uid_decl_hasher> candidates;
304 /* For a candidate UID return the candidates decl. */
306 static inline tree
307 candidate (unsigned uid)
309 tree_node t;
310 t.decl_minimal.uid = uid;
311 return candidates.find_with_hash (&t, static_cast <hashval_t> (uid));
314 /* Bitmap of candidates which we should try to entirely scalarize away and
315 those which cannot be (because they are and need be used as a whole). */
316 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
318 /* Obstack for creation of fancy names. */
319 static struct obstack name_obstack;
321 /* Head of a linked list of accesses that need to have its subaccesses
322 propagated to their assignment counterparts. */
323 static struct access *work_queue_head;
325 /* Number of parameters of the analyzed function when doing early ipa SRA. */
326 static int func_param_count;
328 /* scan_function sets the following to true if it encounters a call to
329 __builtin_apply_args. */
330 static bool encountered_apply_args;
332 /* Set by scan_function when it finds a recursive call. */
333 static bool encountered_recursive_call;
335 /* Set by scan_function when it finds a recursive call with less actual
336 arguments than formal parameters.. */
337 static bool encountered_unchangable_recursive_call;
339 /* This is a table in which for each basic block and parameter there is a
340 distance (offset + size) in that parameter which is dereferenced and
341 accessed in that BB. */
342 static HOST_WIDE_INT *bb_dereferences;
343 /* Bitmap of BBs that can cause the function to "stop" progressing by
344 returning, throwing externally, looping infinitely or calling a function
345 which might abort etc.. */
346 static bitmap final_bbs;
348 /* Representative of no accesses at all. */
349 static struct access no_accesses_representant;
351 /* Predicate to test the special value. */
353 static inline bool
354 no_accesses_p (struct access *access)
356 return access == &no_accesses_representant;
359 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
360 representative fields are dumped, otherwise those which only describe the
361 individual access are. */
363 static struct
365 /* Number of processed aggregates is readily available in
366 analyze_all_variable_accesses and so is not stored here. */
368 /* Number of created scalar replacements. */
369 int replacements;
371 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
372 expression. */
373 int exprs;
375 /* Number of statements created by generate_subtree_copies. */
376 int subtree_copies;
378 /* Number of statements created by load_assign_lhs_subreplacements. */
379 int subreplacements;
381 /* Number of times sra_modify_assign has deleted a statement. */
382 int deleted;
384 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
385 RHS reparately due to type conversions or nonexistent matching
386 references. */
387 int separate_lhs_rhs_handling;
389 /* Number of parameters that were removed because they were unused. */
390 int deleted_unused_parameters;
392 /* Number of scalars passed as parameters by reference that have been
393 converted to be passed by value. */
394 int scalar_by_ref_to_by_val;
396 /* Number of aggregate parameters that were replaced by one or more of their
397 components. */
398 int aggregate_params_reduced;
400 /* Numbber of components created when splitting aggregate parameters. */
401 int param_reductions_created;
402 } sra_stats;
404 static void
405 dump_access (FILE *f, struct access *access, bool grp)
407 fprintf (f, "access { ");
408 fprintf (f, "base = (%d)'", DECL_UID (access->base));
409 print_generic_expr (f, access->base, 0);
410 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
411 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
412 fprintf (f, ", expr = ");
413 print_generic_expr (f, access->expr, 0);
414 fprintf (f, ", type = ");
415 print_generic_expr (f, access->type, 0);
416 if (grp)
417 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
418 "grp_assignment_write = %d, grp_scalar_read = %d, "
419 "grp_scalar_write = %d, grp_total_scalarization = %d, "
420 "grp_hint = %d, grp_covered = %d, "
421 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
422 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
423 "grp_to_be_debug_replaced = %d, grp_maybe_modified = %d, "
424 "grp_not_necessarilly_dereferenced = %d\n",
425 access->grp_read, access->grp_write, access->grp_assignment_read,
426 access->grp_assignment_write, access->grp_scalar_read,
427 access->grp_scalar_write, access->grp_total_scalarization,
428 access->grp_hint, access->grp_covered,
429 access->grp_unscalarizable_region, access->grp_unscalarized_data,
430 access->grp_partial_lhs, access->grp_to_be_replaced,
431 access->grp_to_be_debug_replaced, access->grp_maybe_modified,
432 access->grp_not_necessarilly_dereferenced);
433 else
434 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
435 "grp_partial_lhs = %d\n",
436 access->write, access->grp_total_scalarization,
437 access->grp_partial_lhs);
440 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
442 static void
443 dump_access_tree_1 (FILE *f, struct access *access, int level)
447 int i;
449 for (i = 0; i < level; i++)
450 fputs ("* ", dump_file);
452 dump_access (f, access, true);
454 if (access->first_child)
455 dump_access_tree_1 (f, access->first_child, level + 1);
457 access = access->next_sibling;
459 while (access);
462 /* Dump all access trees for a variable, given the pointer to the first root in
463 ACCESS. */
465 static void
466 dump_access_tree (FILE *f, struct access *access)
468 for (; access; access = access->next_grp)
469 dump_access_tree_1 (f, access, 0);
472 /* Return true iff ACC is non-NULL and has subaccesses. */
474 static inline bool
475 access_has_children_p (struct access *acc)
477 return acc && acc->first_child;
480 /* Return true iff ACC is (partly) covered by at least one replacement. */
482 static bool
483 access_has_replacements_p (struct access *acc)
485 struct access *child;
486 if (acc->grp_to_be_replaced)
487 return true;
488 for (child = acc->first_child; child; child = child->next_sibling)
489 if (access_has_replacements_p (child))
490 return true;
491 return false;
494 /* Return a vector of pointers to accesses for the variable given in BASE or
495 NULL if there is none. */
497 static vec<access_p> *
498 get_base_access_vector (tree base)
500 void **slot;
502 slot = pointer_map_contains (base_access_vec, base);
503 if (!slot)
504 return NULL;
505 else
506 return *(vec<access_p> **) slot;
509 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
510 in ACCESS. Return NULL if it cannot be found. */
512 static struct access *
513 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
514 HOST_WIDE_INT size)
516 while (access && (access->offset != offset || access->size != size))
518 struct access *child = access->first_child;
520 while (child && (child->offset + child->size <= offset))
521 child = child->next_sibling;
522 access = child;
525 return access;
528 /* Return the first group representative for DECL or NULL if none exists. */
530 static struct access *
531 get_first_repr_for_decl (tree base)
533 vec<access_p> *access_vec;
535 access_vec = get_base_access_vector (base);
536 if (!access_vec)
537 return NULL;
539 return (*access_vec)[0];
542 /* Find an access representative for the variable BASE and given OFFSET and
543 SIZE. Requires that access trees have already been built. Return NULL if
544 it cannot be found. */
546 static struct access *
547 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
548 HOST_WIDE_INT size)
550 struct access *access;
552 access = get_first_repr_for_decl (base);
553 while (access && (access->offset + access->size <= offset))
554 access = access->next_grp;
555 if (!access)
556 return NULL;
558 return find_access_in_subtree (access, offset, size);
561 /* Add LINK to the linked list of assign links of RACC. */
562 static void
563 add_link_to_rhs (struct access *racc, struct assign_link *link)
565 gcc_assert (link->racc == racc);
567 if (!racc->first_link)
569 gcc_assert (!racc->last_link);
570 racc->first_link = link;
572 else
573 racc->last_link->next = link;
575 racc->last_link = link;
576 link->next = NULL;
579 /* Move all link structures in their linked list in OLD_RACC to the linked list
580 in NEW_RACC. */
581 static void
582 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
584 if (!old_racc->first_link)
586 gcc_assert (!old_racc->last_link);
587 return;
590 if (new_racc->first_link)
592 gcc_assert (!new_racc->last_link->next);
593 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
595 new_racc->last_link->next = old_racc->first_link;
596 new_racc->last_link = old_racc->last_link;
598 else
600 gcc_assert (!new_racc->last_link);
602 new_racc->first_link = old_racc->first_link;
603 new_racc->last_link = old_racc->last_link;
605 old_racc->first_link = old_racc->last_link = NULL;
608 /* Add ACCESS to the work queue (which is actually a stack). */
610 static void
611 add_access_to_work_queue (struct access *access)
613 if (!access->grp_queued)
615 gcc_assert (!access->next_queued);
616 access->next_queued = work_queue_head;
617 access->grp_queued = 1;
618 work_queue_head = access;
622 /* Pop an access from the work queue, and return it, assuming there is one. */
624 static struct access *
625 pop_access_from_work_queue (void)
627 struct access *access = work_queue_head;
629 work_queue_head = access->next_queued;
630 access->next_queued = NULL;
631 access->grp_queued = 0;
632 return access;
636 /* Allocate necessary structures. */
638 static void
639 sra_initialize (void)
641 candidate_bitmap = BITMAP_ALLOC (NULL);
642 candidates.create (vec_safe_length (cfun->local_decls) / 2);
643 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
644 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
645 gcc_obstack_init (&name_obstack);
646 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
647 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
648 base_access_vec = pointer_map_create ();
649 memset (&sra_stats, 0, sizeof (sra_stats));
650 encountered_apply_args = false;
651 encountered_recursive_call = false;
652 encountered_unchangable_recursive_call = false;
655 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
657 static bool
658 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
659 void *data ATTRIBUTE_UNUSED)
661 vec<access_p> *access_vec = (vec<access_p> *) *value;
662 vec_free (access_vec);
663 return true;
666 /* Deallocate all general structures. */
668 static void
669 sra_deinitialize (void)
671 BITMAP_FREE (candidate_bitmap);
672 candidates.dispose ();
673 BITMAP_FREE (should_scalarize_away_bitmap);
674 BITMAP_FREE (cannot_scalarize_away_bitmap);
675 free_alloc_pool (access_pool);
676 free_alloc_pool (link_pool);
677 obstack_free (&name_obstack, NULL);
679 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
680 pointer_map_destroy (base_access_vec);
683 /* Remove DECL from candidates for SRA and write REASON to the dump file if
684 there is one. */
685 static void
686 disqualify_candidate (tree decl, const char *reason)
688 if (bitmap_clear_bit (candidate_bitmap, DECL_UID (decl)))
689 candidates.clear_slot (candidates.find_slot_with_hash (decl,
690 DECL_UID (decl),
691 NO_INSERT));
693 if (dump_file && (dump_flags & TDF_DETAILS))
695 fprintf (dump_file, "! Disqualifying ");
696 print_generic_expr (dump_file, decl, 0);
697 fprintf (dump_file, " - %s\n", reason);
701 /* Return true iff the type contains a field or an element which does not allow
702 scalarization. */
704 static bool
705 type_internals_preclude_sra_p (tree type, const char **msg)
707 tree fld;
708 tree et;
710 switch (TREE_CODE (type))
712 case RECORD_TYPE:
713 case UNION_TYPE:
714 case QUAL_UNION_TYPE:
715 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
716 if (TREE_CODE (fld) == FIELD_DECL)
718 tree ft = TREE_TYPE (fld);
720 if (TREE_THIS_VOLATILE (fld))
722 *msg = "volatile structure field";
723 return true;
725 if (!DECL_FIELD_OFFSET (fld))
727 *msg = "no structure field offset";
728 return true;
730 if (!DECL_SIZE (fld))
732 *msg = "zero structure field size";
733 return true;
735 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
737 *msg = "structure field offset not fixed";
738 return true;
740 if (!host_integerp (DECL_SIZE (fld), 1))
742 *msg = "structure field size not fixed";
743 return true;
745 if (!host_integerp (bit_position (fld), 0))
747 *msg = "structure field size too big";
748 return true;
750 if (AGGREGATE_TYPE_P (ft)
751 && int_bit_position (fld) % BITS_PER_UNIT != 0)
753 *msg = "structure field is bit field";
754 return true;
757 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
758 return true;
761 return false;
763 case ARRAY_TYPE:
764 et = TREE_TYPE (type);
766 if (TYPE_VOLATILE (et))
768 *msg = "element type is volatile";
769 return true;
772 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
773 return true;
775 return false;
777 default:
778 return false;
782 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
783 base variable if it is. Return T if it is not an SSA_NAME. */
785 static tree
786 get_ssa_base_param (tree t)
788 if (TREE_CODE (t) == SSA_NAME)
790 if (SSA_NAME_IS_DEFAULT_DEF (t))
791 return SSA_NAME_VAR (t);
792 else
793 return NULL_TREE;
795 return t;
798 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
799 belongs to, unless the BB has already been marked as a potentially
800 final. */
802 static void
803 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
805 basic_block bb = gimple_bb (stmt);
806 int idx, parm_index = 0;
807 tree parm;
809 if (bitmap_bit_p (final_bbs, bb->index))
810 return;
812 for (parm = DECL_ARGUMENTS (current_function_decl);
813 parm && parm != base;
814 parm = DECL_CHAIN (parm))
815 parm_index++;
817 gcc_assert (parm_index < func_param_count);
819 idx = bb->index * func_param_count + parm_index;
820 if (bb_dereferences[idx] < dist)
821 bb_dereferences[idx] = dist;
824 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
825 the three fields. Also add it to the vector of accesses corresponding to
826 the base. Finally, return the new access. */
828 static struct access *
829 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
831 vec<access_p> *v;
832 struct access *access;
833 void **slot;
835 access = (struct access *) pool_alloc (access_pool);
836 memset (access, 0, sizeof (struct access));
837 access->base = base;
838 access->offset = offset;
839 access->size = size;
841 slot = pointer_map_contains (base_access_vec, base);
842 if (slot)
843 v = (vec<access_p> *) *slot;
844 else
845 vec_alloc (v, 32);
847 v->safe_push (access);
849 *((vec<access_p> **)
850 pointer_map_insert (base_access_vec, base)) = v;
852 return access;
855 /* Create and insert access for EXPR. Return created access, or NULL if it is
856 not possible. */
858 static struct access *
859 create_access (tree expr, gimple stmt, bool write)
861 struct access *access;
862 HOST_WIDE_INT offset, size, max_size;
863 tree base = expr;
864 bool ptr, unscalarizable_region = false;
866 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
868 if (sra_mode == SRA_MODE_EARLY_IPA
869 && TREE_CODE (base) == MEM_REF)
871 base = get_ssa_base_param (TREE_OPERAND (base, 0));
872 if (!base)
873 return NULL;
874 ptr = true;
876 else
877 ptr = false;
879 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
880 return NULL;
882 if (sra_mode == SRA_MODE_EARLY_IPA)
884 if (size < 0 || size != max_size)
886 disqualify_candidate (base, "Encountered a variable sized access.");
887 return NULL;
889 if (TREE_CODE (expr) == COMPONENT_REF
890 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
892 disqualify_candidate (base, "Encountered a bit-field access.");
893 return NULL;
895 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
897 if (ptr)
898 mark_parm_dereference (base, offset + size, stmt);
900 else
902 if (size != max_size)
904 size = max_size;
905 unscalarizable_region = true;
907 if (size < 0)
909 disqualify_candidate (base, "Encountered an unconstrained access.");
910 return NULL;
914 access = create_access_1 (base, offset, size);
915 access->expr = expr;
916 access->type = TREE_TYPE (expr);
917 access->write = write;
918 access->grp_unscalarizable_region = unscalarizable_region;
919 access->stmt = stmt;
921 if (TREE_CODE (expr) == COMPONENT_REF
922 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
923 access->non_addressable = 1;
925 return access;
929 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
930 register types or (recursively) records with only these two kinds of fields.
931 It also returns false if any of these records contains a bit-field. */
933 static bool
934 type_consists_of_records_p (tree type)
936 tree fld;
938 if (TREE_CODE (type) != RECORD_TYPE)
939 return false;
941 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
942 if (TREE_CODE (fld) == FIELD_DECL)
944 tree ft = TREE_TYPE (fld);
946 if (DECL_BIT_FIELD (fld))
947 return false;
949 if (!is_gimple_reg_type (ft)
950 && !type_consists_of_records_p (ft))
951 return false;
954 return true;
957 /* Create total_scalarization accesses for all scalar type fields in DECL that
958 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
959 must be the top-most VAR_DECL representing the variable, OFFSET must be the
960 offset of DECL within BASE. REF must be the memory reference expression for
961 the given decl. */
963 static void
964 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
965 tree ref)
967 tree fld, decl_type = TREE_TYPE (decl);
969 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
970 if (TREE_CODE (fld) == FIELD_DECL)
972 HOST_WIDE_INT pos = offset + int_bit_position (fld);
973 tree ft = TREE_TYPE (fld);
974 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
975 NULL_TREE);
977 if (is_gimple_reg_type (ft))
979 struct access *access;
980 HOST_WIDE_INT size;
982 size = tree_low_cst (DECL_SIZE (fld), 1);
983 access = create_access_1 (base, pos, size);
984 access->expr = nref;
985 access->type = ft;
986 access->grp_total_scalarization = 1;
987 /* Accesses for intraprocedural SRA can have their stmt NULL. */
989 else
990 completely_scalarize_record (base, fld, pos, nref);
994 /* Create total_scalarization accesses for all scalar type fields in VAR and
995 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
996 type_consists_of_records_p. */
998 static void
999 completely_scalarize_var (tree var)
1001 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
1002 struct access *access;
1004 access = create_access_1 (var, 0, size);
1005 access->expr = var;
1006 access->type = TREE_TYPE (var);
1007 access->grp_total_scalarization = 1;
1009 completely_scalarize_record (var, var, 0, var);
1012 /* Search the given tree for a declaration by skipping handled components and
1013 exclude it from the candidates. */
1015 static void
1016 disqualify_base_of_expr (tree t, const char *reason)
1018 t = get_base_address (t);
1019 if (sra_mode == SRA_MODE_EARLY_IPA
1020 && TREE_CODE (t) == MEM_REF)
1021 t = get_ssa_base_param (TREE_OPERAND (t, 0));
1023 if (t && DECL_P (t))
1024 disqualify_candidate (t, reason);
1027 /* Scan expression EXPR and create access structures for all accesses to
1028 candidates for scalarization. Return the created access or NULL if none is
1029 created. */
1031 static struct access *
1032 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
1034 struct access *ret = NULL;
1035 bool partial_ref;
1037 if (TREE_CODE (expr) == BIT_FIELD_REF
1038 || TREE_CODE (expr) == IMAGPART_EXPR
1039 || TREE_CODE (expr) == REALPART_EXPR)
1041 expr = TREE_OPERAND (expr, 0);
1042 partial_ref = true;
1044 else
1045 partial_ref = false;
1047 /* We need to dive through V_C_Es in order to get the size of its parameter
1048 and not the result type. Ada produces such statements. We are also
1049 capable of handling the topmost V_C_E but not any of those buried in other
1050 handled components. */
1051 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1052 expr = TREE_OPERAND (expr, 0);
1054 if (contains_view_convert_expr_p (expr))
1056 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1057 "component.");
1058 return NULL;
1061 switch (TREE_CODE (expr))
1063 case MEM_REF:
1064 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1065 && sra_mode != SRA_MODE_EARLY_IPA)
1066 return NULL;
1067 /* fall through */
1068 case VAR_DECL:
1069 case PARM_DECL:
1070 case RESULT_DECL:
1071 case COMPONENT_REF:
1072 case ARRAY_REF:
1073 case ARRAY_RANGE_REF:
1074 ret = create_access (expr, stmt, write);
1075 break;
1077 default:
1078 break;
1081 if (write && partial_ref && ret)
1082 ret->grp_partial_lhs = 1;
1084 return ret;
1087 /* Scan expression EXPR and create access structures for all accesses to
1088 candidates for scalarization. Return true if any access has been inserted.
1089 STMT must be the statement from which the expression is taken, WRITE must be
1090 true if the expression is a store and false otherwise. */
1092 static bool
1093 build_access_from_expr (tree expr, gimple stmt, bool write)
1095 struct access *access;
1097 access = build_access_from_expr_1 (expr, stmt, write);
1098 if (access)
1100 /* This means the aggregate is accesses as a whole in a way other than an
1101 assign statement and thus cannot be removed even if we had a scalar
1102 replacement for everything. */
1103 if (cannot_scalarize_away_bitmap)
1104 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1105 return true;
1107 return false;
1110 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1111 modes in which it matters, return true iff they have been disqualified. RHS
1112 may be NULL, in that case ignore it. If we scalarize an aggregate in
1113 intra-SRA we may need to add statements after each statement. This is not
1114 possible if a statement unconditionally has to end the basic block. */
1115 static bool
1116 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1118 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1119 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1121 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1122 if (rhs)
1123 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1124 return true;
1126 return false;
1129 /* Scan expressions occurring in STMT, create access structures for all accesses
1130 to candidates for scalarization and remove those candidates which occur in
1131 statements or expressions that prevent them from being split apart. Return
1132 true if any access has been inserted. */
1134 static bool
1135 build_accesses_from_assign (gimple stmt)
1137 tree lhs, rhs;
1138 struct access *lacc, *racc;
1140 if (!gimple_assign_single_p (stmt)
1141 /* Scope clobbers don't influence scalarization. */
1142 || gimple_clobber_p (stmt))
1143 return false;
1145 lhs = gimple_assign_lhs (stmt);
1146 rhs = gimple_assign_rhs1 (stmt);
1148 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1149 return false;
1151 racc = build_access_from_expr_1 (rhs, stmt, false);
1152 lacc = build_access_from_expr_1 (lhs, stmt, true);
1154 if (lacc)
1155 lacc->grp_assignment_write = 1;
1157 if (racc)
1159 racc->grp_assignment_read = 1;
1160 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1161 && !is_gimple_reg_type (racc->type))
1162 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1165 if (lacc && racc
1166 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1167 && !lacc->grp_unscalarizable_region
1168 && !racc->grp_unscalarizable_region
1169 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1170 && lacc->size == racc->size
1171 && useless_type_conversion_p (lacc->type, racc->type))
1173 struct assign_link *link;
1175 link = (struct assign_link *) pool_alloc (link_pool);
1176 memset (link, 0, sizeof (struct assign_link));
1178 link->lacc = lacc;
1179 link->racc = racc;
1181 add_link_to_rhs (racc, link);
1184 return lacc || racc;
1187 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1188 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1190 static bool
1191 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1192 void *data ATTRIBUTE_UNUSED)
1194 op = get_base_address (op);
1195 if (op
1196 && DECL_P (op))
1197 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1199 return false;
1202 /* Return true iff callsite CALL has at least as many actual arguments as there
1203 are formal parameters of the function currently processed by IPA-SRA. */
1205 static inline bool
1206 callsite_has_enough_arguments_p (gimple call)
1208 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1211 /* Scan function and look for interesting expressions and create access
1212 structures for them. Return true iff any access is created. */
1214 static bool
1215 scan_function (void)
1217 basic_block bb;
1218 bool ret = false;
1220 FOR_EACH_BB (bb)
1222 gimple_stmt_iterator gsi;
1223 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1225 gimple stmt = gsi_stmt (gsi);
1226 tree t;
1227 unsigned i;
1229 if (final_bbs && stmt_can_throw_external (stmt))
1230 bitmap_set_bit (final_bbs, bb->index);
1231 switch (gimple_code (stmt))
1233 case GIMPLE_RETURN:
1234 t = gimple_return_retval (stmt);
1235 if (t != NULL_TREE)
1236 ret |= build_access_from_expr (t, stmt, false);
1237 if (final_bbs)
1238 bitmap_set_bit (final_bbs, bb->index);
1239 break;
1241 case GIMPLE_ASSIGN:
1242 ret |= build_accesses_from_assign (stmt);
1243 break;
1245 case GIMPLE_CALL:
1246 for (i = 0; i < gimple_call_num_args (stmt); i++)
1247 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1248 stmt, false);
1250 if (sra_mode == SRA_MODE_EARLY_IPA)
1252 tree dest = gimple_call_fndecl (stmt);
1253 int flags = gimple_call_flags (stmt);
1255 if (dest)
1257 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1258 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1259 encountered_apply_args = true;
1260 if (recursive_call_p (current_function_decl, dest))
1262 encountered_recursive_call = true;
1263 if (!callsite_has_enough_arguments_p (stmt))
1264 encountered_unchangable_recursive_call = true;
1268 if (final_bbs
1269 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1270 bitmap_set_bit (final_bbs, bb->index);
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;
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);
1284 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1286 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1287 ret |= build_access_from_expr (t, stmt, false);
1289 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1291 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1292 ret |= build_access_from_expr (t, stmt, true);
1294 break;
1296 default:
1297 break;
1302 return ret;
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. */
1309 static int
1310 compare_access_positions (const void *a, const void *b)
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;
1317 if (f1->offset != f2->offset)
1318 return f1->offset < f2->offset ? -1 : 1;
1320 if (f1->size == f2->size)
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);
1359 /* We want the bigger accesses first, thus the opposite operator in the next
1360 line: */
1361 return f1->size > f2->size ? -1 : 1;
1365 /* Append a name of the declaration to the name obstack. A helper function for
1366 make_fancy_name. */
1368 static void
1369 make_fancy_decl_name (tree decl)
1371 char buffer[32];
1373 tree name = DECL_NAME (decl);
1374 if (name)
1375 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1376 IDENTIFIER_LENGTH (name));
1377 else
1379 sprintf (buffer, "D%u", DECL_UID (decl));
1380 obstack_grow (&name_obstack, buffer, strlen (buffer));
1384 /* Helper for make_fancy_name. */
1386 static void
1387 make_fancy_name_1 (tree expr)
1389 char buffer[32];
1390 tree index;
1392 if (DECL_P (expr))
1394 make_fancy_decl_name (expr);
1395 return;
1398 switch (TREE_CODE (expr))
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;
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;
1418 case ADDR_EXPR:
1419 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1420 break;
1422 case MEM_REF:
1423 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1424 if (!integer_zerop (TREE_OPERAND (expr, 1)))
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));
1431 break;
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;
1443 /* Create a human readable name for replacement variable of ACCESS. */
1445 static char *
1446 make_fancy_name (tree expr)
1448 make_fancy_name_1 (expr);
1449 obstack_1grow (&name_obstack, '\0');
1450 return XOBFINISH (&name_obstack, char *);
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.
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). */
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)
1467 tree prev_base = base;
1468 tree off;
1469 tree mem_ref;
1470 HOST_WIDE_INT base_offset;
1471 unsigned HOST_WIDE_INT misalign;
1472 unsigned int align;
1474 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1475 get_object_alignment_1 (base, &align, &misalign);
1476 base = get_addr_base_and_unit_offset (base, &base_offset);
1478 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1479 offset such as array[var_index]. */
1480 if (!base)
1482 gimple stmt;
1483 tree tmp, addr;
1485 gcc_checking_assert (gsi);
1486 tmp = make_ssa_name (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1487 addr = build_fold_addr_expr (unshare_expr (prev_base));
1488 STRIP_USELESS_TYPE_CONVERSION (addr);
1489 stmt = gimple_build_assign (tmp, addr);
1490 gimple_set_location (stmt, loc);
1491 if (insert_after)
1492 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1493 else
1494 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1496 off = build_int_cst (reference_alias_ptr_type (prev_base),
1497 offset / BITS_PER_UNIT);
1498 base = tmp;
1500 else if (TREE_CODE (base) == MEM_REF)
1502 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1503 base_offset + offset / BITS_PER_UNIT);
1504 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1505 base = unshare_expr (TREE_OPERAND (base, 0));
1507 else
1509 off = build_int_cst (reference_alias_ptr_type (base),
1510 base_offset + offset / BITS_PER_UNIT);
1511 base = build_fold_addr_expr (unshare_expr (base));
1514 misalign = (misalign + offset) & (align - 1);
1515 if (misalign != 0)
1516 align = (misalign & -misalign);
1517 if (align < TYPE_ALIGN (exp_type))
1518 exp_type = build_aligned_type (exp_type, align);
1520 mem_ref = fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1521 if (TREE_THIS_VOLATILE (prev_base))
1522 TREE_THIS_VOLATILE (mem_ref) = 1;
1523 if (TREE_SIDE_EFFECTS (prev_base))
1524 TREE_SIDE_EFFECTS (mem_ref) = 1;
1525 return mem_ref;
1528 /* Construct a memory reference to a part of an aggregate BASE at the given
1529 OFFSET and of the same type as MODEL. In case this is a reference to a
1530 bit-field, the function will replicate the last component_ref of model's
1531 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1532 build_ref_for_offset. */
1534 static tree
1535 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1536 struct access *model, gimple_stmt_iterator *gsi,
1537 bool insert_after)
1539 if (TREE_CODE (model->expr) == COMPONENT_REF
1540 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1542 /* This access represents a bit-field. */
1543 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1545 offset -= int_bit_position (fld);
1546 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1547 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1548 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1549 NULL_TREE);
1551 else
1552 return build_ref_for_offset (loc, base, offset, model->type,
1553 gsi, insert_after);
1556 /* Attempt to build a memory reference that we could but into a gimple
1557 debug_bind statement. Similar to build_ref_for_model but punts if it has to
1558 create statements and return s NULL instead. This function also ignores
1559 alignment issues and so its results should never end up in non-debug
1560 statements. */
1562 static tree
1563 build_debug_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1564 struct access *model)
1566 HOST_WIDE_INT base_offset;
1567 tree off;
1569 if (TREE_CODE (model->expr) == COMPONENT_REF
1570 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1571 return NULL_TREE;
1573 base = get_addr_base_and_unit_offset (base, &base_offset);
1574 if (!base)
1575 return NULL_TREE;
1576 if (TREE_CODE (base) == MEM_REF)
1578 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1579 base_offset + offset / BITS_PER_UNIT);
1580 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1581 base = unshare_expr (TREE_OPERAND (base, 0));
1583 else
1585 off = build_int_cst (reference_alias_ptr_type (base),
1586 base_offset + offset / BITS_PER_UNIT);
1587 base = build_fold_addr_expr (unshare_expr (base));
1590 return fold_build2_loc (loc, MEM_REF, model->type, base, off);
1593 /* Construct a memory reference consisting of component_refs and array_refs to
1594 a part of an aggregate *RES (which is of type TYPE). The requested part
1595 should have type EXP_TYPE at be the given OFFSET. This function might not
1596 succeed, it returns true when it does and only then *RES points to something
1597 meaningful. This function should be used only to build expressions that we
1598 might need to present to user (e.g. in warnings). In all other situations,
1599 build_ref_for_model or build_ref_for_offset should be used instead. */
1601 static bool
1602 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1603 tree exp_type)
1605 while (1)
1607 tree fld;
1608 tree tr_size, index, minidx;
1609 HOST_WIDE_INT el_size;
1611 if (offset == 0 && exp_type
1612 && types_compatible_p (exp_type, type))
1613 return true;
1615 switch (TREE_CODE (type))
1617 case UNION_TYPE:
1618 case QUAL_UNION_TYPE:
1619 case RECORD_TYPE:
1620 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1622 HOST_WIDE_INT pos, size;
1623 tree tr_pos, expr, *expr_ptr;
1625 if (TREE_CODE (fld) != FIELD_DECL)
1626 continue;
1628 tr_pos = bit_position (fld);
1629 if (!tr_pos || !host_integerp (tr_pos, 1))
1630 continue;
1631 pos = TREE_INT_CST_LOW (tr_pos);
1632 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1633 tr_size = DECL_SIZE (fld);
1634 if (!tr_size || !host_integerp (tr_size, 1))
1635 continue;
1636 size = TREE_INT_CST_LOW (tr_size);
1637 if (size == 0)
1639 if (pos != offset)
1640 continue;
1642 else if (pos > offset || (pos + size) <= offset)
1643 continue;
1645 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1646 NULL_TREE);
1647 expr_ptr = &expr;
1648 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1649 offset - pos, exp_type))
1651 *res = expr;
1652 return true;
1655 return false;
1657 case ARRAY_TYPE:
1658 tr_size = TYPE_SIZE (TREE_TYPE (type));
1659 if (!tr_size || !host_integerp (tr_size, 1))
1660 return false;
1661 el_size = tree_low_cst (tr_size, 1);
1663 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1664 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1665 return false;
1666 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1667 if (!integer_zerop (minidx))
1668 index = int_const_binop (PLUS_EXPR, index, minidx);
1669 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1670 NULL_TREE, NULL_TREE);
1671 offset = offset % el_size;
1672 type = TREE_TYPE (type);
1673 break;
1675 default:
1676 if (offset != 0)
1677 return false;
1679 if (exp_type)
1680 return false;
1681 else
1682 return true;
1687 /* Return true iff TYPE is stdarg va_list type. */
1689 static inline bool
1690 is_va_list_type (tree type)
1692 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1695 /* Print message to dump file why a variable was rejected. */
1697 static void
1698 reject (tree var, const char *msg)
1700 if (dump_file && (dump_flags & TDF_DETAILS))
1702 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1703 print_generic_expr (dump_file, var, 0);
1704 fprintf (dump_file, "\n");
1708 /* Return true if VAR is a candidate for SRA. */
1710 static bool
1711 maybe_add_sra_candidate (tree var)
1713 tree type = TREE_TYPE (var);
1714 const char *msg;
1715 tree_node **slot;
1717 if (!AGGREGATE_TYPE_P (type))
1719 reject (var, "not aggregate");
1720 return false;
1722 if (needs_to_live_in_memory (var))
1724 reject (var, "needs to live in memory");
1725 return false;
1727 if (TREE_THIS_VOLATILE (var))
1729 reject (var, "is volatile");
1730 return false;
1732 if (!COMPLETE_TYPE_P (type))
1734 reject (var, "has incomplete type");
1735 return false;
1737 if (!host_integerp (TYPE_SIZE (type), 1))
1739 reject (var, "type size not fixed");
1740 return false;
1742 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1744 reject (var, "type size is zero");
1745 return false;
1747 if (type_internals_preclude_sra_p (type, &msg))
1749 reject (var, msg);
1750 return false;
1752 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1753 we also want to schedule it rather late. Thus we ignore it in
1754 the early pass. */
1755 (sra_mode == SRA_MODE_EARLY_INTRA
1756 && is_va_list_type (type)))
1758 reject (var, "is va_list");
1759 return false;
1762 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1763 slot = candidates.find_slot_with_hash (var, DECL_UID (var), INSERT);
1764 *slot = var;
1766 if (dump_file && (dump_flags & TDF_DETAILS))
1768 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1769 print_generic_expr (dump_file, var, 0);
1770 fprintf (dump_file, "\n");
1773 return true;
1776 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1777 those with type which is suitable for scalarization. */
1779 static bool
1780 find_var_candidates (void)
1782 tree var, parm;
1783 unsigned int i;
1784 bool ret = false;
1786 for (parm = DECL_ARGUMENTS (current_function_decl);
1787 parm;
1788 parm = DECL_CHAIN (parm))
1789 ret |= maybe_add_sra_candidate (parm);
1791 FOR_EACH_LOCAL_DECL (cfun, i, var)
1793 if (TREE_CODE (var) != VAR_DECL)
1794 continue;
1796 ret |= maybe_add_sra_candidate (var);
1799 return ret;
1802 /* Sort all accesses for the given variable, check for partial overlaps and
1803 return NULL if there are any. If there are none, pick a representative for
1804 each combination of offset and size and create a linked list out of them.
1805 Return the pointer to the first representative and make sure it is the first
1806 one in the vector of accesses. */
1808 static struct access *
1809 sort_and_splice_var_accesses (tree var)
1811 int i, j, access_count;
1812 struct access *res, **prev_acc_ptr = &res;
1813 vec<access_p> *access_vec;
1814 bool first = true;
1815 HOST_WIDE_INT low = -1, high = 0;
1817 access_vec = get_base_access_vector (var);
1818 if (!access_vec)
1819 return NULL;
1820 access_count = access_vec->length ();
1822 /* Sort by <OFFSET, SIZE>. */
1823 access_vec->qsort (compare_access_positions);
1825 i = 0;
1826 while (i < access_count)
1828 struct access *access = (*access_vec)[i];
1829 bool grp_write = access->write;
1830 bool grp_read = !access->write;
1831 bool grp_scalar_write = access->write
1832 && is_gimple_reg_type (access->type);
1833 bool grp_scalar_read = !access->write
1834 && is_gimple_reg_type (access->type);
1835 bool grp_assignment_read = access->grp_assignment_read;
1836 bool grp_assignment_write = access->grp_assignment_write;
1837 bool multiple_scalar_reads = false;
1838 bool total_scalarization = access->grp_total_scalarization;
1839 bool grp_partial_lhs = access->grp_partial_lhs;
1840 bool first_scalar = is_gimple_reg_type (access->type);
1841 bool unscalarizable_region = access->grp_unscalarizable_region;
1843 if (first || access->offset >= high)
1845 first = false;
1846 low = access->offset;
1847 high = access->offset + access->size;
1849 else if (access->offset > low && access->offset + access->size > high)
1850 return NULL;
1851 else
1852 gcc_assert (access->offset >= low
1853 && access->offset + access->size <= high);
1855 j = i + 1;
1856 while (j < access_count)
1858 struct access *ac2 = (*access_vec)[j];
1859 if (ac2->offset != access->offset || ac2->size != access->size)
1860 break;
1861 if (ac2->write)
1863 grp_write = true;
1864 grp_scalar_write = (grp_scalar_write
1865 || is_gimple_reg_type (ac2->type));
1867 else
1869 grp_read = true;
1870 if (is_gimple_reg_type (ac2->type))
1872 if (grp_scalar_read)
1873 multiple_scalar_reads = true;
1874 else
1875 grp_scalar_read = true;
1878 grp_assignment_read |= ac2->grp_assignment_read;
1879 grp_assignment_write |= ac2->grp_assignment_write;
1880 grp_partial_lhs |= ac2->grp_partial_lhs;
1881 unscalarizable_region |= ac2->grp_unscalarizable_region;
1882 total_scalarization |= ac2->grp_total_scalarization;
1883 relink_to_new_repr (access, ac2);
1885 /* If there are both aggregate-type and scalar-type accesses with
1886 this combination of size and offset, the comparison function
1887 should have put the scalars first. */
1888 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1889 ac2->group_representative = access;
1890 j++;
1893 i = j;
1895 access->group_representative = access;
1896 access->grp_write = grp_write;
1897 access->grp_read = grp_read;
1898 access->grp_scalar_read = grp_scalar_read;
1899 access->grp_scalar_write = grp_scalar_write;
1900 access->grp_assignment_read = grp_assignment_read;
1901 access->grp_assignment_write = grp_assignment_write;
1902 access->grp_hint = multiple_scalar_reads || total_scalarization;
1903 access->grp_total_scalarization = total_scalarization;
1904 access->grp_partial_lhs = grp_partial_lhs;
1905 access->grp_unscalarizable_region = unscalarizable_region;
1906 if (access->first_link)
1907 add_access_to_work_queue (access);
1909 *prev_acc_ptr = access;
1910 prev_acc_ptr = &access->next_grp;
1913 gcc_assert (res == (*access_vec)[0]);
1914 return res;
1917 /* Create a variable for the given ACCESS which determines the type, name and a
1918 few other properties. Return the variable declaration and store it also to
1919 ACCESS->replacement. */
1921 static tree
1922 create_access_replacement (struct access *access)
1924 tree repl;
1926 if (access->grp_to_be_debug_replaced)
1928 repl = create_tmp_var_raw (access->type, NULL);
1929 DECL_CONTEXT (repl) = current_function_decl;
1931 else
1932 repl = create_tmp_var (access->type, "SR");
1933 if (TREE_CODE (access->type) == COMPLEX_TYPE
1934 || TREE_CODE (access->type) == VECTOR_TYPE)
1936 if (!access->grp_partial_lhs)
1937 DECL_GIMPLE_REG_P (repl) = 1;
1939 else if (access->grp_partial_lhs
1940 && is_gimple_reg_type (access->type))
1941 TREE_ADDRESSABLE (repl) = 1;
1943 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1944 DECL_ARTIFICIAL (repl) = 1;
1945 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1947 if (DECL_NAME (access->base)
1948 && !DECL_IGNORED_P (access->base)
1949 && !DECL_ARTIFICIAL (access->base))
1951 char *pretty_name = make_fancy_name (access->expr);
1952 tree debug_expr = unshare_expr_without_location (access->expr), d;
1953 bool fail = false;
1955 DECL_NAME (repl) = get_identifier (pretty_name);
1956 obstack_free (&name_obstack, pretty_name);
1958 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1959 as DECL_DEBUG_EXPR isn't considered when looking for still
1960 used SSA_NAMEs and thus they could be freed. All debug info
1961 generation cares is whether something is constant or variable
1962 and that get_ref_base_and_extent works properly on the
1963 expression. It cannot handle accesses at a non-constant offset
1964 though, so just give up in those cases. */
1965 for (d = debug_expr;
1966 !fail && (handled_component_p (d) || TREE_CODE (d) == MEM_REF);
1967 d = TREE_OPERAND (d, 0))
1968 switch (TREE_CODE (d))
1970 case ARRAY_REF:
1971 case ARRAY_RANGE_REF:
1972 if (TREE_OPERAND (d, 1)
1973 && TREE_CODE (TREE_OPERAND (d, 1)) != INTEGER_CST)
1974 fail = true;
1975 if (TREE_OPERAND (d, 3)
1976 && TREE_CODE (TREE_OPERAND (d, 3)) != INTEGER_CST)
1977 fail = true;
1978 /* FALLTHRU */
1979 case COMPONENT_REF:
1980 if (TREE_OPERAND (d, 2)
1981 && TREE_CODE (TREE_OPERAND (d, 2)) != INTEGER_CST)
1982 fail = true;
1983 break;
1984 case MEM_REF:
1985 if (TREE_CODE (TREE_OPERAND (d, 0)) != ADDR_EXPR)
1986 fail = true;
1987 else
1988 d = TREE_OPERAND (d, 0);
1989 break;
1990 default:
1991 break;
1993 if (!fail)
1995 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1996 DECL_HAS_DEBUG_EXPR_P (repl) = 1;
1998 if (access->grp_no_warning)
1999 TREE_NO_WARNING (repl) = 1;
2000 else
2001 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
2003 else
2004 TREE_NO_WARNING (repl) = 1;
2006 if (dump_file)
2008 if (access->grp_to_be_debug_replaced)
2010 fprintf (dump_file, "Created a debug-only replacement for ");
2011 print_generic_expr (dump_file, access->base, 0);
2012 fprintf (dump_file, " offset: %u, size: %u\n",
2013 (unsigned) access->offset, (unsigned) access->size);
2015 else
2017 fprintf (dump_file, "Created a replacement for ");
2018 print_generic_expr (dump_file, access->base, 0);
2019 fprintf (dump_file, " offset: %u, size: %u: ",
2020 (unsigned) access->offset, (unsigned) access->size);
2021 print_generic_expr (dump_file, repl, 0);
2022 fprintf (dump_file, "\n");
2025 sra_stats.replacements++;
2027 return repl;
2030 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
2032 static inline tree
2033 get_access_replacement (struct access *access)
2035 gcc_checking_assert (access->replacement_decl);
2036 return access->replacement_decl;
2040 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
2041 linked list along the way. Stop when *ACCESS is NULL or the access pointed
2042 to it is not "within" the root. Return false iff some accesses partially
2043 overlap. */
2045 static bool
2046 build_access_subtree (struct access **access)
2048 struct access *root = *access, *last_child = NULL;
2049 HOST_WIDE_INT limit = root->offset + root->size;
2051 *access = (*access)->next_grp;
2052 while (*access && (*access)->offset + (*access)->size <= limit)
2054 if (!last_child)
2055 root->first_child = *access;
2056 else
2057 last_child->next_sibling = *access;
2058 last_child = *access;
2060 if (!build_access_subtree (access))
2061 return false;
2064 if (*access && (*access)->offset < limit)
2065 return false;
2067 return true;
2070 /* Build a tree of access representatives, ACCESS is the pointer to the first
2071 one, others are linked in a list by the next_grp field. Return false iff
2072 some accesses partially overlap. */
2074 static bool
2075 build_access_trees (struct access *access)
2077 while (access)
2079 struct access *root = access;
2081 if (!build_access_subtree (&access))
2082 return false;
2083 root->next_grp = access;
2085 return true;
2088 /* Return true if expr contains some ARRAY_REFs into a variable bounded
2089 array. */
2091 static bool
2092 expr_with_var_bounded_array_refs_p (tree expr)
2094 while (handled_component_p (expr))
2096 if (TREE_CODE (expr) == ARRAY_REF
2097 && !host_integerp (array_ref_low_bound (expr), 0))
2098 return true;
2099 expr = TREE_OPERAND (expr, 0);
2101 return false;
2104 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2105 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2106 sorts of access flags appropriately along the way, notably always set
2107 grp_read and grp_assign_read according to MARK_READ and grp_write when
2108 MARK_WRITE is true.
2110 Creating a replacement for a scalar access is considered beneficial if its
2111 grp_hint is set (this means we are either attempting total scalarization or
2112 there is more than one direct read access) or according to the following
2113 table:
2115 Access written to through a scalar type (once or more times)
2117 | Written to in an assignment statement
2119 | | Access read as scalar _once_
2120 | | |
2121 | | | Read in an assignment statement
2122 | | | |
2123 | | | | Scalarize Comment
2124 -----------------------------------------------------------------------------
2125 0 0 0 0 No access for the scalar
2126 0 0 0 1 No access for the scalar
2127 0 0 1 0 No Single read - won't help
2128 0 0 1 1 No The same case
2129 0 1 0 0 No access for the scalar
2130 0 1 0 1 No access for the scalar
2131 0 1 1 0 Yes s = *g; return s.i;
2132 0 1 1 1 Yes The same case as above
2133 1 0 0 0 No Won't help
2134 1 0 0 1 Yes s.i = 1; *g = s;
2135 1 0 1 0 Yes s.i = 5; g = s.i;
2136 1 0 1 1 Yes The same case as above
2137 1 1 0 0 No Won't help.
2138 1 1 0 1 Yes s.i = 1; *g = s;
2139 1 1 1 0 Yes s = *g; return s.i;
2140 1 1 1 1 Yes Any of the above yeses */
2142 static bool
2143 analyze_access_subtree (struct access *root, struct access *parent,
2144 bool allow_replacements)
2146 struct access *child;
2147 HOST_WIDE_INT limit = root->offset + root->size;
2148 HOST_WIDE_INT covered_to = root->offset;
2149 bool scalar = is_gimple_reg_type (root->type);
2150 bool hole = false, sth_created = false;
2152 if (parent)
2154 if (parent->grp_read)
2155 root->grp_read = 1;
2156 if (parent->grp_assignment_read)
2157 root->grp_assignment_read = 1;
2158 if (parent->grp_write)
2159 root->grp_write = 1;
2160 if (parent->grp_assignment_write)
2161 root->grp_assignment_write = 1;
2162 if (parent->grp_total_scalarization)
2163 root->grp_total_scalarization = 1;
2166 if (root->grp_unscalarizable_region)
2167 allow_replacements = false;
2169 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2170 allow_replacements = false;
2172 for (child = root->first_child; child; child = child->next_sibling)
2174 hole |= covered_to < child->offset;
2175 sth_created |= analyze_access_subtree (child, root,
2176 allow_replacements && !scalar);
2178 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2179 root->grp_total_scalarization &= child->grp_total_scalarization;
2180 if (child->grp_covered)
2181 covered_to += child->size;
2182 else
2183 hole = true;
2186 if (allow_replacements && scalar && !root->first_child
2187 && (root->grp_hint
2188 || ((root->grp_scalar_read || root->grp_assignment_read)
2189 && (root->grp_scalar_write || root->grp_assignment_write))))
2191 /* Always create access replacements that cover the whole access.
2192 For integral types this means the precision has to match.
2193 Avoid assumptions based on the integral type kind, too. */
2194 if (INTEGRAL_TYPE_P (root->type)
2195 && (TREE_CODE (root->type) != INTEGER_TYPE
2196 || TYPE_PRECISION (root->type) != root->size)
2197 /* But leave bitfield accesses alone. */
2198 && (TREE_CODE (root->expr) != COMPONENT_REF
2199 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2201 tree rt = root->type;
2202 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2203 && (root->size % BITS_PER_UNIT) == 0);
2204 root->type = build_nonstandard_integer_type (root->size,
2205 TYPE_UNSIGNED (rt));
2206 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2207 root->base, root->offset,
2208 root->type, NULL, false);
2210 if (dump_file && (dump_flags & TDF_DETAILS))
2212 fprintf (dump_file, "Changing the type of a replacement for ");
2213 print_generic_expr (dump_file, root->base, 0);
2214 fprintf (dump_file, " offset: %u, size: %u ",
2215 (unsigned) root->offset, (unsigned) root->size);
2216 fprintf (dump_file, " to an integer.\n");
2220 root->grp_to_be_replaced = 1;
2221 root->replacement_decl = create_access_replacement (root);
2222 sth_created = true;
2223 hole = false;
2225 else
2227 if (allow_replacements
2228 && scalar && !root->first_child
2229 && (root->grp_scalar_write || root->grp_assignment_write)
2230 && !bitmap_bit_p (cannot_scalarize_away_bitmap,
2231 DECL_UID (root->base)))
2233 gcc_checking_assert (!root->grp_scalar_read
2234 && !root->grp_assignment_read);
2235 sth_created = true;
2236 if (MAY_HAVE_DEBUG_STMTS)
2238 root->grp_to_be_debug_replaced = 1;
2239 root->replacement_decl = create_access_replacement (root);
2243 if (covered_to < limit)
2244 hole = true;
2245 if (scalar)
2246 root->grp_total_scalarization = 0;
2249 if (!hole || root->grp_total_scalarization)
2250 root->grp_covered = 1;
2251 else if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2252 root->grp_unscalarized_data = 1; /* not covered and written to */
2253 return sth_created;
2256 /* Analyze all access trees linked by next_grp by the means of
2257 analyze_access_subtree. */
2258 static bool
2259 analyze_access_trees (struct access *access)
2261 bool ret = false;
2263 while (access)
2265 if (analyze_access_subtree (access, NULL, true))
2266 ret = true;
2267 access = access->next_grp;
2270 return ret;
2273 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2274 SIZE would conflict with an already existing one. If exactly such a child
2275 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2277 static bool
2278 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2279 HOST_WIDE_INT size, struct access **exact_match)
2281 struct access *child;
2283 for (child = lacc->first_child; child; child = child->next_sibling)
2285 if (child->offset == norm_offset && child->size == size)
2287 *exact_match = child;
2288 return true;
2291 if (child->offset < norm_offset + size
2292 && child->offset + child->size > norm_offset)
2293 return true;
2296 return false;
2299 /* Create a new child access of PARENT, with all properties just like MODEL
2300 except for its offset and with its grp_write false and grp_read true.
2301 Return the new access or NULL if it cannot be created. Note that this access
2302 is created long after all splicing and sorting, it's not located in any
2303 access vector and is automatically a representative of its group. */
2305 static struct access *
2306 create_artificial_child_access (struct access *parent, struct access *model,
2307 HOST_WIDE_INT new_offset)
2309 struct access *access;
2310 struct access **child;
2311 tree expr = parent->base;
2313 gcc_assert (!model->grp_unscalarizable_region);
2315 access = (struct access *) pool_alloc (access_pool);
2316 memset (access, 0, sizeof (struct access));
2317 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2318 model->type))
2320 access->grp_no_warning = true;
2321 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2322 new_offset, model, NULL, false);
2325 access->base = parent->base;
2326 access->expr = expr;
2327 access->offset = new_offset;
2328 access->size = model->size;
2329 access->type = model->type;
2330 access->grp_write = true;
2331 access->grp_read = false;
2333 child = &parent->first_child;
2334 while (*child && (*child)->offset < new_offset)
2335 child = &(*child)->next_sibling;
2337 access->next_sibling = *child;
2338 *child = access;
2340 return access;
2344 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2345 true if any new subaccess was created. Additionally, if RACC is a scalar
2346 access but LACC is not, change the type of the latter, if possible. */
2348 static bool
2349 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2351 struct access *rchild;
2352 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2353 bool ret = false;
2355 if (is_gimple_reg_type (lacc->type)
2356 || lacc->grp_unscalarizable_region
2357 || racc->grp_unscalarizable_region)
2358 return false;
2360 if (is_gimple_reg_type (racc->type))
2362 if (!lacc->first_child && !racc->first_child)
2364 tree t = lacc->base;
2366 lacc->type = racc->type;
2367 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2368 lacc->offset, racc->type))
2369 lacc->expr = t;
2370 else
2372 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2373 lacc->base, lacc->offset,
2374 racc, NULL, false);
2375 lacc->grp_no_warning = true;
2378 return false;
2381 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2383 struct access *new_acc = NULL;
2384 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2386 if (rchild->grp_unscalarizable_region)
2387 continue;
2389 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2390 &new_acc))
2392 if (new_acc)
2394 rchild->grp_hint = 1;
2395 new_acc->grp_hint |= new_acc->grp_read;
2396 if (rchild->first_child)
2397 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2399 continue;
2402 rchild->grp_hint = 1;
2403 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2404 if (new_acc)
2406 ret = true;
2407 if (racc->first_child)
2408 propagate_subaccesses_across_link (new_acc, rchild);
2412 return ret;
2415 /* Propagate all subaccesses across assignment links. */
2417 static void
2418 propagate_all_subaccesses (void)
2420 while (work_queue_head)
2422 struct access *racc = pop_access_from_work_queue ();
2423 struct assign_link *link;
2425 gcc_assert (racc->first_link);
2427 for (link = racc->first_link; link; link = link->next)
2429 struct access *lacc = link->lacc;
2431 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2432 continue;
2433 lacc = lacc->group_representative;
2434 if (propagate_subaccesses_across_link (lacc, racc)
2435 && lacc->first_link)
2436 add_access_to_work_queue (lacc);
2441 /* Go through all accesses collected throughout the (intraprocedural) analysis
2442 stage, exclude overlapping ones, identify representatives and build trees
2443 out of them, making decisions about scalarization on the way. Return true
2444 iff there are any to-be-scalarized variables after this stage. */
2446 static bool
2447 analyze_all_variable_accesses (void)
2449 int res = 0;
2450 bitmap tmp = BITMAP_ALLOC (NULL);
2451 bitmap_iterator bi;
2452 unsigned i, max_total_scalarization_size;
2454 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2455 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2457 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2458 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2459 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2461 tree var = candidate (i);
2463 if (TREE_CODE (var) == VAR_DECL
2464 && type_consists_of_records_p (TREE_TYPE (var)))
2466 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2467 <= max_total_scalarization_size)
2469 completely_scalarize_var (var);
2470 if (dump_file && (dump_flags & TDF_DETAILS))
2472 fprintf (dump_file, "Will attempt to totally scalarize ");
2473 print_generic_expr (dump_file, var, 0);
2474 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2477 else if (dump_file && (dump_flags & TDF_DETAILS))
2479 fprintf (dump_file, "Too big to totally scalarize: ");
2480 print_generic_expr (dump_file, var, 0);
2481 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2486 bitmap_copy (tmp, candidate_bitmap);
2487 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2489 tree var = candidate (i);
2490 struct access *access;
2492 access = sort_and_splice_var_accesses (var);
2493 if (!access || !build_access_trees (access))
2494 disqualify_candidate (var,
2495 "No or inhibitingly overlapping accesses.");
2498 propagate_all_subaccesses ();
2500 bitmap_copy (tmp, candidate_bitmap);
2501 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2503 tree var = candidate (i);
2504 struct access *access = get_first_repr_for_decl (var);
2506 if (analyze_access_trees (access))
2508 res++;
2509 if (dump_file && (dump_flags & TDF_DETAILS))
2511 fprintf (dump_file, "\nAccess trees for ");
2512 print_generic_expr (dump_file, var, 0);
2513 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2514 dump_access_tree (dump_file, access);
2515 fprintf (dump_file, "\n");
2518 else
2519 disqualify_candidate (var, "No scalar replacements to be created.");
2522 BITMAP_FREE (tmp);
2524 if (res)
2526 statistics_counter_event (cfun, "Scalarized aggregates", res);
2527 return true;
2529 else
2530 return false;
2533 /* Generate statements copying scalar replacements of accesses within a subtree
2534 into or out of AGG. ACCESS, all its children, siblings and their children
2535 are to be processed. AGG is an aggregate type expression (can be a
2536 declaration but does not have to be, it can for example also be a mem_ref or
2537 a series of handled components). TOP_OFFSET is the offset of the processed
2538 subtree which has to be subtracted from offsets of individual accesses to
2539 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2540 replacements in the interval <start_offset, start_offset + chunk_size>,
2541 otherwise copy all. GSI is a statement iterator used to place the new
2542 statements. WRITE should be true when the statements should write from AGG
2543 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2544 statements will be added after the current statement in GSI, they will be
2545 added before the statement otherwise. */
2547 static void
2548 generate_subtree_copies (struct access *access, tree agg,
2549 HOST_WIDE_INT top_offset,
2550 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2551 gimple_stmt_iterator *gsi, bool write,
2552 bool insert_after, location_t loc)
2556 if (chunk_size && access->offset >= start_offset + chunk_size)
2557 return;
2559 if (access->grp_to_be_replaced
2560 && (chunk_size == 0
2561 || access->offset + access->size > start_offset))
2563 tree expr, repl = get_access_replacement (access);
2564 gimple stmt;
2566 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2567 access, gsi, insert_after);
2569 if (write)
2571 if (access->grp_partial_lhs)
2572 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2573 !insert_after,
2574 insert_after ? GSI_NEW_STMT
2575 : GSI_SAME_STMT);
2576 stmt = gimple_build_assign (repl, expr);
2578 else
2580 TREE_NO_WARNING (repl) = 1;
2581 if (access->grp_partial_lhs)
2582 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2583 !insert_after,
2584 insert_after ? GSI_NEW_STMT
2585 : GSI_SAME_STMT);
2586 stmt = gimple_build_assign (expr, repl);
2588 gimple_set_location (stmt, loc);
2590 if (insert_after)
2591 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2592 else
2593 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2594 update_stmt (stmt);
2595 sra_stats.subtree_copies++;
2597 else if (write
2598 && access->grp_to_be_debug_replaced
2599 && (chunk_size == 0
2600 || access->offset + access->size > start_offset))
2602 gimple ds;
2603 tree drhs = build_debug_ref_for_model (loc, agg,
2604 access->offset - top_offset,
2605 access);
2606 ds = gimple_build_debug_bind (get_access_replacement (access),
2607 drhs, gsi_stmt (*gsi));
2608 if (insert_after)
2609 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2610 else
2611 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2614 if (access->first_child)
2615 generate_subtree_copies (access->first_child, agg, top_offset,
2616 start_offset, chunk_size, gsi,
2617 write, insert_after, loc);
2619 access = access->next_sibling;
2621 while (access);
2624 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2625 the root of the subtree to be processed. GSI is the statement iterator used
2626 for inserting statements which are added after the current statement if
2627 INSERT_AFTER is true or before it otherwise. */
2629 static void
2630 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2631 bool insert_after, location_t loc)
2634 struct access *child;
2636 if (access->grp_to_be_replaced)
2638 gimple stmt;
2640 stmt = gimple_build_assign (get_access_replacement (access),
2641 build_zero_cst (access->type));
2642 if (insert_after)
2643 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2644 else
2645 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2646 update_stmt (stmt);
2647 gimple_set_location (stmt, loc);
2649 else if (access->grp_to_be_debug_replaced)
2651 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2652 build_zero_cst (access->type),
2653 gsi_stmt (*gsi));
2654 if (insert_after)
2655 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2656 else
2657 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2660 for (child = access->first_child; child; child = child->next_sibling)
2661 init_subtree_with_zero (child, gsi, insert_after, loc);
2664 /* Search for an access representative for the given expression EXPR and
2665 return it or NULL if it cannot be found. */
2667 static struct access *
2668 get_access_for_expr (tree expr)
2670 HOST_WIDE_INT offset, size, max_size;
2671 tree base;
2673 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2674 a different size than the size of its argument and we need the latter
2675 one. */
2676 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2677 expr = TREE_OPERAND (expr, 0);
2679 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2680 if (max_size == -1 || !DECL_P (base))
2681 return NULL;
2683 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2684 return NULL;
2686 return get_var_base_offset_size_access (base, offset, max_size);
2689 /* Replace the expression EXPR with a scalar replacement if there is one and
2690 generate other statements to do type conversion or subtree copying if
2691 necessary. GSI is used to place newly created statements, WRITE is true if
2692 the expression is being written to (it is on a LHS of a statement or output
2693 in an assembly statement). */
2695 static bool
2696 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2698 location_t loc;
2699 struct access *access;
2700 tree type, bfr;
2702 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2704 bfr = *expr;
2705 expr = &TREE_OPERAND (*expr, 0);
2707 else
2708 bfr = NULL_TREE;
2710 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2711 expr = &TREE_OPERAND (*expr, 0);
2712 access = get_access_for_expr (*expr);
2713 if (!access)
2714 return false;
2715 type = TREE_TYPE (*expr);
2717 loc = gimple_location (gsi_stmt (*gsi));
2718 if (access->grp_to_be_replaced)
2720 tree repl = get_access_replacement (access);
2721 /* If we replace a non-register typed access simply use the original
2722 access expression to extract the scalar component afterwards.
2723 This happens if scalarizing a function return value or parameter
2724 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2725 gcc.c-torture/compile/20011217-1.c.
2727 We also want to use this when accessing a complex or vector which can
2728 be accessed as a different type too, potentially creating a need for
2729 type conversion (see PR42196) and when scalarized unions are involved
2730 in assembler statements (see PR42398). */
2731 if (!useless_type_conversion_p (type, access->type))
2733 tree ref;
2735 ref = build_ref_for_model (loc, access->base, access->offset, access,
2736 NULL, false);
2738 if (write)
2740 gimple stmt;
2742 if (access->grp_partial_lhs)
2743 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2744 false, GSI_NEW_STMT);
2745 stmt = gimple_build_assign (repl, ref);
2746 gimple_set_location (stmt, loc);
2747 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2749 else
2751 gimple stmt;
2753 if (access->grp_partial_lhs)
2754 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2755 true, GSI_SAME_STMT);
2756 stmt = gimple_build_assign (ref, repl);
2757 gimple_set_location (stmt, loc);
2758 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2761 else
2762 *expr = repl;
2763 sra_stats.exprs++;
2765 else if (write && access->grp_to_be_debug_replaced)
2767 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2768 NULL_TREE,
2769 gsi_stmt (*gsi));
2770 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2773 if (access->first_child)
2775 HOST_WIDE_INT start_offset, chunk_size;
2776 if (bfr
2777 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2778 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2780 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2781 start_offset = access->offset
2782 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2784 else
2785 start_offset = chunk_size = 0;
2787 generate_subtree_copies (access->first_child, access->base, 0,
2788 start_offset, chunk_size, gsi, write, write,
2789 loc);
2791 return true;
2794 /* Where scalar replacements of the RHS have been written to when a replacement
2795 of a LHS of an assigments cannot be direclty loaded from a replacement of
2796 the RHS. */
2797 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2798 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2799 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2801 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2802 base aggregate if there are unscalarized data or directly to LHS of the
2803 statement that is pointed to by GSI otherwise. */
2805 static enum unscalarized_data_handling
2806 handle_unscalarized_data_in_subtree (struct access *top_racc,
2807 gimple_stmt_iterator *gsi)
2809 if (top_racc->grp_unscalarized_data)
2811 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2812 gsi, false, false,
2813 gimple_location (gsi_stmt (*gsi)));
2814 return SRA_UDH_RIGHT;
2816 else
2818 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2819 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2820 0, 0, gsi, false, false,
2821 gimple_location (gsi_stmt (*gsi)));
2822 return SRA_UDH_LEFT;
2827 /* Try to generate statements to load all sub-replacements in an access subtree
2828 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2829 If that is not possible, refresh the TOP_RACC base aggregate and load the
2830 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2831 copied. NEW_GSI is stmt iterator used for statement insertions after the
2832 original assignment, OLD_GSI is used to insert statements before the
2833 assignment. *REFRESHED keeps the information whether we have needed to
2834 refresh replacements of the LHS and from which side of the assignments this
2835 takes place. */
2837 static void
2838 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2839 HOST_WIDE_INT left_offset,
2840 gimple_stmt_iterator *old_gsi,
2841 gimple_stmt_iterator *new_gsi,
2842 enum unscalarized_data_handling *refreshed)
2844 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2845 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2847 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2849 if (lacc->grp_to_be_replaced)
2851 struct access *racc;
2852 gimple stmt;
2853 tree rhs;
2855 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2856 if (racc && racc->grp_to_be_replaced)
2858 rhs = get_access_replacement (racc);
2859 if (!useless_type_conversion_p (lacc->type, racc->type))
2860 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2862 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2863 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2864 true, GSI_SAME_STMT);
2866 else
2868 /* No suitable access on the right hand side, need to load from
2869 the aggregate. See if we have to update it first... */
2870 if (*refreshed == SRA_UDH_NONE)
2871 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2872 old_gsi);
2874 if (*refreshed == SRA_UDH_LEFT)
2875 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2876 new_gsi, true);
2877 else
2878 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2879 new_gsi, true);
2880 if (lacc->grp_partial_lhs)
2881 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2882 false, GSI_NEW_STMT);
2885 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2886 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2887 gimple_set_location (stmt, loc);
2888 update_stmt (stmt);
2889 sra_stats.subreplacements++;
2891 else
2893 if (*refreshed == SRA_UDH_NONE
2894 && lacc->grp_read && !lacc->grp_covered)
2895 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2896 old_gsi);
2897 if (lacc && lacc->grp_to_be_debug_replaced)
2899 gimple ds;
2900 tree drhs;
2901 struct access *racc = find_access_in_subtree (top_racc, offset,
2902 lacc->size);
2904 if (racc && racc->grp_to_be_replaced)
2906 if (racc->grp_write)
2907 drhs = get_access_replacement (racc);
2908 else
2909 drhs = NULL;
2911 else if (*refreshed == SRA_UDH_LEFT)
2912 drhs = build_debug_ref_for_model (loc, lacc->base, lacc->offset,
2913 lacc);
2914 else if (*refreshed == SRA_UDH_RIGHT)
2915 drhs = build_debug_ref_for_model (loc, top_racc->base, offset,
2916 lacc);
2917 else
2918 drhs = NULL_TREE;
2919 ds = gimple_build_debug_bind (get_access_replacement (lacc),
2920 drhs, gsi_stmt (*old_gsi));
2921 gsi_insert_after (new_gsi, ds, GSI_NEW_STMT);
2925 if (lacc->first_child)
2926 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2927 old_gsi, new_gsi, refreshed);
2931 /* Result code for SRA assignment modification. */
2932 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2933 SRA_AM_MODIFIED, /* stmt changed but not
2934 removed */
2935 SRA_AM_REMOVED }; /* stmt eliminated */
2937 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2938 to the assignment and GSI is the statement iterator pointing at it. Returns
2939 the same values as sra_modify_assign. */
2941 static enum assignment_mod_result
2942 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2944 tree lhs = gimple_assign_lhs (*stmt);
2945 struct access *acc;
2946 location_t loc;
2948 acc = get_access_for_expr (lhs);
2949 if (!acc)
2950 return SRA_AM_NONE;
2952 if (gimple_clobber_p (*stmt))
2954 /* Remove clobbers of fully scalarized variables, otherwise
2955 do nothing. */
2956 if (acc->grp_covered)
2958 unlink_stmt_vdef (*stmt);
2959 gsi_remove (gsi, true);
2960 release_defs (*stmt);
2961 return SRA_AM_REMOVED;
2963 else
2964 return SRA_AM_NONE;
2967 loc = gimple_location (*stmt);
2968 if (vec_safe_length (CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2970 /* I have never seen this code path trigger but if it can happen the
2971 following should handle it gracefully. */
2972 if (access_has_children_p (acc))
2973 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2974 true, true, loc);
2975 return SRA_AM_MODIFIED;
2978 if (acc->grp_covered)
2980 init_subtree_with_zero (acc, gsi, false, loc);
2981 unlink_stmt_vdef (*stmt);
2982 gsi_remove (gsi, true);
2983 release_defs (*stmt);
2984 return SRA_AM_REMOVED;
2986 else
2988 init_subtree_with_zero (acc, gsi, true, loc);
2989 return SRA_AM_MODIFIED;
2993 /* Create and return a new suitable default definition SSA_NAME for RACC which
2994 is an access describing an uninitialized part of an aggregate that is being
2995 loaded. */
2997 static tree
2998 get_repl_default_def_ssa_name (struct access *racc)
3000 gcc_checking_assert (!racc->grp_to_be_replaced
3001 && !racc->grp_to_be_debug_replaced);
3002 if (!racc->replacement_decl)
3003 racc->replacement_decl = create_access_replacement (racc);
3004 return get_or_create_ssa_default_def (cfun, racc->replacement_decl);
3007 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3008 bit-field field declaration somewhere in it. */
3010 static inline bool
3011 contains_vce_or_bfcref_p (const_tree ref)
3013 while (handled_component_p (ref))
3015 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3016 || (TREE_CODE (ref) == COMPONENT_REF
3017 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3018 return true;
3019 ref = TREE_OPERAND (ref, 0);
3022 return false;
3025 /* Examine both sides of the assignment statement pointed to by STMT, replace
3026 them with a scalare replacement if there is one and generate copying of
3027 replacements if scalarized aggregates have been used in the assignment. GSI
3028 is used to hold generated statements for type conversions and subtree
3029 copying. */
3031 static enum assignment_mod_result
3032 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3034 struct access *lacc, *racc;
3035 tree lhs, rhs;
3036 bool modify_this_stmt = false;
3037 bool force_gimple_rhs = false;
3038 location_t loc;
3039 gimple_stmt_iterator orig_gsi = *gsi;
3041 if (!gimple_assign_single_p (*stmt))
3042 return SRA_AM_NONE;
3043 lhs = gimple_assign_lhs (*stmt);
3044 rhs = gimple_assign_rhs1 (*stmt);
3046 if (TREE_CODE (rhs) == CONSTRUCTOR)
3047 return sra_modify_constructor_assign (stmt, gsi);
3049 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3050 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3051 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3053 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3054 gsi, false);
3055 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3056 gsi, true);
3057 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3060 lacc = get_access_for_expr (lhs);
3061 racc = get_access_for_expr (rhs);
3062 if (!lacc && !racc)
3063 return SRA_AM_NONE;
3065 loc = gimple_location (*stmt);
3066 if (lacc && lacc->grp_to_be_replaced)
3068 lhs = get_access_replacement (lacc);
3069 gimple_assign_set_lhs (*stmt, lhs);
3070 modify_this_stmt = true;
3071 if (lacc->grp_partial_lhs)
3072 force_gimple_rhs = true;
3073 sra_stats.exprs++;
3076 if (racc && racc->grp_to_be_replaced)
3078 rhs = get_access_replacement (racc);
3079 modify_this_stmt = true;
3080 if (racc->grp_partial_lhs)
3081 force_gimple_rhs = true;
3082 sra_stats.exprs++;
3084 else if (racc
3085 && !racc->grp_unscalarized_data
3086 && TREE_CODE (lhs) == SSA_NAME
3087 && !access_has_replacements_p (racc))
3089 rhs = get_repl_default_def_ssa_name (racc);
3090 modify_this_stmt = true;
3091 sra_stats.exprs++;
3094 if (modify_this_stmt)
3096 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3098 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3099 ??? This should move to fold_stmt which we simply should
3100 call after building a VIEW_CONVERT_EXPR here. */
3101 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3102 && !contains_bitfld_component_ref_p (lhs))
3104 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3105 gimple_assign_set_lhs (*stmt, lhs);
3107 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3108 && !contains_vce_or_bfcref_p (rhs))
3109 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3111 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3113 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3114 rhs);
3115 if (is_gimple_reg_type (TREE_TYPE (lhs))
3116 && TREE_CODE (lhs) != SSA_NAME)
3117 force_gimple_rhs = true;
3122 if (lacc && lacc->grp_to_be_debug_replaced)
3124 tree dlhs = get_access_replacement (lacc);
3125 tree drhs = unshare_expr (rhs);
3126 if (!useless_type_conversion_p (TREE_TYPE (dlhs), TREE_TYPE (drhs)))
3128 if (AGGREGATE_TYPE_P (TREE_TYPE (drhs))
3129 && !contains_vce_or_bfcref_p (drhs))
3130 drhs = build_debug_ref_for_model (loc, drhs, 0, lacc);
3131 if (drhs
3132 && !useless_type_conversion_p (TREE_TYPE (dlhs),
3133 TREE_TYPE (drhs)))
3134 drhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR,
3135 TREE_TYPE (dlhs), drhs);
3137 gimple ds = gimple_build_debug_bind (dlhs, drhs, *stmt);
3138 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3141 /* From this point on, the function deals with assignments in between
3142 aggregates when at least one has scalar reductions of some of its
3143 components. There are three possible scenarios: Both the LHS and RHS have
3144 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3146 In the first case, we would like to load the LHS components from RHS
3147 components whenever possible. If that is not possible, we would like to
3148 read it directly from the RHS (after updating it by storing in it its own
3149 components). If there are some necessary unscalarized data in the LHS,
3150 those will be loaded by the original assignment too. If neither of these
3151 cases happen, the original statement can be removed. Most of this is done
3152 by load_assign_lhs_subreplacements.
3154 In the second case, we would like to store all RHS scalarized components
3155 directly into LHS and if they cover the aggregate completely, remove the
3156 statement too. In the third case, we want the LHS components to be loaded
3157 directly from the RHS (DSE will remove the original statement if it
3158 becomes redundant).
3160 This is a bit complex but manageable when types match and when unions do
3161 not cause confusion in a way that we cannot really load a component of LHS
3162 from the RHS or vice versa (the access representing this level can have
3163 subaccesses that are accessible only through a different union field at a
3164 higher level - different from the one used in the examined expression).
3165 Unions are fun.
3167 Therefore, I specially handle a fourth case, happening when there is a
3168 specific type cast or it is impossible to locate a scalarized subaccess on
3169 the other side of the expression. If that happens, I simply "refresh" the
3170 RHS by storing in it is scalarized components leave the original statement
3171 there to do the copying and then load the scalar replacements of the LHS.
3172 This is what the first branch does. */
3174 if (modify_this_stmt
3175 || gimple_has_volatile_ops (*stmt)
3176 || contains_vce_or_bfcref_p (rhs)
3177 || contains_vce_or_bfcref_p (lhs))
3179 if (access_has_children_p (racc))
3180 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3181 gsi, false, false, loc);
3182 if (access_has_children_p (lacc))
3183 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3184 gsi, true, true, loc);
3185 sra_stats.separate_lhs_rhs_handling++;
3187 /* This gimplification must be done after generate_subtree_copies,
3188 lest we insert the subtree copies in the middle of the gimplified
3189 sequence. */
3190 if (force_gimple_rhs)
3191 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3192 true, GSI_SAME_STMT);
3193 if (gimple_assign_rhs1 (*stmt) != rhs)
3195 modify_this_stmt = true;
3196 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3197 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3200 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3202 else
3204 if (access_has_children_p (lacc)
3205 && access_has_children_p (racc)
3206 /* When an access represents an unscalarizable region, it usually
3207 represents accesses with variable offset and thus must not be used
3208 to generate new memory accesses. */
3209 && !lacc->grp_unscalarizable_region
3210 && !racc->grp_unscalarizable_region)
3212 gimple_stmt_iterator orig_gsi = *gsi;
3213 enum unscalarized_data_handling refreshed;
3215 if (lacc->grp_read && !lacc->grp_covered)
3216 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3217 else
3218 refreshed = SRA_UDH_NONE;
3220 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3221 &orig_gsi, gsi, &refreshed);
3222 if (refreshed != SRA_UDH_RIGHT)
3224 gsi_next (gsi);
3225 unlink_stmt_vdef (*stmt);
3226 gsi_remove (&orig_gsi, true);
3227 release_defs (*stmt);
3228 sra_stats.deleted++;
3229 return SRA_AM_REMOVED;
3232 else
3234 if (access_has_children_p (racc)
3235 && !racc->grp_unscalarized_data)
3237 if (dump_file)
3239 fprintf (dump_file, "Removing load: ");
3240 print_gimple_stmt (dump_file, *stmt, 0, 0);
3242 generate_subtree_copies (racc->first_child, lhs,
3243 racc->offset, 0, 0, gsi,
3244 false, false, loc);
3245 gcc_assert (*stmt == gsi_stmt (*gsi));
3246 unlink_stmt_vdef (*stmt);
3247 gsi_remove (gsi, true);
3248 release_defs (*stmt);
3249 sra_stats.deleted++;
3250 return SRA_AM_REMOVED;
3252 /* Restore the aggregate RHS from its components so the
3253 prevailing aggregate copy does the right thing. */
3254 if (access_has_children_p (racc))
3255 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3256 gsi, false, false, loc);
3257 /* Re-load the components of the aggregate copy destination.
3258 But use the RHS aggregate to load from to expose more
3259 optimization opportunities. */
3260 if (access_has_children_p (lacc))
3261 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3262 0, 0, gsi, true, true, loc);
3265 return SRA_AM_NONE;
3269 /* Traverse the function body and all modifications as decided in
3270 analyze_all_variable_accesses. Return true iff the CFG has been
3271 changed. */
3273 static bool
3274 sra_modify_function_body (void)
3276 bool cfg_changed = false;
3277 basic_block bb;
3279 FOR_EACH_BB (bb)
3281 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3282 while (!gsi_end_p (gsi))
3284 gimple stmt = gsi_stmt (gsi);
3285 enum assignment_mod_result assign_result;
3286 bool modified = false, deleted = false;
3287 tree *t;
3288 unsigned i;
3290 switch (gimple_code (stmt))
3292 case GIMPLE_RETURN:
3293 t = gimple_return_retval_ptr (stmt);
3294 if (*t != NULL_TREE)
3295 modified |= sra_modify_expr (t, &gsi, false);
3296 break;
3298 case GIMPLE_ASSIGN:
3299 assign_result = sra_modify_assign (&stmt, &gsi);
3300 modified |= assign_result == SRA_AM_MODIFIED;
3301 deleted = assign_result == SRA_AM_REMOVED;
3302 break;
3304 case GIMPLE_CALL:
3305 /* Operands must be processed before the lhs. */
3306 for (i = 0; i < gimple_call_num_args (stmt); i++)
3308 t = gimple_call_arg_ptr (stmt, i);
3309 modified |= sra_modify_expr (t, &gsi, false);
3312 if (gimple_call_lhs (stmt))
3314 t = gimple_call_lhs_ptr (stmt);
3315 modified |= sra_modify_expr (t, &gsi, true);
3317 break;
3319 case GIMPLE_ASM:
3320 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3322 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3323 modified |= sra_modify_expr (t, &gsi, false);
3325 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3327 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3328 modified |= sra_modify_expr (t, &gsi, true);
3330 break;
3332 default:
3333 break;
3336 if (modified)
3338 update_stmt (stmt);
3339 if (maybe_clean_eh_stmt (stmt)
3340 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3341 cfg_changed = true;
3343 if (!deleted)
3344 gsi_next (&gsi);
3348 return cfg_changed;
3351 /* Generate statements initializing scalar replacements of parts of function
3352 parameters. */
3354 static void
3355 initialize_parameter_reductions (void)
3357 gimple_stmt_iterator gsi;
3358 gimple_seq seq = NULL;
3359 tree parm;
3361 gsi = gsi_start (seq);
3362 for (parm = DECL_ARGUMENTS (current_function_decl);
3363 parm;
3364 parm = DECL_CHAIN (parm))
3366 vec<access_p> *access_vec;
3367 struct access *access;
3369 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3370 continue;
3371 access_vec = get_base_access_vector (parm);
3372 if (!access_vec)
3373 continue;
3375 for (access = (*access_vec)[0];
3376 access;
3377 access = access->next_grp)
3378 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3379 EXPR_LOCATION (parm));
3382 seq = gsi_seq (gsi);
3383 if (seq)
3384 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3387 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3388 it reveals there are components of some aggregates to be scalarized, it runs
3389 the required transformations. */
3390 static unsigned int
3391 perform_intra_sra (void)
3393 int ret = 0;
3394 sra_initialize ();
3396 if (!find_var_candidates ())
3397 goto out;
3399 if (!scan_function ())
3400 goto out;
3402 if (!analyze_all_variable_accesses ())
3403 goto out;
3405 if (sra_modify_function_body ())
3406 ret = TODO_update_ssa | TODO_cleanup_cfg;
3407 else
3408 ret = TODO_update_ssa;
3409 initialize_parameter_reductions ();
3411 statistics_counter_event (cfun, "Scalar replacements created",
3412 sra_stats.replacements);
3413 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3414 statistics_counter_event (cfun, "Subtree copy stmts",
3415 sra_stats.subtree_copies);
3416 statistics_counter_event (cfun, "Subreplacement stmts",
3417 sra_stats.subreplacements);
3418 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3419 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3420 sra_stats.separate_lhs_rhs_handling);
3422 out:
3423 sra_deinitialize ();
3424 return ret;
3427 /* Perform early intraprocedural SRA. */
3428 static unsigned int
3429 early_intra_sra (void)
3431 sra_mode = SRA_MODE_EARLY_INTRA;
3432 return perform_intra_sra ();
3435 /* Perform "late" intraprocedural SRA. */
3436 static unsigned int
3437 late_intra_sra (void)
3439 sra_mode = SRA_MODE_INTRA;
3440 return perform_intra_sra ();
3444 static bool
3445 gate_intra_sra (void)
3447 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3451 namespace {
3453 const pass_data pass_data_sra_early =
3455 GIMPLE_PASS, /* type */
3456 "esra", /* name */
3457 OPTGROUP_NONE, /* optinfo_flags */
3458 true, /* has_gate */
3459 true, /* has_execute */
3460 TV_TREE_SRA, /* tv_id */
3461 ( PROP_cfg | PROP_ssa ), /* properties_required */
3462 0, /* properties_provided */
3463 0, /* properties_destroyed */
3464 0, /* todo_flags_start */
3465 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3468 class pass_sra_early : public gimple_opt_pass
3470 public:
3471 pass_sra_early(gcc::context *ctxt)
3472 : gimple_opt_pass(pass_data_sra_early, ctxt)
3475 /* opt_pass methods: */
3476 bool gate () { return gate_intra_sra (); }
3477 unsigned int execute () { return early_intra_sra (); }
3479 }; // class pass_sra_early
3481 } // anon namespace
3483 gimple_opt_pass *
3484 make_pass_sra_early (gcc::context *ctxt)
3486 return new pass_sra_early (ctxt);
3489 namespace {
3491 const pass_data pass_data_sra =
3493 GIMPLE_PASS, /* type */
3494 "sra", /* name */
3495 OPTGROUP_NONE, /* optinfo_flags */
3496 true, /* has_gate */
3497 true, /* has_execute */
3498 TV_TREE_SRA, /* tv_id */
3499 ( PROP_cfg | PROP_ssa ), /* properties_required */
3500 0, /* properties_provided */
3501 0, /* properties_destroyed */
3502 TODO_update_address_taken, /* todo_flags_start */
3503 ( TODO_update_ssa | TODO_verify_ssa ), /* todo_flags_finish */
3506 class pass_sra : public gimple_opt_pass
3508 public:
3509 pass_sra(gcc::context *ctxt)
3510 : gimple_opt_pass(pass_data_sra, ctxt)
3513 /* opt_pass methods: */
3514 bool gate () { return gate_intra_sra (); }
3515 unsigned int execute () { return late_intra_sra (); }
3517 }; // class pass_sra
3519 } // anon namespace
3521 gimple_opt_pass *
3522 make_pass_sra (gcc::context *ctxt)
3524 return new pass_sra (ctxt);
3528 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3529 parameter. */
3531 static bool
3532 is_unused_scalar_param (tree parm)
3534 tree name;
3535 return (is_gimple_reg (parm)
3536 && (!(name = ssa_default_def (cfun, parm))
3537 || has_zero_uses (name)));
3540 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3541 examine whether there are any direct or otherwise infeasible ones. If so,
3542 return true, otherwise return false. PARM must be a gimple register with a
3543 non-NULL default definition. */
3545 static bool
3546 ptr_parm_has_direct_uses (tree parm)
3548 imm_use_iterator ui;
3549 gimple stmt;
3550 tree name = ssa_default_def (cfun, parm);
3551 bool ret = false;
3553 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3555 int uses_ok = 0;
3556 use_operand_p use_p;
3558 if (is_gimple_debug (stmt))
3559 continue;
3561 /* Valid uses include dereferences on the lhs and the rhs. */
3562 if (gimple_has_lhs (stmt))
3564 tree lhs = gimple_get_lhs (stmt);
3565 while (handled_component_p (lhs))
3566 lhs = TREE_OPERAND (lhs, 0);
3567 if (TREE_CODE (lhs) == MEM_REF
3568 && TREE_OPERAND (lhs, 0) == name
3569 && integer_zerop (TREE_OPERAND (lhs, 1))
3570 && types_compatible_p (TREE_TYPE (lhs),
3571 TREE_TYPE (TREE_TYPE (name)))
3572 && !TREE_THIS_VOLATILE (lhs))
3573 uses_ok++;
3575 if (gimple_assign_single_p (stmt))
3577 tree rhs = gimple_assign_rhs1 (stmt);
3578 while (handled_component_p (rhs))
3579 rhs = TREE_OPERAND (rhs, 0);
3580 if (TREE_CODE (rhs) == MEM_REF
3581 && TREE_OPERAND (rhs, 0) == name
3582 && integer_zerop (TREE_OPERAND (rhs, 1))
3583 && types_compatible_p (TREE_TYPE (rhs),
3584 TREE_TYPE (TREE_TYPE (name)))
3585 && !TREE_THIS_VOLATILE (rhs))
3586 uses_ok++;
3588 else if (is_gimple_call (stmt))
3590 unsigned i;
3591 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3593 tree arg = gimple_call_arg (stmt, i);
3594 while (handled_component_p (arg))
3595 arg = TREE_OPERAND (arg, 0);
3596 if (TREE_CODE (arg) == MEM_REF
3597 && TREE_OPERAND (arg, 0) == name
3598 && integer_zerop (TREE_OPERAND (arg, 1))
3599 && types_compatible_p (TREE_TYPE (arg),
3600 TREE_TYPE (TREE_TYPE (name)))
3601 && !TREE_THIS_VOLATILE (arg))
3602 uses_ok++;
3606 /* If the number of valid uses does not match the number of
3607 uses in this stmt there is an unhandled use. */
3608 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3609 --uses_ok;
3611 if (uses_ok != 0)
3612 ret = true;
3614 if (ret)
3615 BREAK_FROM_IMM_USE_STMT (ui);
3618 return ret;
3621 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3622 them in candidate_bitmap. Note that these do not necessarily include
3623 parameter which are unused and thus can be removed. Return true iff any
3624 such candidate has been found. */
3626 static bool
3627 find_param_candidates (void)
3629 tree parm;
3630 int count = 0;
3631 bool ret = false;
3632 const char *msg;
3634 for (parm = DECL_ARGUMENTS (current_function_decl);
3635 parm;
3636 parm = DECL_CHAIN (parm))
3638 tree type = TREE_TYPE (parm);
3639 tree_node **slot;
3641 count++;
3643 if (TREE_THIS_VOLATILE (parm)
3644 || TREE_ADDRESSABLE (parm)
3645 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3646 continue;
3648 if (is_unused_scalar_param (parm))
3650 ret = true;
3651 continue;
3654 if (POINTER_TYPE_P (type))
3656 type = TREE_TYPE (type);
3658 if (TREE_CODE (type) == FUNCTION_TYPE
3659 || TYPE_VOLATILE (type)
3660 || (TREE_CODE (type) == ARRAY_TYPE
3661 && TYPE_NONALIASED_COMPONENT (type))
3662 || !is_gimple_reg (parm)
3663 || is_va_list_type (type)
3664 || ptr_parm_has_direct_uses (parm))
3665 continue;
3667 else if (!AGGREGATE_TYPE_P (type))
3668 continue;
3670 if (!COMPLETE_TYPE_P (type)
3671 || !host_integerp (TYPE_SIZE (type), 1)
3672 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3673 || (AGGREGATE_TYPE_P (type)
3674 && type_internals_preclude_sra_p (type, &msg)))
3675 continue;
3677 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3678 slot = candidates.find_slot_with_hash (parm, DECL_UID (parm), INSERT);
3679 *slot = parm;
3681 ret = true;
3682 if (dump_file && (dump_flags & TDF_DETAILS))
3684 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3685 print_generic_expr (dump_file, parm, 0);
3686 fprintf (dump_file, "\n");
3690 func_param_count = count;
3691 return ret;
3694 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3695 maybe_modified. */
3697 static bool
3698 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3699 void *data)
3701 struct access *repr = (struct access *) data;
3703 repr->grp_maybe_modified = 1;
3704 return true;
3707 /* Analyze what representatives (in linked lists accessible from
3708 REPRESENTATIVES) can be modified by side effects of statements in the
3709 current function. */
3711 static void
3712 analyze_modified_params (vec<access_p> representatives)
3714 int i;
3716 for (i = 0; i < func_param_count; i++)
3718 struct access *repr;
3720 for (repr = representatives[i];
3721 repr;
3722 repr = repr->next_grp)
3724 struct access *access;
3725 bitmap visited;
3726 ao_ref ar;
3728 if (no_accesses_p (repr))
3729 continue;
3730 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3731 || repr->grp_maybe_modified)
3732 continue;
3734 ao_ref_init (&ar, repr->expr);
3735 visited = BITMAP_ALLOC (NULL);
3736 for (access = repr; access; access = access->next_sibling)
3738 /* All accesses are read ones, otherwise grp_maybe_modified would
3739 be trivially set. */
3740 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3741 mark_maybe_modified, repr, &visited);
3742 if (repr->grp_maybe_modified)
3743 break;
3745 BITMAP_FREE (visited);
3750 /* Propagate distances in bb_dereferences in the opposite direction than the
3751 control flow edges, in each step storing the maximum of the current value
3752 and the minimum of all successors. These steps are repeated until the table
3753 stabilizes. Note that BBs which might terminate the functions (according to
3754 final_bbs bitmap) never updated in this way. */
3756 static void
3757 propagate_dereference_distances (void)
3759 vec<basic_block> queue;
3760 basic_block bb;
3762 queue.create (last_basic_block_for_function (cfun));
3763 queue.quick_push (ENTRY_BLOCK_PTR);
3764 FOR_EACH_BB (bb)
3766 queue.quick_push (bb);
3767 bb->aux = bb;
3770 while (!queue.is_empty ())
3772 edge_iterator ei;
3773 edge e;
3774 bool change = false;
3775 int i;
3777 bb = queue.pop ();
3778 bb->aux = NULL;
3780 if (bitmap_bit_p (final_bbs, bb->index))
3781 continue;
3783 for (i = 0; i < func_param_count; i++)
3785 int idx = bb->index * func_param_count + i;
3786 bool first = true;
3787 HOST_WIDE_INT inh = 0;
3789 FOR_EACH_EDGE (e, ei, bb->succs)
3791 int succ_idx = e->dest->index * func_param_count + i;
3793 if (e->src == EXIT_BLOCK_PTR)
3794 continue;
3796 if (first)
3798 first = false;
3799 inh = bb_dereferences [succ_idx];
3801 else if (bb_dereferences [succ_idx] < inh)
3802 inh = bb_dereferences [succ_idx];
3805 if (!first && bb_dereferences[idx] < inh)
3807 bb_dereferences[idx] = inh;
3808 change = true;
3812 if (change && !bitmap_bit_p (final_bbs, bb->index))
3813 FOR_EACH_EDGE (e, ei, bb->preds)
3815 if (e->src->aux)
3816 continue;
3818 e->src->aux = e->src;
3819 queue.quick_push (e->src);
3823 queue.release ();
3826 /* Dump a dereferences TABLE with heading STR to file F. */
3828 static void
3829 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3831 basic_block bb;
3833 fprintf (dump_file, str);
3834 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3836 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3837 if (bb != EXIT_BLOCK_PTR)
3839 int i;
3840 for (i = 0; i < func_param_count; i++)
3842 int idx = bb->index * func_param_count + i;
3843 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3846 fprintf (f, "\n");
3848 fprintf (dump_file, "\n");
3851 /* Determine what (parts of) parameters passed by reference that are not
3852 assigned to are not certainly dereferenced in this function and thus the
3853 dereferencing cannot be safely moved to the caller without potentially
3854 introducing a segfault. Mark such REPRESENTATIVES as
3855 grp_not_necessarilly_dereferenced.
3857 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3858 part is calculated rather than simple booleans are calculated for each
3859 pointer parameter to handle cases when only a fraction of the whole
3860 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3861 an example).
3863 The maximum dereference distances for each pointer parameter and BB are
3864 already stored in bb_dereference. This routine simply propagates these
3865 values upwards by propagate_dereference_distances and then compares the
3866 distances of individual parameters in the ENTRY BB to the equivalent
3867 distances of each representative of a (fraction of a) parameter. */
3869 static void
3870 analyze_caller_dereference_legality (vec<access_p> representatives)
3872 int i;
3874 if (dump_file && (dump_flags & TDF_DETAILS))
3875 dump_dereferences_table (dump_file,
3876 "Dereference table before propagation:\n",
3877 bb_dereferences);
3879 propagate_dereference_distances ();
3881 if (dump_file && (dump_flags & TDF_DETAILS))
3882 dump_dereferences_table (dump_file,
3883 "Dereference table after propagation:\n",
3884 bb_dereferences);
3886 for (i = 0; i < func_param_count; i++)
3888 struct access *repr = representatives[i];
3889 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3891 if (!repr || no_accesses_p (repr))
3892 continue;
3896 if ((repr->offset + repr->size) > bb_dereferences[idx])
3897 repr->grp_not_necessarilly_dereferenced = 1;
3898 repr = repr->next_grp;
3900 while (repr);
3904 /* Return the representative access for the parameter declaration PARM if it is
3905 a scalar passed by reference which is not written to and the pointer value
3906 is not used directly. Thus, if it is legal to dereference it in the caller
3907 and we can rule out modifications through aliases, such parameter should be
3908 turned into one passed by value. Return NULL otherwise. */
3910 static struct access *
3911 unmodified_by_ref_scalar_representative (tree parm)
3913 int i, access_count;
3914 struct access *repr;
3915 vec<access_p> *access_vec;
3917 access_vec = get_base_access_vector (parm);
3918 gcc_assert (access_vec);
3919 repr = (*access_vec)[0];
3920 if (repr->write)
3921 return NULL;
3922 repr->group_representative = repr;
3924 access_count = access_vec->length ();
3925 for (i = 1; i < access_count; i++)
3927 struct access *access = (*access_vec)[i];
3928 if (access->write)
3929 return NULL;
3930 access->group_representative = repr;
3931 access->next_sibling = repr->next_sibling;
3932 repr->next_sibling = access;
3935 repr->grp_read = 1;
3936 repr->grp_scalar_ptr = 1;
3937 return repr;
3940 /* Return true iff this ACCESS precludes IPA-SRA of the parameter it is
3941 associated with. REQ_ALIGN is the minimum required alignment. */
3943 static bool
3944 access_precludes_ipa_sra_p (struct access *access, unsigned int req_align)
3946 unsigned int exp_align;
3947 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3948 is incompatible assign in a call statement (and possibly even in asm
3949 statements). This can be relaxed by using a new temporary but only for
3950 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3951 intraprocedural SRA we deal with this by keeping the old aggregate around,
3952 something we cannot do in IPA-SRA.) */
3953 if (access->write
3954 && (is_gimple_call (access->stmt)
3955 || gimple_code (access->stmt) == GIMPLE_ASM))
3956 return true;
3958 exp_align = get_object_alignment (access->expr);
3959 if (exp_align < req_align)
3960 return true;
3962 return false;
3966 /* Sort collected accesses for parameter PARM, identify representatives for
3967 each accessed region and link them together. Return NULL if there are
3968 different but overlapping accesses, return the special ptr value meaning
3969 there are no accesses for this parameter if that is the case and return the
3970 first representative otherwise. Set *RO_GRP if there is a group of accesses
3971 with only read (i.e. no write) accesses. */
3973 static struct access *
3974 splice_param_accesses (tree parm, bool *ro_grp)
3976 int i, j, access_count, group_count;
3977 int agg_size, total_size = 0;
3978 struct access *access, *res, **prev_acc_ptr = &res;
3979 vec<access_p> *access_vec;
3981 access_vec = get_base_access_vector (parm);
3982 if (!access_vec)
3983 return &no_accesses_representant;
3984 access_count = access_vec->length ();
3986 access_vec->qsort (compare_access_positions);
3988 i = 0;
3989 total_size = 0;
3990 group_count = 0;
3991 while (i < access_count)
3993 bool modification;
3994 tree a1_alias_type;
3995 access = (*access_vec)[i];
3996 modification = access->write;
3997 if (access_precludes_ipa_sra_p (access, TYPE_ALIGN (access->type)))
3998 return NULL;
3999 a1_alias_type = reference_alias_ptr_type (access->expr);
4001 /* Access is about to become group representative unless we find some
4002 nasty overlap which would preclude us from breaking this parameter
4003 apart. */
4005 j = i + 1;
4006 while (j < access_count)
4008 struct access *ac2 = (*access_vec)[j];
4009 if (ac2->offset != access->offset)
4011 /* All or nothing law for parameters. */
4012 if (access->offset + access->size > ac2->offset)
4013 return NULL;
4014 else
4015 break;
4017 else if (ac2->size != access->size)
4018 return NULL;
4020 if (access_precludes_ipa_sra_p (ac2, TYPE_ALIGN (access->type))
4021 || (ac2->type != access->type
4022 && (TREE_ADDRESSABLE (ac2->type)
4023 || TREE_ADDRESSABLE (access->type)))
4024 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
4025 return NULL;
4027 modification |= ac2->write;
4028 ac2->group_representative = access;
4029 ac2->next_sibling = access->next_sibling;
4030 access->next_sibling = ac2;
4031 j++;
4034 group_count++;
4035 access->grp_maybe_modified = modification;
4036 if (!modification)
4037 *ro_grp = true;
4038 *prev_acc_ptr = access;
4039 prev_acc_ptr = &access->next_grp;
4040 total_size += access->size;
4041 i = j;
4044 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4045 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4046 else
4047 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4048 if (total_size >= agg_size)
4049 return NULL;
4051 gcc_assert (group_count > 0);
4052 return res;
4055 /* Decide whether parameters with representative accesses given by REPR should
4056 be reduced into components. */
4058 static int
4059 decide_one_param_reduction (struct access *repr)
4061 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4062 bool by_ref;
4063 tree parm;
4065 parm = repr->base;
4066 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4067 gcc_assert (cur_parm_size > 0);
4069 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4071 by_ref = true;
4072 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4074 else
4076 by_ref = false;
4077 agg_size = cur_parm_size;
4080 if (dump_file)
4082 struct access *acc;
4083 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4084 print_generic_expr (dump_file, parm, 0);
4085 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4086 for (acc = repr; acc; acc = acc->next_grp)
4087 dump_access (dump_file, acc, true);
4090 total_size = 0;
4091 new_param_count = 0;
4093 for (; repr; repr = repr->next_grp)
4095 gcc_assert (parm == repr->base);
4097 /* Taking the address of a non-addressable field is verboten. */
4098 if (by_ref && repr->non_addressable)
4099 return 0;
4101 /* Do not decompose a non-BLKmode param in a way that would
4102 create BLKmode params. Especially for by-reference passing
4103 (thus, pointer-type param) this is hardly worthwhile. */
4104 if (DECL_MODE (parm) != BLKmode
4105 && TYPE_MODE (repr->type) == BLKmode)
4106 return 0;
4108 if (!by_ref || (!repr->grp_maybe_modified
4109 && !repr->grp_not_necessarilly_dereferenced))
4110 total_size += repr->size;
4111 else
4112 total_size += cur_parm_size;
4114 new_param_count++;
4117 gcc_assert (new_param_count > 0);
4119 if (optimize_function_for_size_p (cfun))
4120 parm_size_limit = cur_parm_size;
4121 else
4122 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4123 * cur_parm_size);
4125 if (total_size < agg_size
4126 && total_size <= parm_size_limit)
4128 if (dump_file)
4129 fprintf (dump_file, " ....will be split into %i components\n",
4130 new_param_count);
4131 return new_param_count;
4133 else
4134 return 0;
4137 /* The order of the following enums is important, we need to do extra work for
4138 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4139 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4140 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4142 /* Identify representatives of all accesses to all candidate parameters for
4143 IPA-SRA. Return result based on what representatives have been found. */
4145 static enum ipa_splicing_result
4146 splice_all_param_accesses (vec<access_p> &representatives)
4148 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4149 tree parm;
4150 struct access *repr;
4152 representatives.create (func_param_count);
4154 for (parm = DECL_ARGUMENTS (current_function_decl);
4155 parm;
4156 parm = DECL_CHAIN (parm))
4158 if (is_unused_scalar_param (parm))
4160 representatives.quick_push (&no_accesses_representant);
4161 if (result == NO_GOOD_ACCESS)
4162 result = UNUSED_PARAMS;
4164 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4165 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4166 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4168 repr = unmodified_by_ref_scalar_representative (parm);
4169 representatives.quick_push (repr);
4170 if (repr)
4171 result = UNMODIF_BY_REF_ACCESSES;
4173 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4175 bool ro_grp = false;
4176 repr = splice_param_accesses (parm, &ro_grp);
4177 representatives.quick_push (repr);
4179 if (repr && !no_accesses_p (repr))
4181 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4183 if (ro_grp)
4184 result = UNMODIF_BY_REF_ACCESSES;
4185 else if (result < MODIF_BY_REF_ACCESSES)
4186 result = MODIF_BY_REF_ACCESSES;
4188 else if (result < BY_VAL_ACCESSES)
4189 result = BY_VAL_ACCESSES;
4191 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4192 result = UNUSED_PARAMS;
4194 else
4195 representatives.quick_push (NULL);
4198 if (result == NO_GOOD_ACCESS)
4200 representatives.release ();
4201 return NO_GOOD_ACCESS;
4204 return result;
4207 /* Return the index of BASE in PARMS. Abort if it is not found. */
4209 static inline int
4210 get_param_index (tree base, vec<tree> parms)
4212 int i, len;
4214 len = parms.length ();
4215 for (i = 0; i < len; i++)
4216 if (parms[i] == base)
4217 return i;
4218 gcc_unreachable ();
4221 /* Convert the decisions made at the representative level into compact
4222 parameter adjustments. REPRESENTATIVES are pointers to first
4223 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4224 final number of adjustments. */
4226 static ipa_parm_adjustment_vec
4227 turn_representatives_into_adjustments (vec<access_p> representatives,
4228 int adjustments_count)
4230 vec<tree> parms;
4231 ipa_parm_adjustment_vec adjustments;
4232 tree parm;
4233 int i;
4235 gcc_assert (adjustments_count > 0);
4236 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4237 adjustments.create (adjustments_count);
4238 parm = DECL_ARGUMENTS (current_function_decl);
4239 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4241 struct access *repr = representatives[i];
4243 if (!repr || no_accesses_p (repr))
4245 struct ipa_parm_adjustment adj;
4247 memset (&adj, 0, sizeof (adj));
4248 adj.base_index = get_param_index (parm, parms);
4249 adj.base = parm;
4250 if (!repr)
4251 adj.copy_param = 1;
4252 else
4253 adj.remove_param = 1;
4254 adjustments.quick_push (adj);
4256 else
4258 struct ipa_parm_adjustment adj;
4259 int index = get_param_index (parm, parms);
4261 for (; repr; repr = repr->next_grp)
4263 memset (&adj, 0, sizeof (adj));
4264 gcc_assert (repr->base == parm);
4265 adj.base_index = index;
4266 adj.base = repr->base;
4267 adj.type = repr->type;
4268 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4269 adj.offset = repr->offset;
4270 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4271 && (repr->grp_maybe_modified
4272 || repr->grp_not_necessarilly_dereferenced));
4273 adjustments.quick_push (adj);
4277 parms.release ();
4278 return adjustments;
4281 /* Analyze the collected accesses and produce a plan what to do with the
4282 parameters in the form of adjustments, NULL meaning nothing. */
4284 static ipa_parm_adjustment_vec
4285 analyze_all_param_acesses (void)
4287 enum ipa_splicing_result repr_state;
4288 bool proceed = false;
4289 int i, adjustments_count = 0;
4290 vec<access_p> representatives;
4291 ipa_parm_adjustment_vec adjustments;
4293 repr_state = splice_all_param_accesses (representatives);
4294 if (repr_state == NO_GOOD_ACCESS)
4295 return ipa_parm_adjustment_vec();
4297 /* If there are any parameters passed by reference which are not modified
4298 directly, we need to check whether they can be modified indirectly. */
4299 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4301 analyze_caller_dereference_legality (representatives);
4302 analyze_modified_params (representatives);
4305 for (i = 0; i < func_param_count; i++)
4307 struct access *repr = representatives[i];
4309 if (repr && !no_accesses_p (repr))
4311 if (repr->grp_scalar_ptr)
4313 adjustments_count++;
4314 if (repr->grp_not_necessarilly_dereferenced
4315 || repr->grp_maybe_modified)
4316 representatives[i] = NULL;
4317 else
4319 proceed = true;
4320 sra_stats.scalar_by_ref_to_by_val++;
4323 else
4325 int new_components = decide_one_param_reduction (repr);
4327 if (new_components == 0)
4329 representatives[i] = NULL;
4330 adjustments_count++;
4332 else
4334 adjustments_count += new_components;
4335 sra_stats.aggregate_params_reduced++;
4336 sra_stats.param_reductions_created += new_components;
4337 proceed = true;
4341 else
4343 if (no_accesses_p (repr))
4345 proceed = true;
4346 sra_stats.deleted_unused_parameters++;
4348 adjustments_count++;
4352 if (!proceed && dump_file)
4353 fprintf (dump_file, "NOT proceeding to change params.\n");
4355 if (proceed)
4356 adjustments = turn_representatives_into_adjustments (representatives,
4357 adjustments_count);
4358 else
4359 adjustments = ipa_parm_adjustment_vec();
4361 representatives.release ();
4362 return adjustments;
4365 /* If a parameter replacement identified by ADJ does not yet exist in the form
4366 of declaration, create it and record it, otherwise return the previously
4367 created one. */
4369 static tree
4370 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4372 tree repl;
4373 if (!adj->new_ssa_base)
4375 char *pretty_name = make_fancy_name (adj->base);
4377 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4378 DECL_NAME (repl) = get_identifier (pretty_name);
4379 obstack_free (&name_obstack, pretty_name);
4381 adj->new_ssa_base = repl;
4383 else
4384 repl = adj->new_ssa_base;
4385 return repl;
4388 /* Find the first adjustment for a particular parameter BASE in a vector of
4389 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4390 adjustment. */
4392 static struct ipa_parm_adjustment *
4393 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4395 int i, len;
4397 len = adjustments.length ();
4398 for (i = 0; i < len; i++)
4400 struct ipa_parm_adjustment *adj;
4402 adj = &adjustments[i];
4403 if (!adj->copy_param && adj->base == base)
4404 return adj;
4407 return NULL;
4410 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4411 removed because its value is not used, replace the SSA_NAME with a one
4412 relating to a created VAR_DECL together all of its uses and return true.
4413 ADJUSTMENTS is a pointer to an adjustments vector. */
4415 static bool
4416 replace_removed_params_ssa_names (gimple stmt,
4417 ipa_parm_adjustment_vec adjustments)
4419 struct ipa_parm_adjustment *adj;
4420 tree lhs, decl, repl, name;
4422 if (gimple_code (stmt) == GIMPLE_PHI)
4423 lhs = gimple_phi_result (stmt);
4424 else if (is_gimple_assign (stmt))
4425 lhs = gimple_assign_lhs (stmt);
4426 else if (is_gimple_call (stmt))
4427 lhs = gimple_call_lhs (stmt);
4428 else
4429 gcc_unreachable ();
4431 if (TREE_CODE (lhs) != SSA_NAME)
4432 return false;
4434 decl = SSA_NAME_VAR (lhs);
4435 if (decl == NULL_TREE
4436 || TREE_CODE (decl) != PARM_DECL)
4437 return false;
4439 adj = get_adjustment_for_base (adjustments, decl);
4440 if (!adj)
4441 return false;
4443 repl = get_replaced_param_substitute (adj);
4444 name = make_ssa_name (repl, stmt);
4446 if (dump_file)
4448 fprintf (dump_file, "replacing an SSA name of a removed param ");
4449 print_generic_expr (dump_file, lhs, 0);
4450 fprintf (dump_file, " with ");
4451 print_generic_expr (dump_file, name, 0);
4452 fprintf (dump_file, "\n");
4455 if (is_gimple_assign (stmt))
4456 gimple_assign_set_lhs (stmt, name);
4457 else if (is_gimple_call (stmt))
4458 gimple_call_set_lhs (stmt, name);
4459 else
4460 gimple_phi_set_result (stmt, name);
4462 replace_uses_by (lhs, name);
4463 release_ssa_name (lhs);
4464 return true;
4467 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4468 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4469 specifies whether the function should care about type incompatibility the
4470 current and new expressions. If it is false, the function will leave
4471 incompatibility issues to the caller. Return true iff the expression
4472 was modified. */
4474 static bool
4475 sra_ipa_modify_expr (tree *expr, bool convert,
4476 ipa_parm_adjustment_vec adjustments)
4478 int i, len;
4479 struct ipa_parm_adjustment *adj, *cand = NULL;
4480 HOST_WIDE_INT offset, size, max_size;
4481 tree base, src;
4483 len = adjustments.length ();
4485 if (TREE_CODE (*expr) == BIT_FIELD_REF
4486 || TREE_CODE (*expr) == IMAGPART_EXPR
4487 || TREE_CODE (*expr) == REALPART_EXPR)
4489 expr = &TREE_OPERAND (*expr, 0);
4490 convert = true;
4493 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4494 if (!base || size == -1 || max_size == -1)
4495 return false;
4497 if (TREE_CODE (base) == MEM_REF)
4499 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4500 base = TREE_OPERAND (base, 0);
4503 base = get_ssa_base_param (base);
4504 if (!base || TREE_CODE (base) != PARM_DECL)
4505 return false;
4507 for (i = 0; i < len; i++)
4509 adj = &adjustments[i];
4511 if (adj->base == base
4512 && (adj->offset == offset || adj->remove_param))
4514 cand = adj;
4515 break;
4518 if (!cand || cand->copy_param || cand->remove_param)
4519 return false;
4521 if (cand->by_ref)
4522 src = build_simple_mem_ref (cand->reduction);
4523 else
4524 src = cand->reduction;
4526 if (dump_file && (dump_flags & TDF_DETAILS))
4528 fprintf (dump_file, "About to replace expr ");
4529 print_generic_expr (dump_file, *expr, 0);
4530 fprintf (dump_file, " with ");
4531 print_generic_expr (dump_file, src, 0);
4532 fprintf (dump_file, "\n");
4535 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4537 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4538 *expr = vce;
4540 else
4541 *expr = src;
4542 return true;
4545 /* If the statement pointed to by STMT_PTR contains any expressions that need
4546 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4547 potential type incompatibilities (GSI is used to accommodate conversion
4548 statements and must point to the statement). Return true iff the statement
4549 was modified. */
4551 static bool
4552 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4553 ipa_parm_adjustment_vec adjustments)
4555 gimple stmt = *stmt_ptr;
4556 tree *lhs_p, *rhs_p;
4557 bool any;
4559 if (!gimple_assign_single_p (stmt))
4560 return false;
4562 rhs_p = gimple_assign_rhs1_ptr (stmt);
4563 lhs_p = gimple_assign_lhs_ptr (stmt);
4565 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4566 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4567 if (any)
4569 tree new_rhs = NULL_TREE;
4571 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4573 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4575 /* V_C_Es of constructors can cause trouble (PR 42714). */
4576 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4577 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4578 else
4579 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4580 NULL);
4582 else
4583 new_rhs = fold_build1_loc (gimple_location (stmt),
4584 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4585 *rhs_p);
4587 else if (REFERENCE_CLASS_P (*rhs_p)
4588 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4589 && !is_gimple_reg (*lhs_p))
4590 /* This can happen when an assignment in between two single field
4591 structures is turned into an assignment in between two pointers to
4592 scalars (PR 42237). */
4593 new_rhs = *rhs_p;
4595 if (new_rhs)
4597 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4598 true, GSI_SAME_STMT);
4600 gimple_assign_set_rhs_from_tree (gsi, tmp);
4603 return true;
4606 return false;
4609 /* Traverse the function body and all modifications as described in
4610 ADJUSTMENTS. Return true iff the CFG has been changed. */
4612 static bool
4613 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4615 bool cfg_changed = false;
4616 basic_block bb;
4618 FOR_EACH_BB (bb)
4620 gimple_stmt_iterator gsi;
4622 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4623 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4625 gsi = gsi_start_bb (bb);
4626 while (!gsi_end_p (gsi))
4628 gimple stmt = gsi_stmt (gsi);
4629 bool modified = false;
4630 tree *t;
4631 unsigned i;
4633 switch (gimple_code (stmt))
4635 case GIMPLE_RETURN:
4636 t = gimple_return_retval_ptr (stmt);
4637 if (*t != NULL_TREE)
4638 modified |= sra_ipa_modify_expr (t, true, adjustments);
4639 break;
4641 case GIMPLE_ASSIGN:
4642 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4643 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4644 break;
4646 case GIMPLE_CALL:
4647 /* Operands must be processed before the lhs. */
4648 for (i = 0; i < gimple_call_num_args (stmt); i++)
4650 t = gimple_call_arg_ptr (stmt, i);
4651 modified |= sra_ipa_modify_expr (t, true, adjustments);
4654 if (gimple_call_lhs (stmt))
4656 t = gimple_call_lhs_ptr (stmt);
4657 modified |= sra_ipa_modify_expr (t, false, adjustments);
4658 modified |= replace_removed_params_ssa_names (stmt,
4659 adjustments);
4661 break;
4663 case GIMPLE_ASM:
4664 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4666 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4667 modified |= sra_ipa_modify_expr (t, true, adjustments);
4669 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4671 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4672 modified |= sra_ipa_modify_expr (t, false, adjustments);
4674 break;
4676 default:
4677 break;
4680 if (modified)
4682 update_stmt (stmt);
4683 if (maybe_clean_eh_stmt (stmt)
4684 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4685 cfg_changed = true;
4687 gsi_next (&gsi);
4691 return cfg_changed;
4694 /* Call gimple_debug_bind_reset_value on all debug statements describing
4695 gimple register parameters that are being removed or replaced. */
4697 static void
4698 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4700 int i, len;
4701 gimple_stmt_iterator *gsip = NULL, gsi;
4703 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4705 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4706 gsip = &gsi;
4708 len = adjustments.length ();
4709 for (i = 0; i < len; i++)
4711 struct ipa_parm_adjustment *adj;
4712 imm_use_iterator ui;
4713 gimple stmt, def_temp;
4714 tree name, vexpr, copy = NULL_TREE;
4715 use_operand_p use_p;
4717 adj = &adjustments[i];
4718 if (adj->copy_param || !is_gimple_reg (adj->base))
4719 continue;
4720 name = ssa_default_def (cfun, adj->base);
4721 vexpr = NULL;
4722 if (name)
4723 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4725 if (gimple_clobber_p (stmt))
4727 gimple_stmt_iterator cgsi = gsi_for_stmt (stmt);
4728 unlink_stmt_vdef (stmt);
4729 gsi_remove (&cgsi, true);
4730 release_defs (stmt);
4731 continue;
4733 /* All other users must have been removed by
4734 ipa_sra_modify_function_body. */
4735 gcc_assert (is_gimple_debug (stmt));
4736 if (vexpr == NULL && gsip != NULL)
4738 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4739 vexpr = make_node (DEBUG_EXPR_DECL);
4740 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4741 NULL);
4742 DECL_ARTIFICIAL (vexpr) = 1;
4743 TREE_TYPE (vexpr) = TREE_TYPE (name);
4744 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4745 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4747 if (vexpr)
4749 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4750 SET_USE (use_p, vexpr);
4752 else
4753 gimple_debug_bind_reset_value (stmt);
4754 update_stmt (stmt);
4756 /* Create a VAR_DECL for debug info purposes. */
4757 if (!DECL_IGNORED_P (adj->base))
4759 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4760 VAR_DECL, DECL_NAME (adj->base),
4761 TREE_TYPE (adj->base));
4762 if (DECL_PT_UID_SET_P (adj->base))
4763 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4764 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4765 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4766 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4767 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4768 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4769 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4770 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4771 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4772 SET_DECL_RTL (copy, 0);
4773 TREE_USED (copy) = 1;
4774 DECL_CONTEXT (copy) = current_function_decl;
4775 add_local_decl (cfun, copy);
4776 DECL_CHAIN (copy) =
4777 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4778 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4780 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4782 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4783 if (vexpr)
4784 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4785 else
4786 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4787 NULL);
4788 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4793 /* Return false iff all callers have at least as many actual arguments as there
4794 are formal parameters in the current function. */
4796 static bool
4797 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4798 void *data ATTRIBUTE_UNUSED)
4800 struct cgraph_edge *cs;
4801 for (cs = node->callers; cs; cs = cs->next_caller)
4802 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4803 return true;
4805 return false;
4808 /* Convert all callers of NODE. */
4810 static bool
4811 convert_callers_for_node (struct cgraph_node *node,
4812 void *data)
4814 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4815 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4816 struct cgraph_edge *cs;
4818 for (cs = node->callers; cs; cs = cs->next_caller)
4820 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4822 if (dump_file)
4823 fprintf (dump_file, "Adjusting call %s/%i -> %s/%i\n",
4824 xstrdup (cgraph_node_name (cs->caller)),
4825 cs->caller->symbol.order,
4826 xstrdup (cgraph_node_name (cs->callee)),
4827 cs->callee->symbol.order);
4829 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4831 pop_cfun ();
4834 for (cs = node->callers; cs; cs = cs->next_caller)
4835 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4836 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4837 compute_inline_parameters (cs->caller, true);
4838 BITMAP_FREE (recomputed_callers);
4840 return true;
4843 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4845 static void
4846 convert_callers (struct cgraph_node *node, tree old_decl,
4847 ipa_parm_adjustment_vec adjustments)
4849 basic_block this_block;
4851 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4852 &adjustments, false);
4854 if (!encountered_recursive_call)
4855 return;
4857 FOR_EACH_BB (this_block)
4859 gimple_stmt_iterator gsi;
4861 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4863 gimple stmt = gsi_stmt (gsi);
4864 tree call_fndecl;
4865 if (gimple_code (stmt) != GIMPLE_CALL)
4866 continue;
4867 call_fndecl = gimple_call_fndecl (stmt);
4868 if (call_fndecl == old_decl)
4870 if (dump_file)
4871 fprintf (dump_file, "Adjusting recursive call");
4872 gimple_call_set_fndecl (stmt, node->symbol.decl);
4873 ipa_modify_call_arguments (NULL, stmt, adjustments);
4878 return;
4881 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4882 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4884 static bool
4885 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4887 struct cgraph_node *new_node;
4888 bool cfg_changed;
4889 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4891 rebuild_cgraph_edges ();
4892 free_dominance_info (CDI_DOMINATORS);
4893 pop_cfun ();
4895 new_node = cgraph_function_versioning (node, redirect_callers,
4896 NULL,
4897 NULL, false, NULL, NULL, "isra");
4898 redirect_callers.release ();
4900 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4901 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4902 cfg_changed = ipa_sra_modify_function_body (adjustments);
4903 sra_ipa_reset_debug_stmts (adjustments);
4904 convert_callers (new_node, node->symbol.decl, adjustments);
4905 cgraph_make_node_local (new_node);
4906 return cfg_changed;
4909 /* If NODE has a caller, return true. */
4911 static bool
4912 has_caller_p (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
4914 if (node->callers)
4915 return true;
4916 return false;
4919 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4920 attributes, return true otherwise. NODE is the cgraph node of the current
4921 function. */
4923 static bool
4924 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4926 if (!cgraph_node_can_be_local_p (node))
4928 if (dump_file)
4929 fprintf (dump_file, "Function not local to this compilation unit.\n");
4930 return false;
4933 if (!node->local.can_change_signature)
4935 if (dump_file)
4936 fprintf (dump_file, "Function can not change signature.\n");
4937 return false;
4940 if (!tree_versionable_function_p (node->symbol.decl))
4942 if (dump_file)
4943 fprintf (dump_file, "Function is not versionable.\n");
4944 return false;
4947 if (DECL_VIRTUAL_P (current_function_decl))
4949 if (dump_file)
4950 fprintf (dump_file, "Function is a virtual method.\n");
4951 return false;
4954 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4955 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4957 if (dump_file)
4958 fprintf (dump_file, "Function too big to be made truly local.\n");
4959 return false;
4962 if (!cgraph_for_node_and_aliases (node, has_caller_p, NULL, true))
4964 if (dump_file)
4965 fprintf (dump_file,
4966 "Function has no callers in this compilation unit.\n");
4967 return false;
4970 if (cfun->stdarg)
4972 if (dump_file)
4973 fprintf (dump_file, "Function uses stdarg. \n");
4974 return false;
4977 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4978 return false;
4980 return true;
4983 /* Perform early interprocedural SRA. */
4985 static unsigned int
4986 ipa_early_sra (void)
4988 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4989 ipa_parm_adjustment_vec adjustments;
4990 int ret = 0;
4992 if (!ipa_sra_preliminary_function_checks (node))
4993 return 0;
4995 sra_initialize ();
4996 sra_mode = SRA_MODE_EARLY_IPA;
4998 if (!find_param_candidates ())
5000 if (dump_file)
5001 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
5002 goto simple_out;
5005 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
5006 NULL, true))
5008 if (dump_file)
5009 fprintf (dump_file, "There are callers with insufficient number of "
5010 "arguments.\n");
5011 goto simple_out;
5014 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
5015 func_param_count
5016 * last_basic_block_for_function (cfun));
5017 final_bbs = BITMAP_ALLOC (NULL);
5019 scan_function ();
5020 if (encountered_apply_args)
5022 if (dump_file)
5023 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
5024 goto out;
5027 if (encountered_unchangable_recursive_call)
5029 if (dump_file)
5030 fprintf (dump_file, "Function calls itself with insufficient "
5031 "number of arguments.\n");
5032 goto out;
5035 adjustments = analyze_all_param_acesses ();
5036 if (!adjustments.exists ())
5037 goto out;
5038 if (dump_file)
5039 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
5041 if (modify_function (node, adjustments))
5042 ret = TODO_update_ssa | TODO_cleanup_cfg;
5043 else
5044 ret = TODO_update_ssa;
5045 adjustments.release ();
5047 statistics_counter_event (cfun, "Unused parameters deleted",
5048 sra_stats.deleted_unused_parameters);
5049 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
5050 sra_stats.scalar_by_ref_to_by_val);
5051 statistics_counter_event (cfun, "Aggregate parameters broken up",
5052 sra_stats.aggregate_params_reduced);
5053 statistics_counter_event (cfun, "Aggregate parameter components created",
5054 sra_stats.param_reductions_created);
5056 out:
5057 BITMAP_FREE (final_bbs);
5058 free (bb_dereferences);
5059 simple_out:
5060 sra_deinitialize ();
5061 return ret;
5064 /* Return if early ipa sra shall be performed. */
5065 static bool
5066 ipa_early_sra_gate (void)
5068 return flag_ipa_sra && dbg_cnt (eipa_sra);
5071 namespace {
5073 const pass_data pass_data_early_ipa_sra =
5075 GIMPLE_PASS, /* type */
5076 "eipa_sra", /* name */
5077 OPTGROUP_NONE, /* optinfo_flags */
5078 true, /* has_gate */
5079 true, /* has_execute */
5080 TV_IPA_SRA, /* tv_id */
5081 0, /* properties_required */
5082 0, /* properties_provided */
5083 0, /* properties_destroyed */
5084 0, /* todo_flags_start */
5085 TODO_dump_symtab, /* todo_flags_finish */
5088 class pass_early_ipa_sra : public gimple_opt_pass
5090 public:
5091 pass_early_ipa_sra(gcc::context *ctxt)
5092 : gimple_opt_pass(pass_data_early_ipa_sra, ctxt)
5095 /* opt_pass methods: */
5096 bool gate () { return ipa_early_sra_gate (); }
5097 unsigned int execute () { return ipa_early_sra (); }
5099 }; // class pass_early_ipa_sra
5101 } // anon namespace
5103 gimple_opt_pass *
5104 make_pass_early_ipa_sra (gcc::context *ctxt)
5106 return new pass_early_ipa_sra (ctxt);