Merge trunk version 193672 into gupc branch.
[official-gcc.git] / gcc / tree-sra.c
blobaa87220d2e1955b131417a60a53c3af12c0c3447
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, 2009, 2010, 2011, 2012 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 "alloc-pool.h"
78 #include "tm.h"
79 #include "tree.h"
80 #include "gimple.h"
81 #include "cgraph.h"
82 #include "tree-flow.h"
83 #include "tree-pass.h"
84 #include "ipa-prop.h"
85 #include "statistics.h"
86 #include "params.h"
87 #include "target.h"
88 #include "flags.h"
89 #include "dbgcnt.h"
90 #include "tree-inline.h"
91 #include "gimple-pretty-print.h"
92 #include "ipa-inline.h"
94 /* Enumeration of all aggregate reductions we can do. */
95 enum sra_mode { SRA_MODE_EARLY_IPA, /* early call regularization */
96 SRA_MODE_EARLY_INTRA, /* early intraprocedural SRA */
97 SRA_MODE_INTRA }; /* late intraprocedural SRA */
99 /* Global variable describing which aggregate reduction we are performing at
100 the moment. */
101 static enum sra_mode sra_mode;
103 struct assign_link;
105 /* ACCESS represents each access to an aggregate variable (as a whole or a
106 part). It can also represent a group of accesses that refer to exactly the
107 same fragment of an aggregate (i.e. those that have exactly the same offset
108 and size). Such representatives for a single aggregate, once determined,
109 are linked in a linked list and have the group fields set.
111 Moreover, when doing intraprocedural SRA, a tree is built from those
112 representatives (by the means of first_child and next_sibling pointers), in
113 which all items in a subtree are "within" the root, i.e. their offset is
114 greater or equal to offset of the root and offset+size is smaller or equal
115 to offset+size of the root. Children of an access are sorted by offset.
117 Note that accesses to parts of vector and complex number types always
118 represented by an access to the whole complex number or a vector. It is a
119 duty of the modifying functions to replace them appropriately. */
121 struct access
123 /* Values returned by `get_ref_base_and_extent' for each component reference
124 If EXPR isn't a component reference just set `BASE = EXPR', `OFFSET = 0',
125 `SIZE = TREE_SIZE (TREE_TYPE (expr))'. */
126 HOST_WIDE_INT offset;
127 HOST_WIDE_INT size;
128 tree base;
130 /* Expression. It is context dependent so do not use it to create new
131 expressions to access the original aggregate. See PR 42154 for a
132 testcase. */
133 tree expr;
134 /* Type. */
135 tree type;
137 /* The statement this access belongs to. */
138 gimple stmt;
140 /* Next group representative for this aggregate. */
141 struct access *next_grp;
143 /* Pointer to the group representative. Pointer to itself if the struct is
144 the representative. */
145 struct access *group_representative;
147 /* If this access has any children (in terms of the definition above), this
148 points to the first one. */
149 struct access *first_child;
151 /* In intraprocedural SRA, pointer to the next sibling in the access tree as
152 described above. In IPA-SRA this is a pointer to the next access
153 belonging to the same group (having the same representative). */
154 struct access *next_sibling;
156 /* Pointers to the first and last element in the linked list of assign
157 links. */
158 struct assign_link *first_link, *last_link;
160 /* Pointer to the next access in the work queue. */
161 struct access *next_queued;
163 /* Replacement variable for this access "region." Never to be accessed
164 directly, always only by the means of get_access_replacement() and only
165 when grp_to_be_replaced flag is set. */
166 tree replacement_decl;
168 /* Is this particular access write access? */
169 unsigned write : 1;
171 /* Is this access an access to a non-addressable field? */
172 unsigned non_addressable : 1;
174 /* Is this access currently in the work queue? */
175 unsigned grp_queued : 1;
177 /* Does this group contain a write access? This flag is propagated down the
178 access tree. */
179 unsigned grp_write : 1;
181 /* Does this group contain a read access? This flag is propagated down the
182 access tree. */
183 unsigned grp_read : 1;
185 /* Does this group contain a read access that comes from an assignment
186 statement? This flag is propagated down the access tree. */
187 unsigned grp_assignment_read : 1;
189 /* Does this group contain a write access that comes from an assignment
190 statement? This flag is propagated down the access tree. */
191 unsigned grp_assignment_write : 1;
193 /* Does this group contain a read access through a scalar type? This flag is
194 not propagated in the access tree in any direction. */
195 unsigned grp_scalar_read : 1;
197 /* Does this group contain a write access through a scalar type? This flag
198 is not propagated in the access tree in any direction. */
199 unsigned grp_scalar_write : 1;
201 /* Is this access an artificial one created to scalarize some record
202 entirely? */
203 unsigned grp_total_scalarization : 1;
205 /* Other passes of the analysis use this bit to make function
206 analyze_access_subtree create scalar replacements for this group if
207 possible. */
208 unsigned grp_hint : 1;
210 /* Is the subtree rooted in this access fully covered by scalar
211 replacements? */
212 unsigned grp_covered : 1;
214 /* If set to true, this access and all below it in an access tree must not be
215 scalarized. */
216 unsigned grp_unscalarizable_region : 1;
218 /* Whether data have been written to parts of the aggregate covered by this
219 access which is not to be scalarized. This flag is propagated up in the
220 access tree. */
221 unsigned grp_unscalarized_data : 1;
223 /* Does this access and/or group contain a write access through a
224 BIT_FIELD_REF? */
225 unsigned grp_partial_lhs : 1;
227 /* Set when a scalar replacement should be created for this variable. */
228 unsigned grp_to_be_replaced : 1;
230 /* Set when we want a replacement for the sole purpose of having it in
231 generated debug statements. */
232 unsigned grp_to_be_debug_replaced : 1;
234 /* Should TREE_NO_WARNING of a replacement be set? */
235 unsigned grp_no_warning : 1;
237 /* Is it possible that the group refers to data which might be (directly or
238 otherwise) modified? */
239 unsigned grp_maybe_modified : 1;
241 /* Set when this is a representative of a pointer to scalar (i.e. by
242 reference) parameter which we consider for turning into a plain scalar
243 (i.e. a by value parameter). */
244 unsigned grp_scalar_ptr : 1;
246 /* Set when we discover that this pointer is not safe to dereference in the
247 caller. */
248 unsigned grp_not_necessarilly_dereferenced : 1;
251 typedef struct access *access_p;
254 /* Alloc pool for allocating access structures. */
255 static alloc_pool access_pool;
257 /* A structure linking lhs and rhs accesses from an aggregate assignment. They
258 are used to propagate subaccesses from rhs to lhs as long as they don't
259 conflict with what is already there. */
260 struct assign_link
262 struct access *lacc, *racc;
263 struct assign_link *next;
266 /* Alloc pool for allocating assign link structures. */
267 static alloc_pool link_pool;
269 /* Base (tree) -> Vector (vec<access_p> *) map. */
270 static struct pointer_map_t *base_access_vec;
272 /* Set of candidates. */
273 static bitmap candidate_bitmap;
274 static htab_t candidates;
276 /* For a candidate UID return the candidates decl. */
278 static inline tree
279 candidate (unsigned uid)
281 struct tree_decl_minimal t;
282 t.uid = uid;
283 return (tree) htab_find_with_hash (candidates, &t, uid);
286 /* Bitmap of candidates which we should try to entirely scalarize away and
287 those which cannot be (because they are and need be used as a whole). */
288 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
290 /* Obstack for creation of fancy names. */
291 static struct obstack name_obstack;
293 /* Head of a linked list of accesses that need to have its subaccesses
294 propagated to their assignment counterparts. */
295 static struct access *work_queue_head;
297 /* Number of parameters of the analyzed function when doing early ipa SRA. */
298 static int func_param_count;
300 /* scan_function sets the following to true if it encounters a call to
301 __builtin_apply_args. */
302 static bool encountered_apply_args;
304 /* Set by scan_function when it finds a recursive call. */
305 static bool encountered_recursive_call;
307 /* Set by scan_function when it finds a recursive call with less actual
308 arguments than formal parameters.. */
309 static bool encountered_unchangable_recursive_call;
311 /* This is a table in which for each basic block and parameter there is a
312 distance (offset + size) in that parameter which is dereferenced and
313 accessed in that BB. */
314 static HOST_WIDE_INT *bb_dereferences;
315 /* Bitmap of BBs that can cause the function to "stop" progressing by
316 returning, throwing externally, looping infinitely or calling a function
317 which might abort etc.. */
318 static bitmap final_bbs;
320 /* Representative of no accesses at all. */
321 static struct access no_accesses_representant;
323 /* Predicate to test the special value. */
325 static inline bool
326 no_accesses_p (struct access *access)
328 return access == &no_accesses_representant;
331 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
332 representative fields are dumped, otherwise those which only describe the
333 individual access are. */
335 static struct
337 /* Number of processed aggregates is readily available in
338 analyze_all_variable_accesses and so is not stored here. */
340 /* Number of created scalar replacements. */
341 int replacements;
343 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
344 expression. */
345 int exprs;
347 /* Number of statements created by generate_subtree_copies. */
348 int subtree_copies;
350 /* Number of statements created by load_assign_lhs_subreplacements. */
351 int subreplacements;
353 /* Number of times sra_modify_assign has deleted a statement. */
354 int deleted;
356 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
357 RHS reparately due to type conversions or nonexistent matching
358 references. */
359 int separate_lhs_rhs_handling;
361 /* Number of parameters that were removed because they were unused. */
362 int deleted_unused_parameters;
364 /* Number of scalars passed as parameters by reference that have been
365 converted to be passed by value. */
366 int scalar_by_ref_to_by_val;
368 /* Number of aggregate parameters that were replaced by one or more of their
369 components. */
370 int aggregate_params_reduced;
372 /* Numbber of components created when splitting aggregate parameters. */
373 int param_reductions_created;
374 } sra_stats;
376 static void
377 dump_access (FILE *f, struct access *access, bool grp)
379 fprintf (f, "access { ");
380 fprintf (f, "base = (%d)'", DECL_UID (access->base));
381 print_generic_expr (f, access->base, 0);
382 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
383 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
384 fprintf (f, ", expr = ");
385 print_generic_expr (f, access->expr, 0);
386 fprintf (f, ", type = ");
387 print_generic_expr (f, access->type, 0);
388 if (grp)
389 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
390 "grp_assignment_write = %d, grp_scalar_read = %d, "
391 "grp_scalar_write = %d, grp_total_scalarization = %d, "
392 "grp_hint = %d, grp_covered = %d, "
393 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
394 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
395 "grp_to_be_debug_replaced = %d, grp_maybe_modified = %d, "
396 "grp_not_necessarilly_dereferenced = %d\n",
397 access->grp_read, access->grp_write, access->grp_assignment_read,
398 access->grp_assignment_write, access->grp_scalar_read,
399 access->grp_scalar_write, access->grp_total_scalarization,
400 access->grp_hint, access->grp_covered,
401 access->grp_unscalarizable_region, access->grp_unscalarized_data,
402 access->grp_partial_lhs, access->grp_to_be_replaced,
403 access->grp_to_be_debug_replaced, access->grp_maybe_modified,
404 access->grp_not_necessarilly_dereferenced);
405 else
406 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
407 "grp_partial_lhs = %d\n",
408 access->write, access->grp_total_scalarization,
409 access->grp_partial_lhs);
412 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
414 static void
415 dump_access_tree_1 (FILE *f, struct access *access, int level)
419 int i;
421 for (i = 0; i < level; i++)
422 fputs ("* ", dump_file);
424 dump_access (f, access, true);
426 if (access->first_child)
427 dump_access_tree_1 (f, access->first_child, level + 1);
429 access = access->next_sibling;
431 while (access);
434 /* Dump all access trees for a variable, given the pointer to the first root in
435 ACCESS. */
437 static void
438 dump_access_tree (FILE *f, struct access *access)
440 for (; access; access = access->next_grp)
441 dump_access_tree_1 (f, access, 0);
444 /* Return true iff ACC is non-NULL and has subaccesses. */
446 static inline bool
447 access_has_children_p (struct access *acc)
449 return acc && acc->first_child;
452 /* Return true iff ACC is (partly) covered by at least one replacement. */
454 static bool
455 access_has_replacements_p (struct access *acc)
457 struct access *child;
458 if (acc->grp_to_be_replaced)
459 return true;
460 for (child = acc->first_child; child; child = child->next_sibling)
461 if (access_has_replacements_p (child))
462 return true;
463 return false;
466 /* Return a vector of pointers to accesses for the variable given in BASE or
467 NULL if there is none. */
469 static vec<access_p> *
470 get_base_access_vector (tree base)
472 void **slot;
474 slot = pointer_map_contains (base_access_vec, base);
475 if (!slot)
476 return NULL;
477 else
478 return *(vec<access_p> **) slot;
481 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
482 in ACCESS. Return NULL if it cannot be found. */
484 static struct access *
485 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
486 HOST_WIDE_INT size)
488 while (access && (access->offset != offset || access->size != size))
490 struct access *child = access->first_child;
492 while (child && (child->offset + child->size <= offset))
493 child = child->next_sibling;
494 access = child;
497 return access;
500 /* Return the first group representative for DECL or NULL if none exists. */
502 static struct access *
503 get_first_repr_for_decl (tree base)
505 vec<access_p> *access_vec;
507 access_vec = get_base_access_vector (base);
508 if (!access_vec)
509 return NULL;
511 return (*access_vec)[0];
514 /* Find an access representative for the variable BASE and given OFFSET and
515 SIZE. Requires that access trees have already been built. Return NULL if
516 it cannot be found. */
518 static struct access *
519 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
520 HOST_WIDE_INT size)
522 struct access *access;
524 access = get_first_repr_for_decl (base);
525 while (access && (access->offset + access->size <= offset))
526 access = access->next_grp;
527 if (!access)
528 return NULL;
530 return find_access_in_subtree (access, offset, size);
533 /* Add LINK to the linked list of assign links of RACC. */
534 static void
535 add_link_to_rhs (struct access *racc, struct assign_link *link)
537 gcc_assert (link->racc == racc);
539 if (!racc->first_link)
541 gcc_assert (!racc->last_link);
542 racc->first_link = link;
544 else
545 racc->last_link->next = link;
547 racc->last_link = link;
548 link->next = NULL;
551 /* Move all link structures in their linked list in OLD_RACC to the linked list
552 in NEW_RACC. */
553 static void
554 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
556 if (!old_racc->first_link)
558 gcc_assert (!old_racc->last_link);
559 return;
562 if (new_racc->first_link)
564 gcc_assert (!new_racc->last_link->next);
565 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
567 new_racc->last_link->next = old_racc->first_link;
568 new_racc->last_link = old_racc->last_link;
570 else
572 gcc_assert (!new_racc->last_link);
574 new_racc->first_link = old_racc->first_link;
575 new_racc->last_link = old_racc->last_link;
577 old_racc->first_link = old_racc->last_link = NULL;
580 /* Add ACCESS to the work queue (which is actually a stack). */
582 static void
583 add_access_to_work_queue (struct access *access)
585 if (!access->grp_queued)
587 gcc_assert (!access->next_queued);
588 access->next_queued = work_queue_head;
589 access->grp_queued = 1;
590 work_queue_head = access;
594 /* Pop an access from the work queue, and return it, assuming there is one. */
596 static struct access *
597 pop_access_from_work_queue (void)
599 struct access *access = work_queue_head;
601 work_queue_head = access->next_queued;
602 access->next_queued = NULL;
603 access->grp_queued = 0;
604 return access;
608 /* Allocate necessary structures. */
610 static void
611 sra_initialize (void)
613 candidate_bitmap = BITMAP_ALLOC (NULL);
614 candidates = htab_create (vec_safe_length (cfun->local_decls) / 2,
615 uid_decl_map_hash, uid_decl_map_eq, NULL);
616 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
617 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
618 gcc_obstack_init (&name_obstack);
619 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
620 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
621 base_access_vec = pointer_map_create ();
622 memset (&sra_stats, 0, sizeof (sra_stats));
623 encountered_apply_args = false;
624 encountered_recursive_call = false;
625 encountered_unchangable_recursive_call = false;
628 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
630 static bool
631 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
632 void *data ATTRIBUTE_UNUSED)
634 vec<access_p> *access_vec = (vec<access_p> *) *value;
635 vec_free (access_vec);
636 return true;
639 /* Deallocate all general structures. */
641 static void
642 sra_deinitialize (void)
644 BITMAP_FREE (candidate_bitmap);
645 htab_delete (candidates);
646 BITMAP_FREE (should_scalarize_away_bitmap);
647 BITMAP_FREE (cannot_scalarize_away_bitmap);
648 free_alloc_pool (access_pool);
649 free_alloc_pool (link_pool);
650 obstack_free (&name_obstack, NULL);
652 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
653 pointer_map_destroy (base_access_vec);
656 /* Remove DECL from candidates for SRA and write REASON to the dump file if
657 there is one. */
658 static void
659 disqualify_candidate (tree decl, const char *reason)
661 if (bitmap_clear_bit (candidate_bitmap, DECL_UID (decl)))
662 htab_clear_slot (candidates,
663 htab_find_slot_with_hash (candidates, decl,
664 DECL_UID (decl), NO_INSERT));
666 if (dump_file && (dump_flags & TDF_DETAILS))
668 fprintf (dump_file, "! Disqualifying ");
669 print_generic_expr (dump_file, decl, 0);
670 fprintf (dump_file, " - %s\n", reason);
674 /* Return true iff the type contains a field or an element which does not allow
675 scalarization. */
677 static bool
678 type_internals_preclude_sra_p (tree type, const char **msg)
680 tree fld;
681 tree et;
683 switch (TREE_CODE (type))
685 case RECORD_TYPE:
686 case UNION_TYPE:
687 case QUAL_UNION_TYPE:
688 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
689 if (TREE_CODE (fld) == FIELD_DECL)
691 tree ft = TREE_TYPE (fld);
693 if (TREE_THIS_VOLATILE (fld))
695 *msg = "volatile structure field";
696 return true;
698 if (!DECL_FIELD_OFFSET (fld))
700 *msg = "no structure field offset";
701 return true;
703 if (!DECL_SIZE (fld))
705 *msg = "zero structure field size";
706 return true;
708 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
710 *msg = "structure field offset not fixed";
711 return true;
713 if (!host_integerp (DECL_SIZE (fld), 1))
715 *msg = "structure field size not fixed";
716 return true;
718 if (AGGREGATE_TYPE_P (ft)
719 && int_bit_position (fld) % BITS_PER_UNIT != 0)
721 *msg = "structure field is bit field";
722 return true;
725 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
726 return true;
729 return false;
731 case ARRAY_TYPE:
732 et = TREE_TYPE (type);
734 if (TYPE_VOLATILE (et))
736 *msg = "element type is volatile";
737 return true;
740 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
741 return true;
743 return false;
745 default:
746 return false;
750 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
751 base variable if it is. Return T if it is not an SSA_NAME. */
753 static tree
754 get_ssa_base_param (tree t)
756 if (TREE_CODE (t) == SSA_NAME)
758 if (SSA_NAME_IS_DEFAULT_DEF (t))
759 return SSA_NAME_VAR (t);
760 else
761 return NULL_TREE;
763 return t;
766 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
767 belongs to, unless the BB has already been marked as a potentially
768 final. */
770 static void
771 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
773 basic_block bb = gimple_bb (stmt);
774 int idx, parm_index = 0;
775 tree parm;
777 if (bitmap_bit_p (final_bbs, bb->index))
778 return;
780 for (parm = DECL_ARGUMENTS (current_function_decl);
781 parm && parm != base;
782 parm = DECL_CHAIN (parm))
783 parm_index++;
785 gcc_assert (parm_index < func_param_count);
787 idx = bb->index * func_param_count + parm_index;
788 if (bb_dereferences[idx] < dist)
789 bb_dereferences[idx] = dist;
792 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
793 the three fields. Also add it to the vector of accesses corresponding to
794 the base. Finally, return the new access. */
796 static struct access *
797 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
799 vec<access_p> *v;
800 struct access *access;
801 void **slot;
803 access = (struct access *) pool_alloc (access_pool);
804 memset (access, 0, sizeof (struct access));
805 access->base = base;
806 access->offset = offset;
807 access->size = size;
809 slot = pointer_map_contains (base_access_vec, base);
810 if (slot)
811 v = (vec<access_p> *) *slot;
812 else
813 vec_alloc (v, 32);
815 v->safe_push (access);
817 *((vec<access_p> **)
818 pointer_map_insert (base_access_vec, base)) = v;
820 return access;
823 /* Create and insert access for EXPR. Return created access, or NULL if it is
824 not possible. */
826 static struct access *
827 create_access (tree expr, gimple stmt, bool write)
829 struct access *access;
830 HOST_WIDE_INT offset, size, max_size;
831 tree base = expr;
832 bool ptr, unscalarizable_region = false;
834 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
836 if (sra_mode == SRA_MODE_EARLY_IPA
837 && TREE_CODE (base) == MEM_REF)
839 base = get_ssa_base_param (TREE_OPERAND (base, 0));
840 if (!base)
841 return NULL;
842 ptr = true;
844 else
845 ptr = false;
847 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
848 return NULL;
850 if (sra_mode == SRA_MODE_EARLY_IPA)
852 if (size < 0 || size != max_size)
854 disqualify_candidate (base, "Encountered a variable sized access.");
855 return NULL;
857 if (TREE_CODE (expr) == COMPONENT_REF
858 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
860 disqualify_candidate (base, "Encountered a bit-field access.");
861 return NULL;
863 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
865 if (ptr)
866 mark_parm_dereference (base, offset + size, stmt);
868 else
870 if (size != max_size)
872 size = max_size;
873 unscalarizable_region = true;
875 if (size < 0)
877 disqualify_candidate (base, "Encountered an unconstrained access.");
878 return NULL;
882 access = create_access_1 (base, offset, size);
883 access->expr = expr;
884 access->type = TREE_TYPE (expr);
885 access->write = write;
886 access->grp_unscalarizable_region = unscalarizable_region;
887 access->stmt = stmt;
889 if (TREE_CODE (expr) == COMPONENT_REF
890 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
891 access->non_addressable = 1;
893 return access;
897 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
898 register types or (recursively) records with only these two kinds of fields.
899 It also returns false if any of these records contains a bit-field. */
901 static bool
902 type_consists_of_records_p (tree type)
904 tree fld;
906 if (TREE_CODE (type) != RECORD_TYPE)
907 return false;
909 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
910 if (TREE_CODE (fld) == FIELD_DECL)
912 tree ft = TREE_TYPE (fld);
914 if (DECL_BIT_FIELD (fld))
915 return false;
917 if (!is_gimple_reg_type (ft)
918 && !type_consists_of_records_p (ft))
919 return false;
922 return true;
925 /* Create total_scalarization accesses for all scalar type fields in DECL that
926 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
927 must be the top-most VAR_DECL representing the variable, OFFSET must be the
928 offset of DECL within BASE. REF must be the memory reference expression for
929 the given decl. */
931 static void
932 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
933 tree ref)
935 tree fld, decl_type = TREE_TYPE (decl);
937 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
938 if (TREE_CODE (fld) == FIELD_DECL)
940 HOST_WIDE_INT pos = offset + int_bit_position (fld);
941 tree ft = TREE_TYPE (fld);
942 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
943 NULL_TREE);
945 if (is_gimple_reg_type (ft))
947 struct access *access;
948 HOST_WIDE_INT size;
950 size = tree_low_cst (DECL_SIZE (fld), 1);
951 access = create_access_1 (base, pos, size);
952 access->expr = nref;
953 access->type = ft;
954 access->grp_total_scalarization = 1;
955 /* Accesses for intraprocedural SRA can have their stmt NULL. */
957 else
958 completely_scalarize_record (base, fld, pos, nref);
962 /* Create total_scalarization accesses for all scalar type fields in VAR and
963 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
964 type_consists_of_records_p. */
966 static void
967 completely_scalarize_var (tree var)
969 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
970 struct access *access;
972 access = create_access_1 (var, 0, size);
973 access->expr = var;
974 access->type = TREE_TYPE (var);
975 access->grp_total_scalarization = 1;
977 completely_scalarize_record (var, var, 0, var);
980 /* Search the given tree for a declaration by skipping handled components and
981 exclude it from the candidates. */
983 static void
984 disqualify_base_of_expr (tree t, const char *reason)
986 t = get_base_address (t);
987 if (sra_mode == SRA_MODE_EARLY_IPA
988 && TREE_CODE (t) == MEM_REF)
989 t = get_ssa_base_param (TREE_OPERAND (t, 0));
991 if (t && DECL_P (t))
992 disqualify_candidate (t, reason);
995 /* Scan expression EXPR and create access structures for all accesses to
996 candidates for scalarization. Return the created access or NULL if none is
997 created. */
999 static struct access *
1000 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
1002 struct access *ret = NULL;
1003 bool partial_ref;
1005 if (TREE_CODE (expr) == BIT_FIELD_REF
1006 || TREE_CODE (expr) == IMAGPART_EXPR
1007 || TREE_CODE (expr) == REALPART_EXPR)
1009 expr = TREE_OPERAND (expr, 0);
1010 partial_ref = true;
1012 else
1013 partial_ref = false;
1015 /* We need to dive through V_C_Es in order to get the size of its parameter
1016 and not the result type. Ada produces such statements. We are also
1017 capable of handling the topmost V_C_E but not any of those buried in other
1018 handled components. */
1019 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1020 expr = TREE_OPERAND (expr, 0);
1022 if (contains_view_convert_expr_p (expr))
1024 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1025 "component.");
1026 return NULL;
1029 switch (TREE_CODE (expr))
1031 case MEM_REF:
1032 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1033 && sra_mode != SRA_MODE_EARLY_IPA)
1034 return NULL;
1035 /* fall through */
1036 case VAR_DECL:
1037 case PARM_DECL:
1038 case RESULT_DECL:
1039 case COMPONENT_REF:
1040 case ARRAY_REF:
1041 case ARRAY_RANGE_REF:
1042 ret = create_access (expr, stmt, write);
1043 break;
1045 default:
1046 break;
1049 if (write && partial_ref && ret)
1050 ret->grp_partial_lhs = 1;
1052 return ret;
1055 /* Scan expression EXPR and create access structures for all accesses to
1056 candidates for scalarization. Return true if any access has been inserted.
1057 STMT must be the statement from which the expression is taken, WRITE must be
1058 true if the expression is a store and false otherwise. */
1060 static bool
1061 build_access_from_expr (tree expr, gimple stmt, bool write)
1063 struct access *access;
1065 access = build_access_from_expr_1 (expr, stmt, write);
1066 if (access)
1068 /* This means the aggregate is accesses as a whole in a way other than an
1069 assign statement and thus cannot be removed even if we had a scalar
1070 replacement for everything. */
1071 if (cannot_scalarize_away_bitmap)
1072 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1073 return true;
1075 return false;
1078 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1079 modes in which it matters, return true iff they have been disqualified. RHS
1080 may be NULL, in that case ignore it. If we scalarize an aggregate in
1081 intra-SRA we may need to add statements after each statement. This is not
1082 possible if a statement unconditionally has to end the basic block. */
1083 static bool
1084 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1086 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1087 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1089 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1090 if (rhs)
1091 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1092 return true;
1094 return false;
1097 /* Scan expressions occurring in STMT, create access structures for all accesses
1098 to candidates for scalarization and remove those candidates which occur in
1099 statements or expressions that prevent them from being split apart. Return
1100 true if any access has been inserted. */
1102 static bool
1103 build_accesses_from_assign (gimple stmt)
1105 tree lhs, rhs;
1106 struct access *lacc, *racc;
1108 if (!gimple_assign_single_p (stmt)
1109 /* Scope clobbers don't influence scalarization. */
1110 || gimple_clobber_p (stmt))
1111 return false;
1113 lhs = gimple_assign_lhs (stmt);
1114 rhs = gimple_assign_rhs1 (stmt);
1116 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1117 return false;
1119 racc = build_access_from_expr_1 (rhs, stmt, false);
1120 lacc = build_access_from_expr_1 (lhs, stmt, true);
1122 if (lacc)
1123 lacc->grp_assignment_write = 1;
1125 if (racc)
1127 racc->grp_assignment_read = 1;
1128 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1129 && !is_gimple_reg_type (racc->type))
1130 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1133 if (lacc && racc
1134 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1135 && !lacc->grp_unscalarizable_region
1136 && !racc->grp_unscalarizable_region
1137 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1138 && lacc->size == racc->size
1139 && useless_type_conversion_p (lacc->type, racc->type))
1141 struct assign_link *link;
1143 link = (struct assign_link *) pool_alloc (link_pool);
1144 memset (link, 0, sizeof (struct assign_link));
1146 link->lacc = lacc;
1147 link->racc = racc;
1149 add_link_to_rhs (racc, link);
1152 return lacc || racc;
1155 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1156 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1158 static bool
1159 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1160 void *data ATTRIBUTE_UNUSED)
1162 op = get_base_address (op);
1163 if (op
1164 && DECL_P (op))
1165 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1167 return false;
1170 /* Return true iff callsite CALL has at least as many actual arguments as there
1171 are formal parameters of the function currently processed by IPA-SRA. */
1173 static inline bool
1174 callsite_has_enough_arguments_p (gimple call)
1176 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1179 /* Scan function and look for interesting expressions and create access
1180 structures for them. Return true iff any access is created. */
1182 static bool
1183 scan_function (void)
1185 basic_block bb;
1186 bool ret = false;
1188 FOR_EACH_BB (bb)
1190 gimple_stmt_iterator gsi;
1191 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1193 gimple stmt = gsi_stmt (gsi);
1194 tree t;
1195 unsigned i;
1197 if (final_bbs && stmt_can_throw_external (stmt))
1198 bitmap_set_bit (final_bbs, bb->index);
1199 switch (gimple_code (stmt))
1201 case GIMPLE_RETURN:
1202 t = gimple_return_retval (stmt);
1203 if (t != NULL_TREE)
1204 ret |= build_access_from_expr (t, stmt, false);
1205 if (final_bbs)
1206 bitmap_set_bit (final_bbs, bb->index);
1207 break;
1209 case GIMPLE_ASSIGN:
1210 ret |= build_accesses_from_assign (stmt);
1211 break;
1213 case GIMPLE_CALL:
1214 for (i = 0; i < gimple_call_num_args (stmt); i++)
1215 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1216 stmt, false);
1218 if (sra_mode == SRA_MODE_EARLY_IPA)
1220 tree dest = gimple_call_fndecl (stmt);
1221 int flags = gimple_call_flags (stmt);
1223 if (dest)
1225 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1226 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1227 encountered_apply_args = true;
1228 if (cgraph_get_node (dest)
1229 == cgraph_get_node (current_function_decl))
1231 encountered_recursive_call = true;
1232 if (!callsite_has_enough_arguments_p (stmt))
1233 encountered_unchangable_recursive_call = true;
1237 if (final_bbs
1238 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1239 bitmap_set_bit (final_bbs, bb->index);
1242 t = gimple_call_lhs (stmt);
1243 if (t && !disqualify_ops_if_throwing_stmt (stmt, t, NULL))
1244 ret |= build_access_from_expr (t, stmt, true);
1245 break;
1247 case GIMPLE_ASM:
1248 walk_stmt_load_store_addr_ops (stmt, NULL, NULL, NULL,
1249 asm_visit_addr);
1250 if (final_bbs)
1251 bitmap_set_bit (final_bbs, bb->index);
1253 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1255 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1256 ret |= build_access_from_expr (t, stmt, false);
1258 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1260 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1261 ret |= build_access_from_expr (t, stmt, true);
1263 break;
1265 default:
1266 break;
1271 return ret;
1274 /* Helper of QSORT function. There are pointers to accesses in the array. An
1275 access is considered smaller than another if it has smaller offset or if the
1276 offsets are the same but is size is bigger. */
1278 static int
1279 compare_access_positions (const void *a, const void *b)
1281 const access_p *fp1 = (const access_p *) a;
1282 const access_p *fp2 = (const access_p *) b;
1283 const access_p f1 = *fp1;
1284 const access_p f2 = *fp2;
1286 if (f1->offset != f2->offset)
1287 return f1->offset < f2->offset ? -1 : 1;
1289 if (f1->size == f2->size)
1291 if (f1->type == f2->type)
1292 return 0;
1293 /* Put any non-aggregate type before any aggregate type. */
1294 else if (!is_gimple_reg_type (f1->type)
1295 && is_gimple_reg_type (f2->type))
1296 return 1;
1297 else if (is_gimple_reg_type (f1->type)
1298 && !is_gimple_reg_type (f2->type))
1299 return -1;
1300 /* Put any complex or vector type before any other scalar type. */
1301 else if (TREE_CODE (f1->type) != COMPLEX_TYPE
1302 && TREE_CODE (f1->type) != VECTOR_TYPE
1303 && (TREE_CODE (f2->type) == COMPLEX_TYPE
1304 || TREE_CODE (f2->type) == VECTOR_TYPE))
1305 return 1;
1306 else if ((TREE_CODE (f1->type) == COMPLEX_TYPE
1307 || TREE_CODE (f1->type) == VECTOR_TYPE)
1308 && TREE_CODE (f2->type) != COMPLEX_TYPE
1309 && TREE_CODE (f2->type) != VECTOR_TYPE)
1310 return -1;
1311 /* Put the integral type with the bigger precision first. */
1312 else if (INTEGRAL_TYPE_P (f1->type)
1313 && INTEGRAL_TYPE_P (f2->type))
1314 return TYPE_PRECISION (f2->type) - TYPE_PRECISION (f1->type);
1315 /* Put any integral type with non-full precision last. */
1316 else if (INTEGRAL_TYPE_P (f1->type)
1317 && (TREE_INT_CST_LOW (TYPE_SIZE (f1->type))
1318 != TYPE_PRECISION (f1->type)))
1319 return 1;
1320 else if (INTEGRAL_TYPE_P (f2->type)
1321 && (TREE_INT_CST_LOW (TYPE_SIZE (f2->type))
1322 != TYPE_PRECISION (f2->type)))
1323 return -1;
1324 /* Stabilize the sort. */
1325 return TYPE_UID (f1->type) - TYPE_UID (f2->type);
1328 /* We want the bigger accesses first, thus the opposite operator in the next
1329 line: */
1330 return f1->size > f2->size ? -1 : 1;
1334 /* Append a name of the declaration to the name obstack. A helper function for
1335 make_fancy_name. */
1337 static void
1338 make_fancy_decl_name (tree decl)
1340 char buffer[32];
1342 tree name = DECL_NAME (decl);
1343 if (name)
1344 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1345 IDENTIFIER_LENGTH (name));
1346 else
1348 sprintf (buffer, "D%u", DECL_UID (decl));
1349 obstack_grow (&name_obstack, buffer, strlen (buffer));
1353 /* Helper for make_fancy_name. */
1355 static void
1356 make_fancy_name_1 (tree expr)
1358 char buffer[32];
1359 tree index;
1361 if (DECL_P (expr))
1363 make_fancy_decl_name (expr);
1364 return;
1367 switch (TREE_CODE (expr))
1369 case COMPONENT_REF:
1370 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1371 obstack_1grow (&name_obstack, '$');
1372 make_fancy_decl_name (TREE_OPERAND (expr, 1));
1373 break;
1375 case ARRAY_REF:
1376 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1377 obstack_1grow (&name_obstack, '$');
1378 /* Arrays with only one element may not have a constant as their
1379 index. */
1380 index = TREE_OPERAND (expr, 1);
1381 if (TREE_CODE (index) != INTEGER_CST)
1382 break;
1383 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (index));
1384 obstack_grow (&name_obstack, buffer, strlen (buffer));
1385 break;
1387 case ADDR_EXPR:
1388 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1389 break;
1391 case MEM_REF:
1392 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1393 if (!integer_zerop (TREE_OPERAND (expr, 1)))
1395 obstack_1grow (&name_obstack, '$');
1396 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC,
1397 TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
1398 obstack_grow (&name_obstack, buffer, strlen (buffer));
1400 break;
1402 case BIT_FIELD_REF:
1403 case REALPART_EXPR:
1404 case IMAGPART_EXPR:
1405 gcc_unreachable (); /* we treat these as scalars. */
1406 break;
1407 default:
1408 break;
1412 /* Create a human readable name for replacement variable of ACCESS. */
1414 static char *
1415 make_fancy_name (tree expr)
1417 make_fancy_name_1 (expr);
1418 obstack_1grow (&name_obstack, '\0');
1419 return XOBFINISH (&name_obstack, char *);
1422 /* Construct a MEM_REF that would reference a part of aggregate BASE of type
1423 EXP_TYPE at the given OFFSET. If BASE is something for which
1424 get_addr_base_and_unit_offset returns NULL, gsi must be non-NULL and is used
1425 to insert new statements either before or below the current one as specified
1426 by INSERT_AFTER. This function is not capable of handling bitfields. */
1428 tree
1429 build_ref_for_offset (location_t loc, tree base, HOST_WIDE_INT offset,
1430 tree exp_type, gimple_stmt_iterator *gsi,
1431 bool insert_after)
1433 tree prev_base = base;
1434 tree off;
1435 HOST_WIDE_INT base_offset;
1436 unsigned HOST_WIDE_INT misalign;
1437 unsigned int align;
1439 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1441 base = get_addr_base_and_unit_offset (base, &base_offset);
1443 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1444 offset such as array[var_index]. */
1445 if (!base)
1447 gimple stmt;
1448 tree tmp, addr;
1450 gcc_checking_assert (gsi);
1451 tmp = make_ssa_name (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1452 addr = build_fold_addr_expr (unshare_expr (prev_base));
1453 STRIP_USELESS_TYPE_CONVERSION (addr);
1454 stmt = gimple_build_assign (tmp, addr);
1455 gimple_set_location (stmt, loc);
1456 if (insert_after)
1457 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1458 else
1459 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1461 off = build_int_cst (reference_alias_ptr_type (prev_base),
1462 offset / BITS_PER_UNIT);
1463 base = tmp;
1465 else if (TREE_CODE (base) == MEM_REF)
1467 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1468 base_offset + offset / BITS_PER_UNIT);
1469 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1470 base = unshare_expr (TREE_OPERAND (base, 0));
1472 else
1474 off = build_int_cst (reference_alias_ptr_type (base),
1475 base_offset + offset / BITS_PER_UNIT);
1476 base = build_fold_addr_expr (unshare_expr (base));
1479 /* If prev_base were always an originally performed access
1480 we can extract more optimistic alignment information
1481 by looking at the access mode. That would constrain the
1482 alignment of base + base_offset which we would need to
1483 adjust according to offset. */
1484 if (!get_pointer_alignment_1 (base, &align, &misalign))
1486 gcc_assert (misalign == 0);
1487 if (TREE_CODE (prev_base) == MEM_REF
1488 || TREE_CODE (prev_base) == TARGET_MEM_REF)
1489 align = TYPE_ALIGN (TREE_TYPE (prev_base));
1491 misalign += (tree_to_double_int (off)
1492 .sext (TYPE_PRECISION (TREE_TYPE (off))).low
1493 * BITS_PER_UNIT);
1494 misalign = misalign & (align - 1);
1495 if (misalign != 0)
1496 align = (misalign & -misalign);
1497 if (align < TYPE_ALIGN (exp_type))
1498 exp_type = build_aligned_type (exp_type, align);
1500 return fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1503 /* Construct a memory reference to a part of an aggregate BASE at the given
1504 OFFSET and of the same type as MODEL. In case this is a reference to a
1505 bit-field, the function will replicate the last component_ref of model's
1506 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1507 build_ref_for_offset. */
1509 static tree
1510 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1511 struct access *model, gimple_stmt_iterator *gsi,
1512 bool insert_after)
1514 if (TREE_CODE (model->expr) == COMPONENT_REF
1515 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1517 /* This access represents a bit-field. */
1518 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1520 offset -= int_bit_position (fld);
1521 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1522 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1523 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1524 NULL_TREE);
1526 else
1527 return build_ref_for_offset (loc, base, offset, model->type,
1528 gsi, insert_after);
1531 /* Attempt to build a memory reference that we could but into a gimple
1532 debug_bind statement. Similar to build_ref_for_model but punts if it has to
1533 create statements and return s NULL instead. This function also ignores
1534 alignment issues and so its results should never end up in non-debug
1535 statements. */
1537 static tree
1538 build_debug_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1539 struct access *model)
1541 HOST_WIDE_INT base_offset;
1542 tree off;
1544 if (TREE_CODE (model->expr) == COMPONENT_REF
1545 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1546 return NULL_TREE;
1548 base = get_addr_base_and_unit_offset (base, &base_offset);
1549 if (!base)
1550 return NULL_TREE;
1551 if (TREE_CODE (base) == MEM_REF)
1553 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1554 base_offset + offset / BITS_PER_UNIT);
1555 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1556 base = unshare_expr (TREE_OPERAND (base, 0));
1558 else
1560 off = build_int_cst (reference_alias_ptr_type (base),
1561 base_offset + offset / BITS_PER_UNIT);
1562 base = build_fold_addr_expr (unshare_expr (base));
1565 return fold_build2_loc (loc, MEM_REF, model->type, base, off);
1568 /* Construct a memory reference consisting of component_refs and array_refs to
1569 a part of an aggregate *RES (which is of type TYPE). The requested part
1570 should have type EXP_TYPE at be the given OFFSET. This function might not
1571 succeed, it returns true when it does and only then *RES points to something
1572 meaningful. This function should be used only to build expressions that we
1573 might need to present to user (e.g. in warnings). In all other situations,
1574 build_ref_for_model or build_ref_for_offset should be used instead. */
1576 static bool
1577 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1578 tree exp_type)
1580 while (1)
1582 tree fld;
1583 tree tr_size, index, minidx;
1584 HOST_WIDE_INT el_size;
1586 if (offset == 0 && exp_type
1587 && types_compatible_p (exp_type, type))
1588 return true;
1590 switch (TREE_CODE (type))
1592 case UNION_TYPE:
1593 case QUAL_UNION_TYPE:
1594 case RECORD_TYPE:
1595 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1597 HOST_WIDE_INT pos, size;
1598 tree tr_pos, expr, *expr_ptr;
1600 if (TREE_CODE (fld) != FIELD_DECL)
1601 continue;
1603 tr_pos = bit_position (fld);
1604 if (!tr_pos || !host_integerp (tr_pos, 1))
1605 continue;
1606 pos = TREE_INT_CST_LOW (tr_pos);
1607 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1608 tr_size = DECL_SIZE (fld);
1609 if (!tr_size || !host_integerp (tr_size, 1))
1610 continue;
1611 size = TREE_INT_CST_LOW (tr_size);
1612 if (size == 0)
1614 if (pos != offset)
1615 continue;
1617 else if (pos > offset || (pos + size) <= offset)
1618 continue;
1620 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1621 NULL_TREE);
1622 expr_ptr = &expr;
1623 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1624 offset - pos, exp_type))
1626 *res = expr;
1627 return true;
1630 return false;
1632 case ARRAY_TYPE:
1633 tr_size = TYPE_SIZE (TREE_TYPE (type));
1634 if (!tr_size || !host_integerp (tr_size, 1))
1635 return false;
1636 el_size = tree_low_cst (tr_size, 1);
1638 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1639 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1640 return false;
1641 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1642 if (!integer_zerop (minidx))
1643 index = int_const_binop (PLUS_EXPR, index, minidx);
1644 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1645 NULL_TREE, NULL_TREE);
1646 offset = offset % el_size;
1647 type = TREE_TYPE (type);
1648 break;
1650 default:
1651 if (offset != 0)
1652 return false;
1654 if (exp_type)
1655 return false;
1656 else
1657 return true;
1662 /* Return true iff TYPE is stdarg va_list type. */
1664 static inline bool
1665 is_va_list_type (tree type)
1667 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1670 /* Print message to dump file why a variable was rejected. */
1672 static void
1673 reject (tree var, const char *msg)
1675 if (dump_file && (dump_flags & TDF_DETAILS))
1677 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1678 print_generic_expr (dump_file, var, 0);
1679 fprintf (dump_file, "\n");
1683 /* Return true if VAR is a candidate for SRA. */
1685 static bool
1686 maybe_add_sra_candidate (tree var)
1688 tree type = TREE_TYPE (var);
1689 const char *msg;
1690 void **slot;
1692 if (!AGGREGATE_TYPE_P (type))
1694 reject (var, "not aggregate");
1695 return false;
1697 if (needs_to_live_in_memory (var))
1699 reject (var, "needs to live in memory");
1700 return false;
1702 if (TREE_THIS_VOLATILE (var))
1704 reject (var, "is volatile");
1705 return false;
1707 if (!COMPLETE_TYPE_P (type))
1709 reject (var, "has incomplete type");
1710 return false;
1712 if (!host_integerp (TYPE_SIZE (type), 1))
1714 reject (var, "type size not fixed");
1715 return false;
1717 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1719 reject (var, "type size is zero");
1720 return false;
1722 if (type_internals_preclude_sra_p (type, &msg))
1724 reject (var, msg);
1725 return false;
1727 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1728 we also want to schedule it rather late. Thus we ignore it in
1729 the early pass. */
1730 (sra_mode == SRA_MODE_EARLY_INTRA
1731 && is_va_list_type (type)))
1733 reject (var, "is va_list");
1734 return false;
1737 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1738 slot = htab_find_slot_with_hash (candidates, var, DECL_UID (var), INSERT);
1739 *slot = (void *) var;
1741 if (dump_file && (dump_flags & TDF_DETAILS))
1743 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1744 print_generic_expr (dump_file, var, 0);
1745 fprintf (dump_file, "\n");
1748 return true;
1751 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1752 those with type which is suitable for scalarization. */
1754 static bool
1755 find_var_candidates (void)
1757 tree var, parm;
1758 unsigned int i;
1759 bool ret = false;
1761 for (parm = DECL_ARGUMENTS (current_function_decl);
1762 parm;
1763 parm = DECL_CHAIN (parm))
1764 ret |= maybe_add_sra_candidate (parm);
1766 FOR_EACH_LOCAL_DECL (cfun, i, var)
1768 if (TREE_CODE (var) != VAR_DECL)
1769 continue;
1771 ret |= maybe_add_sra_candidate (var);
1774 return ret;
1777 /* Sort all accesses for the given variable, check for partial overlaps and
1778 return NULL if there are any. If there are none, pick a representative for
1779 each combination of offset and size and create a linked list out of them.
1780 Return the pointer to the first representative and make sure it is the first
1781 one in the vector of accesses. */
1783 static struct access *
1784 sort_and_splice_var_accesses (tree var)
1786 int i, j, access_count;
1787 struct access *res, **prev_acc_ptr = &res;
1788 vec<access_p> *access_vec;
1789 bool first = true;
1790 HOST_WIDE_INT low = -1, high = 0;
1792 access_vec = get_base_access_vector (var);
1793 if (!access_vec)
1794 return NULL;
1795 access_count = access_vec->length ();
1797 /* Sort by <OFFSET, SIZE>. */
1798 access_vec->qsort (compare_access_positions);
1800 i = 0;
1801 while (i < access_count)
1803 struct access *access = (*access_vec)[i];
1804 bool grp_write = access->write;
1805 bool grp_read = !access->write;
1806 bool grp_scalar_write = access->write
1807 && is_gimple_reg_type (access->type);
1808 bool grp_scalar_read = !access->write
1809 && is_gimple_reg_type (access->type);
1810 bool grp_assignment_read = access->grp_assignment_read;
1811 bool grp_assignment_write = access->grp_assignment_write;
1812 bool multiple_scalar_reads = false;
1813 bool total_scalarization = access->grp_total_scalarization;
1814 bool grp_partial_lhs = access->grp_partial_lhs;
1815 bool first_scalar = is_gimple_reg_type (access->type);
1816 bool unscalarizable_region = access->grp_unscalarizable_region;
1818 if (first || access->offset >= high)
1820 first = false;
1821 low = access->offset;
1822 high = access->offset + access->size;
1824 else if (access->offset > low && access->offset + access->size > high)
1825 return NULL;
1826 else
1827 gcc_assert (access->offset >= low
1828 && access->offset + access->size <= high);
1830 j = i + 1;
1831 while (j < access_count)
1833 struct access *ac2 = (*access_vec)[j];
1834 if (ac2->offset != access->offset || ac2->size != access->size)
1835 break;
1836 if (ac2->write)
1838 grp_write = true;
1839 grp_scalar_write = (grp_scalar_write
1840 || is_gimple_reg_type (ac2->type));
1842 else
1844 grp_read = true;
1845 if (is_gimple_reg_type (ac2->type))
1847 if (grp_scalar_read)
1848 multiple_scalar_reads = true;
1849 else
1850 grp_scalar_read = true;
1853 grp_assignment_read |= ac2->grp_assignment_read;
1854 grp_assignment_write |= ac2->grp_assignment_write;
1855 grp_partial_lhs |= ac2->grp_partial_lhs;
1856 unscalarizable_region |= ac2->grp_unscalarizable_region;
1857 total_scalarization |= ac2->grp_total_scalarization;
1858 relink_to_new_repr (access, ac2);
1860 /* If there are both aggregate-type and scalar-type accesses with
1861 this combination of size and offset, the comparison function
1862 should have put the scalars first. */
1863 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1864 ac2->group_representative = access;
1865 j++;
1868 i = j;
1870 access->group_representative = access;
1871 access->grp_write = grp_write;
1872 access->grp_read = grp_read;
1873 access->grp_scalar_read = grp_scalar_read;
1874 access->grp_scalar_write = grp_scalar_write;
1875 access->grp_assignment_read = grp_assignment_read;
1876 access->grp_assignment_write = grp_assignment_write;
1877 access->grp_hint = multiple_scalar_reads || total_scalarization;
1878 access->grp_total_scalarization = total_scalarization;
1879 access->grp_partial_lhs = grp_partial_lhs;
1880 access->grp_unscalarizable_region = unscalarizable_region;
1881 if (access->first_link)
1882 add_access_to_work_queue (access);
1884 *prev_acc_ptr = access;
1885 prev_acc_ptr = &access->next_grp;
1888 gcc_assert (res == (*access_vec)[0]);
1889 return res;
1892 /* Create a variable for the given ACCESS which determines the type, name and a
1893 few other properties. Return the variable declaration and store it also to
1894 ACCESS->replacement. */
1896 static tree
1897 create_access_replacement (struct access *access)
1899 tree repl;
1901 if (access->grp_to_be_debug_replaced)
1903 repl = create_tmp_var_raw (access->type, NULL);
1904 DECL_CONTEXT (repl) = current_function_decl;
1906 else
1907 repl = create_tmp_var (access->type, "SR");
1908 if (TREE_CODE (access->type) == COMPLEX_TYPE
1909 || TREE_CODE (access->type) == VECTOR_TYPE)
1911 if (!access->grp_partial_lhs)
1912 DECL_GIMPLE_REG_P (repl) = 1;
1914 else if (access->grp_partial_lhs
1915 && is_gimple_reg_type (access->type))
1916 TREE_ADDRESSABLE (repl) = 1;
1918 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1919 DECL_ARTIFICIAL (repl) = 1;
1920 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1922 if (DECL_NAME (access->base)
1923 && !DECL_IGNORED_P (access->base)
1924 && !DECL_ARTIFICIAL (access->base))
1926 char *pretty_name = make_fancy_name (access->expr);
1927 tree debug_expr = unshare_expr (access->expr), d;
1928 bool fail = false;
1930 DECL_NAME (repl) = get_identifier (pretty_name);
1931 obstack_free (&name_obstack, pretty_name);
1933 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1934 as DECL_DEBUG_EXPR isn't considered when looking for still
1935 used SSA_NAMEs and thus they could be freed. All debug info
1936 generation cares is whether something is constant or variable
1937 and that get_ref_base_and_extent works properly on the
1938 expression. It cannot handle accesses at a non-constant offset
1939 though, so just give up in those cases. */
1940 for (d = debug_expr;
1941 !fail && (handled_component_p (d) || TREE_CODE (d) == MEM_REF);
1942 d = TREE_OPERAND (d, 0))
1943 switch (TREE_CODE (d))
1945 case ARRAY_REF:
1946 case ARRAY_RANGE_REF:
1947 if (TREE_OPERAND (d, 1)
1948 && TREE_CODE (TREE_OPERAND (d, 1)) != INTEGER_CST)
1949 fail = true;
1950 if (TREE_OPERAND (d, 3)
1951 && TREE_CODE (TREE_OPERAND (d, 3)) != INTEGER_CST)
1952 fail = true;
1953 /* FALLTHRU */
1954 case COMPONENT_REF:
1955 if (TREE_OPERAND (d, 2)
1956 && TREE_CODE (TREE_OPERAND (d, 2)) != INTEGER_CST)
1957 fail = true;
1958 break;
1959 case MEM_REF:
1960 if (TREE_CODE (TREE_OPERAND (d, 0)) != ADDR_EXPR)
1961 fail = true;
1962 else
1963 d = TREE_OPERAND (d, 0);
1964 break;
1965 default:
1966 break;
1968 if (!fail)
1970 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1971 DECL_DEBUG_EXPR_IS_FROM (repl) = 1;
1973 if (access->grp_no_warning)
1974 TREE_NO_WARNING (repl) = 1;
1975 else
1976 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
1978 else
1979 TREE_NO_WARNING (repl) = 1;
1981 if (dump_file)
1983 if (access->grp_to_be_debug_replaced)
1985 fprintf (dump_file, "Created a debug-only replacement for ");
1986 print_generic_expr (dump_file, access->base, 0);
1987 fprintf (dump_file, " offset: %u, size: %u\n",
1988 (unsigned) access->offset, (unsigned) access->size);
1990 else
1992 fprintf (dump_file, "Created a replacement for ");
1993 print_generic_expr (dump_file, access->base, 0);
1994 fprintf (dump_file, " offset: %u, size: %u: ",
1995 (unsigned) access->offset, (unsigned) access->size);
1996 print_generic_expr (dump_file, repl, 0);
1997 fprintf (dump_file, "\n");
2000 sra_stats.replacements++;
2002 return repl;
2005 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
2007 static inline tree
2008 get_access_replacement (struct access *access)
2010 if (!access->replacement_decl)
2011 access->replacement_decl = create_access_replacement (access);
2012 return access->replacement_decl;
2016 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
2017 linked list along the way. Stop when *ACCESS is NULL or the access pointed
2018 to it is not "within" the root. Return false iff some accesses partially
2019 overlap. */
2021 static bool
2022 build_access_subtree (struct access **access)
2024 struct access *root = *access, *last_child = NULL;
2025 HOST_WIDE_INT limit = root->offset + root->size;
2027 *access = (*access)->next_grp;
2028 while (*access && (*access)->offset + (*access)->size <= limit)
2030 if (!last_child)
2031 root->first_child = *access;
2032 else
2033 last_child->next_sibling = *access;
2034 last_child = *access;
2036 if (!build_access_subtree (access))
2037 return false;
2040 if (*access && (*access)->offset < limit)
2041 return false;
2043 return true;
2046 /* Build a tree of access representatives, ACCESS is the pointer to the first
2047 one, others are linked in a list by the next_grp field. Return false iff
2048 some accesses partially overlap. */
2050 static bool
2051 build_access_trees (struct access *access)
2053 while (access)
2055 struct access *root = access;
2057 if (!build_access_subtree (&access))
2058 return false;
2059 root->next_grp = access;
2061 return true;
2064 /* Return true if expr contains some ARRAY_REFs into a variable bounded
2065 array. */
2067 static bool
2068 expr_with_var_bounded_array_refs_p (tree expr)
2070 while (handled_component_p (expr))
2072 if (TREE_CODE (expr) == ARRAY_REF
2073 && !host_integerp (array_ref_low_bound (expr), 0))
2074 return true;
2075 expr = TREE_OPERAND (expr, 0);
2077 return false;
2080 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2081 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2082 sorts of access flags appropriately along the way, notably always set
2083 grp_read and grp_assign_read according to MARK_READ and grp_write when
2084 MARK_WRITE is true.
2086 Creating a replacement for a scalar access is considered beneficial if its
2087 grp_hint is set (this means we are either attempting total scalarization or
2088 there is more than one direct read access) or according to the following
2089 table:
2091 Access written to through a scalar type (once or more times)
2093 | Written to in an assignment statement
2095 | | Access read as scalar _once_
2096 | | |
2097 | | | Read in an assignment statement
2098 | | | |
2099 | | | | Scalarize Comment
2100 -----------------------------------------------------------------------------
2101 0 0 0 0 No access for the scalar
2102 0 0 0 1 No access for the scalar
2103 0 0 1 0 No Single read - won't help
2104 0 0 1 1 No The same case
2105 0 1 0 0 No access for the scalar
2106 0 1 0 1 No access for the scalar
2107 0 1 1 0 Yes s = *g; return s.i;
2108 0 1 1 1 Yes The same case as above
2109 1 0 0 0 No Won't help
2110 1 0 0 1 Yes s.i = 1; *g = s;
2111 1 0 1 0 Yes s.i = 5; g = s.i;
2112 1 0 1 1 Yes The same case as above
2113 1 1 0 0 No Won't help.
2114 1 1 0 1 Yes s.i = 1; *g = s;
2115 1 1 1 0 Yes s = *g; return s.i;
2116 1 1 1 1 Yes Any of the above yeses */
2118 static bool
2119 analyze_access_subtree (struct access *root, struct access *parent,
2120 bool allow_replacements)
2122 struct access *child;
2123 HOST_WIDE_INT limit = root->offset + root->size;
2124 HOST_WIDE_INT covered_to = root->offset;
2125 bool scalar = is_gimple_reg_type (root->type);
2126 bool hole = false, sth_created = false;
2128 if (parent)
2130 if (parent->grp_read)
2131 root->grp_read = 1;
2132 if (parent->grp_assignment_read)
2133 root->grp_assignment_read = 1;
2134 if (parent->grp_write)
2135 root->grp_write = 1;
2136 if (parent->grp_assignment_write)
2137 root->grp_assignment_write = 1;
2138 if (parent->grp_total_scalarization)
2139 root->grp_total_scalarization = 1;
2142 if (root->grp_unscalarizable_region)
2143 allow_replacements = false;
2145 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2146 allow_replacements = false;
2148 for (child = root->first_child; child; child = child->next_sibling)
2150 hole |= covered_to < child->offset;
2151 sth_created |= analyze_access_subtree (child, root,
2152 allow_replacements && !scalar);
2154 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2155 root->grp_total_scalarization &= child->grp_total_scalarization;
2156 if (child->grp_covered)
2157 covered_to += child->size;
2158 else
2159 hole = true;
2162 if (allow_replacements && scalar && !root->first_child
2163 && (root->grp_hint
2164 || ((root->grp_scalar_read || root->grp_assignment_read)
2165 && (root->grp_scalar_write || root->grp_assignment_write))))
2167 bool new_integer_type;
2168 /* Always create access replacements that cover the whole access.
2169 For integral types this means the precision has to match.
2170 Avoid assumptions based on the integral type kind, too. */
2171 if (INTEGRAL_TYPE_P (root->type)
2172 && (TREE_CODE (root->type) != INTEGER_TYPE
2173 || TYPE_PRECISION (root->type) != root->size)
2174 /* But leave bitfield accesses alone. */
2175 && (TREE_CODE (root->expr) != COMPONENT_REF
2176 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2178 tree rt = root->type;
2179 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2180 && (root->size % BITS_PER_UNIT) == 0);
2181 root->type = build_nonstandard_integer_type (root->size,
2182 TYPE_UNSIGNED (rt));
2183 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2184 root->base, root->offset,
2185 root->type, NULL, false);
2186 new_integer_type = true;
2188 else
2189 new_integer_type = false;
2191 if (dump_file && (dump_flags & TDF_DETAILS))
2193 fprintf (dump_file, "Marking ");
2194 print_generic_expr (dump_file, root->base, 0);
2195 fprintf (dump_file, " offset: %u, size: %u ",
2196 (unsigned) root->offset, (unsigned) root->size);
2197 fprintf (dump_file, " to be replaced%s.\n",
2198 new_integer_type ? " with an integer": "");
2201 root->grp_to_be_replaced = 1;
2202 sth_created = true;
2203 hole = false;
2205 else
2207 if (MAY_HAVE_DEBUG_STMTS && allow_replacements
2208 && scalar && !root->first_child
2209 && (root->grp_scalar_write || root->grp_assignment_write))
2211 gcc_checking_assert (!root->grp_scalar_read
2212 && !root->grp_assignment_read);
2213 root->grp_to_be_debug_replaced = 1;
2214 if (dump_file && (dump_flags & TDF_DETAILS))
2216 fprintf (dump_file, "Marking ");
2217 print_generic_expr (dump_file, root->base, 0);
2218 fprintf (dump_file, " offset: %u, size: %u ",
2219 (unsigned) root->offset, (unsigned) root->size);
2220 fprintf (dump_file, " to be replaced with debug statements.\n");
2224 if (covered_to < limit)
2225 hole = true;
2226 if (scalar)
2227 root->grp_total_scalarization = 0;
2230 if (sth_created
2231 && (!hole || root->grp_total_scalarization))
2233 root->grp_covered = 1;
2234 return true;
2236 if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2237 root->grp_unscalarized_data = 1; /* not covered and written to */
2238 if (sth_created)
2239 return true;
2240 return false;
2243 /* Analyze all access trees linked by next_grp by the means of
2244 analyze_access_subtree. */
2245 static bool
2246 analyze_access_trees (struct access *access)
2248 bool ret = false;
2250 while (access)
2252 if (analyze_access_subtree (access, NULL, true))
2253 ret = true;
2254 access = access->next_grp;
2257 return ret;
2260 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2261 SIZE would conflict with an already existing one. If exactly such a child
2262 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2264 static bool
2265 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2266 HOST_WIDE_INT size, struct access **exact_match)
2268 struct access *child;
2270 for (child = lacc->first_child; child; child = child->next_sibling)
2272 if (child->offset == norm_offset && child->size == size)
2274 *exact_match = child;
2275 return true;
2278 if (child->offset < norm_offset + size
2279 && child->offset + child->size > norm_offset)
2280 return true;
2283 return false;
2286 /* Create a new child access of PARENT, with all properties just like MODEL
2287 except for its offset and with its grp_write false and grp_read true.
2288 Return the new access or NULL if it cannot be created. Note that this access
2289 is created long after all splicing and sorting, it's not located in any
2290 access vector and is automatically a representative of its group. */
2292 static struct access *
2293 create_artificial_child_access (struct access *parent, struct access *model,
2294 HOST_WIDE_INT new_offset)
2296 struct access *access;
2297 struct access **child;
2298 tree expr = parent->base;
2300 gcc_assert (!model->grp_unscalarizable_region);
2302 access = (struct access *) pool_alloc (access_pool);
2303 memset (access, 0, sizeof (struct access));
2304 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2305 model->type))
2307 access->grp_no_warning = true;
2308 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2309 new_offset, model, NULL, false);
2312 access->base = parent->base;
2313 access->expr = expr;
2314 access->offset = new_offset;
2315 access->size = model->size;
2316 access->type = model->type;
2317 access->grp_write = true;
2318 access->grp_read = false;
2320 child = &parent->first_child;
2321 while (*child && (*child)->offset < new_offset)
2322 child = &(*child)->next_sibling;
2324 access->next_sibling = *child;
2325 *child = access;
2327 return access;
2331 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2332 true if any new subaccess was created. Additionally, if RACC is a scalar
2333 access but LACC is not, change the type of the latter, if possible. */
2335 static bool
2336 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2338 struct access *rchild;
2339 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2340 bool ret = false;
2342 if (is_gimple_reg_type (lacc->type)
2343 || lacc->grp_unscalarizable_region
2344 || racc->grp_unscalarizable_region)
2345 return false;
2347 if (is_gimple_reg_type (racc->type))
2349 if (!lacc->first_child && !racc->first_child)
2351 tree t = lacc->base;
2353 lacc->type = racc->type;
2354 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2355 lacc->offset, racc->type))
2356 lacc->expr = t;
2357 else
2359 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2360 lacc->base, lacc->offset,
2361 racc, NULL, false);
2362 lacc->grp_no_warning = true;
2365 return false;
2368 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2370 struct access *new_acc = NULL;
2371 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2373 if (rchild->grp_unscalarizable_region)
2374 continue;
2376 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2377 &new_acc))
2379 if (new_acc)
2381 rchild->grp_hint = 1;
2382 new_acc->grp_hint |= new_acc->grp_read;
2383 if (rchild->first_child)
2384 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2386 continue;
2389 rchild->grp_hint = 1;
2390 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2391 if (new_acc)
2393 ret = true;
2394 if (racc->first_child)
2395 propagate_subaccesses_across_link (new_acc, rchild);
2399 return ret;
2402 /* Propagate all subaccesses across assignment links. */
2404 static void
2405 propagate_all_subaccesses (void)
2407 while (work_queue_head)
2409 struct access *racc = pop_access_from_work_queue ();
2410 struct assign_link *link;
2412 gcc_assert (racc->first_link);
2414 for (link = racc->first_link; link; link = link->next)
2416 struct access *lacc = link->lacc;
2418 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2419 continue;
2420 lacc = lacc->group_representative;
2421 if (propagate_subaccesses_across_link (lacc, racc)
2422 && lacc->first_link)
2423 add_access_to_work_queue (lacc);
2428 /* Go through all accesses collected throughout the (intraprocedural) analysis
2429 stage, exclude overlapping ones, identify representatives and build trees
2430 out of them, making decisions about scalarization on the way. Return true
2431 iff there are any to-be-scalarized variables after this stage. */
2433 static bool
2434 analyze_all_variable_accesses (void)
2436 int res = 0;
2437 bitmap tmp = BITMAP_ALLOC (NULL);
2438 bitmap_iterator bi;
2439 unsigned i, max_total_scalarization_size;
2441 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2442 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2444 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2445 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2446 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2448 tree var = candidate (i);
2450 if (TREE_CODE (var) == VAR_DECL
2451 && type_consists_of_records_p (TREE_TYPE (var)))
2453 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2454 <= max_total_scalarization_size)
2456 completely_scalarize_var (var);
2457 if (dump_file && (dump_flags & TDF_DETAILS))
2459 fprintf (dump_file, "Will attempt to totally scalarize ");
2460 print_generic_expr (dump_file, var, 0);
2461 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2464 else if (dump_file && (dump_flags & TDF_DETAILS))
2466 fprintf (dump_file, "Too big to totally scalarize: ");
2467 print_generic_expr (dump_file, var, 0);
2468 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2473 bitmap_copy (tmp, candidate_bitmap);
2474 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2476 tree var = candidate (i);
2477 struct access *access;
2479 access = sort_and_splice_var_accesses (var);
2480 if (!access || !build_access_trees (access))
2481 disqualify_candidate (var,
2482 "No or inhibitingly overlapping accesses.");
2485 propagate_all_subaccesses ();
2487 bitmap_copy (tmp, candidate_bitmap);
2488 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2490 tree var = candidate (i);
2491 struct access *access = get_first_repr_for_decl (var);
2493 if (analyze_access_trees (access))
2495 res++;
2496 if (dump_file && (dump_flags & TDF_DETAILS))
2498 fprintf (dump_file, "\nAccess trees for ");
2499 print_generic_expr (dump_file, var, 0);
2500 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2501 dump_access_tree (dump_file, access);
2502 fprintf (dump_file, "\n");
2505 else
2506 disqualify_candidate (var, "No scalar replacements to be created.");
2509 BITMAP_FREE (tmp);
2511 if (res)
2513 statistics_counter_event (cfun, "Scalarized aggregates", res);
2514 return true;
2516 else
2517 return false;
2520 /* Generate statements copying scalar replacements of accesses within a subtree
2521 into or out of AGG. ACCESS, all its children, siblings and their children
2522 are to be processed. AGG is an aggregate type expression (can be a
2523 declaration but does not have to be, it can for example also be a mem_ref or
2524 a series of handled components). TOP_OFFSET is the offset of the processed
2525 subtree which has to be subtracted from offsets of individual accesses to
2526 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2527 replacements in the interval <start_offset, start_offset + chunk_size>,
2528 otherwise copy all. GSI is a statement iterator used to place the new
2529 statements. WRITE should be true when the statements should write from AGG
2530 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2531 statements will be added after the current statement in GSI, they will be
2532 added before the statement otherwise. */
2534 static void
2535 generate_subtree_copies (struct access *access, tree agg,
2536 HOST_WIDE_INT top_offset,
2537 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2538 gimple_stmt_iterator *gsi, bool write,
2539 bool insert_after, location_t loc)
2543 if (chunk_size && access->offset >= start_offset + chunk_size)
2544 return;
2546 if (access->grp_to_be_replaced
2547 && (chunk_size == 0
2548 || access->offset + access->size > start_offset))
2550 tree expr, repl = get_access_replacement (access);
2551 gimple stmt;
2553 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2554 access, gsi, insert_after);
2556 if (write)
2558 if (access->grp_partial_lhs)
2559 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2560 !insert_after,
2561 insert_after ? GSI_NEW_STMT
2562 : GSI_SAME_STMT);
2563 stmt = gimple_build_assign (repl, expr);
2565 else
2567 TREE_NO_WARNING (repl) = 1;
2568 if (access->grp_partial_lhs)
2569 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2570 !insert_after,
2571 insert_after ? GSI_NEW_STMT
2572 : GSI_SAME_STMT);
2573 stmt = gimple_build_assign (expr, repl);
2575 gimple_set_location (stmt, loc);
2577 if (insert_after)
2578 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2579 else
2580 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2581 update_stmt (stmt);
2582 sra_stats.subtree_copies++;
2584 else if (write
2585 && access->grp_to_be_debug_replaced
2586 && (chunk_size == 0
2587 || access->offset + access->size > start_offset))
2589 gimple ds;
2590 tree drhs = build_debug_ref_for_model (loc, agg,
2591 access->offset - top_offset,
2592 access);
2593 ds = gimple_build_debug_bind (get_access_replacement (access),
2594 drhs, gsi_stmt (*gsi));
2595 if (insert_after)
2596 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2597 else
2598 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2601 if (access->first_child)
2602 generate_subtree_copies (access->first_child, agg, top_offset,
2603 start_offset, chunk_size, gsi,
2604 write, insert_after, loc);
2606 access = access->next_sibling;
2608 while (access);
2611 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2612 the root of the subtree to be processed. GSI is the statement iterator used
2613 for inserting statements which are added after the current statement if
2614 INSERT_AFTER is true or before it otherwise. */
2616 static void
2617 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2618 bool insert_after, location_t loc)
2621 struct access *child;
2623 if (access->grp_to_be_replaced)
2625 gimple stmt;
2627 stmt = gimple_build_assign (get_access_replacement (access),
2628 build_zero_cst (access->type));
2629 if (insert_after)
2630 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2631 else
2632 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2633 update_stmt (stmt);
2634 gimple_set_location (stmt, loc);
2636 else if (access->grp_to_be_debug_replaced)
2638 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2639 build_zero_cst (access->type),
2640 gsi_stmt (*gsi));
2641 if (insert_after)
2642 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2643 else
2644 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2647 for (child = access->first_child; child; child = child->next_sibling)
2648 init_subtree_with_zero (child, gsi, insert_after, loc);
2651 /* Search for an access representative for the given expression EXPR and
2652 return it or NULL if it cannot be found. */
2654 static struct access *
2655 get_access_for_expr (tree expr)
2657 HOST_WIDE_INT offset, size, max_size;
2658 tree base;
2660 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2661 a different size than the size of its argument and we need the latter
2662 one. */
2663 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2664 expr = TREE_OPERAND (expr, 0);
2666 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2667 if (max_size == -1 || !DECL_P (base))
2668 return NULL;
2670 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2671 return NULL;
2673 return get_var_base_offset_size_access (base, offset, max_size);
2676 /* Replace the expression EXPR with a scalar replacement if there is one and
2677 generate other statements to do type conversion or subtree copying if
2678 necessary. GSI is used to place newly created statements, WRITE is true if
2679 the expression is being written to (it is on a LHS of a statement or output
2680 in an assembly statement). */
2682 static bool
2683 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2685 location_t loc;
2686 struct access *access;
2687 tree type, bfr;
2689 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2691 bfr = *expr;
2692 expr = &TREE_OPERAND (*expr, 0);
2694 else
2695 bfr = NULL_TREE;
2697 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2698 expr = &TREE_OPERAND (*expr, 0);
2699 access = get_access_for_expr (*expr);
2700 if (!access)
2701 return false;
2702 type = TREE_TYPE (*expr);
2704 loc = gimple_location (gsi_stmt (*gsi));
2705 if (access->grp_to_be_replaced)
2707 tree repl = get_access_replacement (access);
2708 /* If we replace a non-register typed access simply use the original
2709 access expression to extract the scalar component afterwards.
2710 This happens if scalarizing a function return value or parameter
2711 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2712 gcc.c-torture/compile/20011217-1.c.
2714 We also want to use this when accessing a complex or vector which can
2715 be accessed as a different type too, potentially creating a need for
2716 type conversion (see PR42196) and when scalarized unions are involved
2717 in assembler statements (see PR42398). */
2718 if (!useless_type_conversion_p (type, access->type))
2720 tree ref;
2722 ref = build_ref_for_model (loc, access->base, access->offset, access,
2723 NULL, false);
2725 if (write)
2727 gimple stmt;
2729 if (access->grp_partial_lhs)
2730 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2731 false, GSI_NEW_STMT);
2732 stmt = gimple_build_assign (repl, ref);
2733 gimple_set_location (stmt, loc);
2734 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2736 else
2738 gimple stmt;
2740 if (access->grp_partial_lhs)
2741 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2742 true, GSI_SAME_STMT);
2743 stmt = gimple_build_assign (ref, repl);
2744 gimple_set_location (stmt, loc);
2745 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2748 else
2749 *expr = repl;
2750 sra_stats.exprs++;
2752 else if (write && access->grp_to_be_debug_replaced)
2754 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2755 NULL_TREE,
2756 gsi_stmt (*gsi));
2757 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2760 if (access->first_child)
2762 HOST_WIDE_INT start_offset, chunk_size;
2763 if (bfr
2764 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2765 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2767 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2768 start_offset = access->offset
2769 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2771 else
2772 start_offset = chunk_size = 0;
2774 generate_subtree_copies (access->first_child, access->base, 0,
2775 start_offset, chunk_size, gsi, write, write,
2776 loc);
2778 return true;
2781 /* Where scalar replacements of the RHS have been written to when a replacement
2782 of a LHS of an assigments cannot be direclty loaded from a replacement of
2783 the RHS. */
2784 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2785 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2786 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2788 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2789 base aggregate if there are unscalarized data or directly to LHS of the
2790 statement that is pointed to by GSI otherwise. */
2792 static enum unscalarized_data_handling
2793 handle_unscalarized_data_in_subtree (struct access *top_racc,
2794 gimple_stmt_iterator *gsi)
2796 if (top_racc->grp_unscalarized_data)
2798 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2799 gsi, false, false,
2800 gimple_location (gsi_stmt (*gsi)));
2801 return SRA_UDH_RIGHT;
2803 else
2805 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2806 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2807 0, 0, gsi, false, false,
2808 gimple_location (gsi_stmt (*gsi)));
2809 return SRA_UDH_LEFT;
2814 /* Try to generate statements to load all sub-replacements in an access subtree
2815 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2816 If that is not possible, refresh the TOP_RACC base aggregate and load the
2817 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2818 copied. NEW_GSI is stmt iterator used for statement insertions after the
2819 original assignment, OLD_GSI is used to insert statements before the
2820 assignment. *REFRESHED keeps the information whether we have needed to
2821 refresh replacements of the LHS and from which side of the assignments this
2822 takes place. */
2824 static void
2825 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2826 HOST_WIDE_INT left_offset,
2827 gimple_stmt_iterator *old_gsi,
2828 gimple_stmt_iterator *new_gsi,
2829 enum unscalarized_data_handling *refreshed)
2831 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2832 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2834 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2836 if (lacc->grp_to_be_replaced)
2838 struct access *racc;
2839 gimple stmt;
2840 tree rhs;
2842 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2843 if (racc && racc->grp_to_be_replaced)
2845 rhs = get_access_replacement (racc);
2846 if (!useless_type_conversion_p (lacc->type, racc->type))
2847 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2849 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2850 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2851 true, GSI_SAME_STMT);
2853 else
2855 /* No suitable access on the right hand side, need to load from
2856 the aggregate. See if we have to update it first... */
2857 if (*refreshed == SRA_UDH_NONE)
2858 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2859 old_gsi);
2861 if (*refreshed == SRA_UDH_LEFT)
2862 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2863 new_gsi, true);
2864 else
2865 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2866 new_gsi, true);
2867 if (lacc->grp_partial_lhs)
2868 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2869 false, GSI_NEW_STMT);
2872 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2873 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2874 gimple_set_location (stmt, loc);
2875 update_stmt (stmt);
2876 sra_stats.subreplacements++;
2878 else
2880 if (*refreshed == SRA_UDH_NONE
2881 && lacc->grp_read && !lacc->grp_covered)
2882 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2883 old_gsi);
2884 if (lacc && lacc->grp_to_be_debug_replaced)
2886 gimple ds;
2887 tree drhs;
2888 struct access *racc = find_access_in_subtree (top_racc, offset,
2889 lacc->size);
2891 if (racc && racc->grp_to_be_replaced)
2892 drhs = get_access_replacement (racc);
2893 else if (*refreshed == SRA_UDH_LEFT)
2894 drhs = build_debug_ref_for_model (loc, lacc->base, lacc->offset,
2895 lacc);
2896 else if (*refreshed == SRA_UDH_RIGHT)
2897 drhs = build_debug_ref_for_model (loc, top_racc->base, offset,
2898 lacc);
2899 else
2900 drhs = NULL_TREE;
2901 ds = gimple_build_debug_bind (get_access_replacement (lacc),
2902 drhs, gsi_stmt (*old_gsi));
2903 gsi_insert_after (new_gsi, ds, GSI_NEW_STMT);
2907 if (lacc->first_child)
2908 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2909 old_gsi, new_gsi, refreshed);
2913 /* Result code for SRA assignment modification. */
2914 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2915 SRA_AM_MODIFIED, /* stmt changed but not
2916 removed */
2917 SRA_AM_REMOVED }; /* stmt eliminated */
2919 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2920 to the assignment and GSI is the statement iterator pointing at it. Returns
2921 the same values as sra_modify_assign. */
2923 static enum assignment_mod_result
2924 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2926 tree lhs = gimple_assign_lhs (*stmt);
2927 struct access *acc;
2928 location_t loc;
2930 acc = get_access_for_expr (lhs);
2931 if (!acc)
2932 return SRA_AM_NONE;
2934 if (gimple_clobber_p (*stmt))
2936 /* Remove clobbers of fully scalarized variables, otherwise
2937 do nothing. */
2938 if (acc->grp_covered)
2940 unlink_stmt_vdef (*stmt);
2941 gsi_remove (gsi, true);
2942 release_defs (*stmt);
2943 return SRA_AM_REMOVED;
2945 else
2946 return SRA_AM_NONE;
2949 loc = gimple_location (*stmt);
2950 if (vec_safe_length (CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2952 /* I have never seen this code path trigger but if it can happen the
2953 following should handle it gracefully. */
2954 if (access_has_children_p (acc))
2955 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2956 true, true, loc);
2957 return SRA_AM_MODIFIED;
2960 if (acc->grp_covered)
2962 init_subtree_with_zero (acc, gsi, false, loc);
2963 unlink_stmt_vdef (*stmt);
2964 gsi_remove (gsi, true);
2965 release_defs (*stmt);
2966 return SRA_AM_REMOVED;
2968 else
2970 init_subtree_with_zero (acc, gsi, true, loc);
2971 return SRA_AM_MODIFIED;
2975 /* Create and return a new suitable default definition SSA_NAME for RACC which
2976 is an access describing an uninitialized part of an aggregate that is being
2977 loaded. */
2979 static tree
2980 get_repl_default_def_ssa_name (struct access *racc)
2982 return get_or_create_ssa_default_def (cfun, get_access_replacement (racc));
2985 /* Return true if REF has a COMPONENT_REF with a bit-field field declaration
2986 somewhere in it. */
2988 static inline bool
2989 contains_bitfld_comp_ref_p (const_tree ref)
2991 while (handled_component_p (ref))
2993 if (TREE_CODE (ref) == COMPONENT_REF
2994 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
2995 return true;
2996 ref = TREE_OPERAND (ref, 0);
2999 return false;
3002 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3003 bit-field field declaration somewhere in it. */
3005 static inline bool
3006 contains_vce_or_bfcref_p (const_tree ref)
3008 while (handled_component_p (ref))
3010 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3011 || (TREE_CODE (ref) == COMPONENT_REF
3012 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3013 return true;
3014 ref = TREE_OPERAND (ref, 0);
3017 return false;
3020 /* Examine both sides of the assignment statement pointed to by STMT, replace
3021 them with a scalare replacement if there is one and generate copying of
3022 replacements if scalarized aggregates have been used in the assignment. GSI
3023 is used to hold generated statements for type conversions and subtree
3024 copying. */
3026 static enum assignment_mod_result
3027 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3029 struct access *lacc, *racc;
3030 tree lhs, rhs;
3031 bool modify_this_stmt = false;
3032 bool force_gimple_rhs = false;
3033 location_t loc;
3034 gimple_stmt_iterator orig_gsi = *gsi;
3036 if (!gimple_assign_single_p (*stmt))
3037 return SRA_AM_NONE;
3038 lhs = gimple_assign_lhs (*stmt);
3039 rhs = gimple_assign_rhs1 (*stmt);
3041 if (TREE_CODE (rhs) == CONSTRUCTOR)
3042 return sra_modify_constructor_assign (stmt, gsi);
3044 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3045 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3046 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3048 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3049 gsi, false);
3050 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3051 gsi, true);
3052 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3055 lacc = get_access_for_expr (lhs);
3056 racc = get_access_for_expr (rhs);
3057 if (!lacc && !racc)
3058 return SRA_AM_NONE;
3060 loc = gimple_location (*stmt);
3061 if (lacc && lacc->grp_to_be_replaced)
3063 lhs = get_access_replacement (lacc);
3064 gimple_assign_set_lhs (*stmt, lhs);
3065 modify_this_stmt = true;
3066 if (lacc->grp_partial_lhs)
3067 force_gimple_rhs = true;
3068 sra_stats.exprs++;
3071 if (racc && racc->grp_to_be_replaced)
3073 rhs = get_access_replacement (racc);
3074 modify_this_stmt = true;
3075 if (racc->grp_partial_lhs)
3076 force_gimple_rhs = true;
3077 sra_stats.exprs++;
3079 else if (racc
3080 && !racc->grp_unscalarized_data
3081 && TREE_CODE (lhs) == SSA_NAME
3082 && !access_has_replacements_p (racc))
3084 rhs = get_repl_default_def_ssa_name (racc);
3085 modify_this_stmt = true;
3086 sra_stats.exprs++;
3089 if (modify_this_stmt)
3091 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3093 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3094 ??? This should move to fold_stmt which we simply should
3095 call after building a VIEW_CONVERT_EXPR here. */
3096 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3097 && !contains_bitfld_comp_ref_p (lhs)
3098 && !access_has_children_p (lacc))
3100 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3101 gimple_assign_set_lhs (*stmt, lhs);
3103 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3104 && !contains_vce_or_bfcref_p (rhs)
3105 && !access_has_children_p (racc))
3106 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3108 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3110 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3111 rhs);
3112 if (is_gimple_reg_type (TREE_TYPE (lhs))
3113 && TREE_CODE (lhs) != SSA_NAME)
3114 force_gimple_rhs = true;
3119 if (lacc && lacc->grp_to_be_debug_replaced)
3121 gimple ds = gimple_build_debug_bind (get_access_replacement (lacc),
3122 unshare_expr (rhs), *stmt);
3123 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3126 /* From this point on, the function deals with assignments in between
3127 aggregates when at least one has scalar reductions of some of its
3128 components. There are three possible scenarios: Both the LHS and RHS have
3129 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3131 In the first case, we would like to load the LHS components from RHS
3132 components whenever possible. If that is not possible, we would like to
3133 read it directly from the RHS (after updating it by storing in it its own
3134 components). If there are some necessary unscalarized data in the LHS,
3135 those will be loaded by the original assignment too. If neither of these
3136 cases happen, the original statement can be removed. Most of this is done
3137 by load_assign_lhs_subreplacements.
3139 In the second case, we would like to store all RHS scalarized components
3140 directly into LHS and if they cover the aggregate completely, remove the
3141 statement too. In the third case, we want the LHS components to be loaded
3142 directly from the RHS (DSE will remove the original statement if it
3143 becomes redundant).
3145 This is a bit complex but manageable when types match and when unions do
3146 not cause confusion in a way that we cannot really load a component of LHS
3147 from the RHS or vice versa (the access representing this level can have
3148 subaccesses that are accessible only through a different union field at a
3149 higher level - different from the one used in the examined expression).
3150 Unions are fun.
3152 Therefore, I specially handle a fourth case, happening when there is a
3153 specific type cast or it is impossible to locate a scalarized subaccess on
3154 the other side of the expression. If that happens, I simply "refresh" the
3155 RHS by storing in it is scalarized components leave the original statement
3156 there to do the copying and then load the scalar replacements of the LHS.
3157 This is what the first branch does. */
3159 if (modify_this_stmt
3160 || gimple_has_volatile_ops (*stmt)
3161 || contains_vce_or_bfcref_p (rhs)
3162 || contains_vce_or_bfcref_p (lhs))
3164 if (access_has_children_p (racc))
3165 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3166 gsi, false, false, loc);
3167 if (access_has_children_p (lacc))
3168 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3169 gsi, true, true, loc);
3170 sra_stats.separate_lhs_rhs_handling++;
3172 /* This gimplification must be done after generate_subtree_copies,
3173 lest we insert the subtree copies in the middle of the gimplified
3174 sequence. */
3175 if (force_gimple_rhs)
3176 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3177 true, GSI_SAME_STMT);
3178 if (gimple_assign_rhs1 (*stmt) != rhs)
3180 modify_this_stmt = true;
3181 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3182 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3185 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3187 else
3189 if (access_has_children_p (lacc)
3190 && access_has_children_p (racc)
3191 /* When an access represents an unscalarizable region, it usually
3192 represents accesses with variable offset and thus must not be used
3193 to generate new memory accesses. */
3194 && !lacc->grp_unscalarizable_region
3195 && !racc->grp_unscalarizable_region)
3197 gimple_stmt_iterator orig_gsi = *gsi;
3198 enum unscalarized_data_handling refreshed;
3200 if (lacc->grp_read && !lacc->grp_covered)
3201 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3202 else
3203 refreshed = SRA_UDH_NONE;
3205 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3206 &orig_gsi, gsi, &refreshed);
3207 if (refreshed != SRA_UDH_RIGHT)
3209 gsi_next (gsi);
3210 unlink_stmt_vdef (*stmt);
3211 gsi_remove (&orig_gsi, true);
3212 release_defs (*stmt);
3213 sra_stats.deleted++;
3214 return SRA_AM_REMOVED;
3217 else
3219 if (access_has_children_p (racc)
3220 && !racc->grp_unscalarized_data)
3222 if (dump_file)
3224 fprintf (dump_file, "Removing load: ");
3225 print_gimple_stmt (dump_file, *stmt, 0, 0);
3227 generate_subtree_copies (racc->first_child, lhs,
3228 racc->offset, 0, 0, gsi,
3229 false, false, loc);
3230 gcc_assert (*stmt == gsi_stmt (*gsi));
3231 unlink_stmt_vdef (*stmt);
3232 gsi_remove (gsi, true);
3233 release_defs (*stmt);
3234 sra_stats.deleted++;
3235 return SRA_AM_REMOVED;
3237 /* Restore the aggregate RHS from its components so the
3238 prevailing aggregate copy does the right thing. */
3239 if (access_has_children_p (racc))
3240 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3241 gsi, false, false, loc);
3242 /* Re-load the components of the aggregate copy destination.
3243 But use the RHS aggregate to load from to expose more
3244 optimization opportunities. */
3245 if (access_has_children_p (lacc))
3246 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3247 0, 0, gsi, true, true, loc);
3250 return SRA_AM_NONE;
3254 /* Traverse the function body and all modifications as decided in
3255 analyze_all_variable_accesses. Return true iff the CFG has been
3256 changed. */
3258 static bool
3259 sra_modify_function_body (void)
3261 bool cfg_changed = false;
3262 basic_block bb;
3264 FOR_EACH_BB (bb)
3266 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3267 while (!gsi_end_p (gsi))
3269 gimple stmt = gsi_stmt (gsi);
3270 enum assignment_mod_result assign_result;
3271 bool modified = false, deleted = false;
3272 tree *t;
3273 unsigned i;
3275 switch (gimple_code (stmt))
3277 case GIMPLE_RETURN:
3278 t = gimple_return_retval_ptr (stmt);
3279 if (*t != NULL_TREE)
3280 modified |= sra_modify_expr (t, &gsi, false);
3281 break;
3283 case GIMPLE_ASSIGN:
3284 assign_result = sra_modify_assign (&stmt, &gsi);
3285 modified |= assign_result == SRA_AM_MODIFIED;
3286 deleted = assign_result == SRA_AM_REMOVED;
3287 break;
3289 case GIMPLE_CALL:
3290 /* Operands must be processed before the lhs. */
3291 for (i = 0; i < gimple_call_num_args (stmt); i++)
3293 t = gimple_call_arg_ptr (stmt, i);
3294 modified |= sra_modify_expr (t, &gsi, false);
3297 if (gimple_call_lhs (stmt))
3299 t = gimple_call_lhs_ptr (stmt);
3300 modified |= sra_modify_expr (t, &gsi, true);
3302 break;
3304 case GIMPLE_ASM:
3305 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3307 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3308 modified |= sra_modify_expr (t, &gsi, false);
3310 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3312 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3313 modified |= sra_modify_expr (t, &gsi, true);
3315 break;
3317 default:
3318 break;
3321 if (modified)
3323 update_stmt (stmt);
3324 if (maybe_clean_eh_stmt (stmt)
3325 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3326 cfg_changed = true;
3328 if (!deleted)
3329 gsi_next (&gsi);
3333 return cfg_changed;
3336 /* Generate statements initializing scalar replacements of parts of function
3337 parameters. */
3339 static void
3340 initialize_parameter_reductions (void)
3342 gimple_stmt_iterator gsi;
3343 gimple_seq seq = NULL;
3344 tree parm;
3346 gsi = gsi_start (seq);
3347 for (parm = DECL_ARGUMENTS (current_function_decl);
3348 parm;
3349 parm = DECL_CHAIN (parm))
3351 vec<access_p> *access_vec;
3352 struct access *access;
3354 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3355 continue;
3356 access_vec = get_base_access_vector (parm);
3357 if (!access_vec)
3358 continue;
3360 for (access = (*access_vec)[0];
3361 access;
3362 access = access->next_grp)
3363 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3364 EXPR_LOCATION (parm));
3367 seq = gsi_seq (gsi);
3368 if (seq)
3369 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3372 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3373 it reveals there are components of some aggregates to be scalarized, it runs
3374 the required transformations. */
3375 static unsigned int
3376 perform_intra_sra (void)
3378 int ret = 0;
3379 sra_initialize ();
3381 if (!find_var_candidates ())
3382 goto out;
3384 if (!scan_function ())
3385 goto out;
3387 if (!analyze_all_variable_accesses ())
3388 goto out;
3390 if (sra_modify_function_body ())
3391 ret = TODO_update_ssa | TODO_cleanup_cfg;
3392 else
3393 ret = TODO_update_ssa;
3394 initialize_parameter_reductions ();
3396 statistics_counter_event (cfun, "Scalar replacements created",
3397 sra_stats.replacements);
3398 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3399 statistics_counter_event (cfun, "Subtree copy stmts",
3400 sra_stats.subtree_copies);
3401 statistics_counter_event (cfun, "Subreplacement stmts",
3402 sra_stats.subreplacements);
3403 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3404 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3405 sra_stats.separate_lhs_rhs_handling);
3407 out:
3408 sra_deinitialize ();
3409 return ret;
3412 /* Perform early intraprocedural SRA. */
3413 static unsigned int
3414 early_intra_sra (void)
3416 sra_mode = SRA_MODE_EARLY_INTRA;
3417 return perform_intra_sra ();
3420 /* Perform "late" intraprocedural SRA. */
3421 static unsigned int
3422 late_intra_sra (void)
3424 sra_mode = SRA_MODE_INTRA;
3425 return perform_intra_sra ();
3429 static bool
3430 gate_intra_sra (void)
3432 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3436 struct gimple_opt_pass pass_sra_early =
3439 GIMPLE_PASS,
3440 "esra", /* name */
3441 OPTGROUP_NONE, /* optinfo_flags */
3442 gate_intra_sra, /* gate */
3443 early_intra_sra, /* execute */
3444 NULL, /* sub */
3445 NULL, /* next */
3446 0, /* static_pass_number */
3447 TV_TREE_SRA, /* tv_id */
3448 PROP_cfg | PROP_ssa, /* properties_required */
3449 0, /* properties_provided */
3450 0, /* properties_destroyed */
3451 0, /* todo_flags_start */
3452 TODO_update_ssa
3453 | TODO_ggc_collect
3454 | TODO_verify_ssa /* todo_flags_finish */
3458 struct gimple_opt_pass pass_sra =
3461 GIMPLE_PASS,
3462 "sra", /* name */
3463 OPTGROUP_NONE, /* optinfo_flags */
3464 gate_intra_sra, /* gate */
3465 late_intra_sra, /* execute */
3466 NULL, /* sub */
3467 NULL, /* next */
3468 0, /* static_pass_number */
3469 TV_TREE_SRA, /* tv_id */
3470 PROP_cfg | PROP_ssa, /* properties_required */
3471 0, /* properties_provided */
3472 0, /* properties_destroyed */
3473 TODO_update_address_taken, /* todo_flags_start */
3474 TODO_update_ssa
3475 | TODO_ggc_collect
3476 | TODO_verify_ssa /* todo_flags_finish */
3481 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3482 parameter. */
3484 static bool
3485 is_unused_scalar_param (tree parm)
3487 tree name;
3488 return (is_gimple_reg (parm)
3489 && (!(name = ssa_default_def (cfun, parm))
3490 || has_zero_uses (name)));
3493 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3494 examine whether there are any direct or otherwise infeasible ones. If so,
3495 return true, otherwise return false. PARM must be a gimple register with a
3496 non-NULL default definition. */
3498 static bool
3499 ptr_parm_has_direct_uses (tree parm)
3501 imm_use_iterator ui;
3502 gimple stmt;
3503 tree name = ssa_default_def (cfun, parm);
3504 bool ret = false;
3506 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3508 int uses_ok = 0;
3509 use_operand_p use_p;
3511 if (is_gimple_debug (stmt))
3512 continue;
3514 /* Valid uses include dereferences on the lhs and the rhs. */
3515 if (gimple_has_lhs (stmt))
3517 tree lhs = gimple_get_lhs (stmt);
3518 while (handled_component_p (lhs))
3519 lhs = TREE_OPERAND (lhs, 0);
3520 if (TREE_CODE (lhs) == MEM_REF
3521 && TREE_OPERAND (lhs, 0) == name
3522 && integer_zerop (TREE_OPERAND (lhs, 1))
3523 && types_compatible_p (TREE_TYPE (lhs),
3524 TREE_TYPE (TREE_TYPE (name)))
3525 && !TREE_THIS_VOLATILE (lhs))
3526 uses_ok++;
3528 if (gimple_assign_single_p (stmt))
3530 tree rhs = gimple_assign_rhs1 (stmt);
3531 while (handled_component_p (rhs))
3532 rhs = TREE_OPERAND (rhs, 0);
3533 if (TREE_CODE (rhs) == MEM_REF
3534 && TREE_OPERAND (rhs, 0) == name
3535 && integer_zerop (TREE_OPERAND (rhs, 1))
3536 && types_compatible_p (TREE_TYPE (rhs),
3537 TREE_TYPE (TREE_TYPE (name)))
3538 && !TREE_THIS_VOLATILE (rhs))
3539 uses_ok++;
3541 else if (is_gimple_call (stmt))
3543 unsigned i;
3544 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3546 tree arg = gimple_call_arg (stmt, i);
3547 while (handled_component_p (arg))
3548 arg = TREE_OPERAND (arg, 0);
3549 if (TREE_CODE (arg) == MEM_REF
3550 && TREE_OPERAND (arg, 0) == name
3551 && integer_zerop (TREE_OPERAND (arg, 1))
3552 && types_compatible_p (TREE_TYPE (arg),
3553 TREE_TYPE (TREE_TYPE (name)))
3554 && !TREE_THIS_VOLATILE (arg))
3555 uses_ok++;
3559 /* If the number of valid uses does not match the number of
3560 uses in this stmt there is an unhandled use. */
3561 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3562 --uses_ok;
3564 if (uses_ok != 0)
3565 ret = true;
3567 if (ret)
3568 BREAK_FROM_IMM_USE_STMT (ui);
3571 return ret;
3574 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3575 them in candidate_bitmap. Note that these do not necessarily include
3576 parameter which are unused and thus can be removed. Return true iff any
3577 such candidate has been found. */
3579 static bool
3580 find_param_candidates (void)
3582 tree parm;
3583 int count = 0;
3584 bool ret = false;
3585 const char *msg;
3587 for (parm = DECL_ARGUMENTS (current_function_decl);
3588 parm;
3589 parm = DECL_CHAIN (parm))
3591 tree type = TREE_TYPE (parm);
3592 void **slot;
3594 count++;
3596 if (TREE_THIS_VOLATILE (parm)
3597 || TREE_ADDRESSABLE (parm)
3598 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3599 continue;
3601 if (is_unused_scalar_param (parm))
3603 ret = true;
3604 continue;
3607 if (POINTER_TYPE_P (type))
3609 type = TREE_TYPE (type);
3611 if (TREE_CODE (type) == FUNCTION_TYPE
3612 || TYPE_VOLATILE (type)
3613 || upc_shared_type_p (type)
3614 || (TREE_CODE (type) == ARRAY_TYPE
3615 && TYPE_NONALIASED_COMPONENT (type))
3616 || !is_gimple_reg (parm)
3617 || is_va_list_type (type)
3618 || ptr_parm_has_direct_uses (parm))
3619 continue;
3621 else if (!AGGREGATE_TYPE_P (type))
3622 continue;
3624 if (!COMPLETE_TYPE_P (type)
3625 || !host_integerp (TYPE_SIZE (type), 1)
3626 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3627 || (AGGREGATE_TYPE_P (type)
3628 && type_internals_preclude_sra_p (type, &msg)))
3629 continue;
3631 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3632 slot = htab_find_slot_with_hash (candidates, parm,
3633 DECL_UID (parm), INSERT);
3634 *slot = (void *) parm;
3636 ret = true;
3637 if (dump_file && (dump_flags & TDF_DETAILS))
3639 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3640 print_generic_expr (dump_file, parm, 0);
3641 fprintf (dump_file, "\n");
3645 func_param_count = count;
3646 return ret;
3649 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3650 maybe_modified. */
3652 static bool
3653 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3654 void *data)
3656 struct access *repr = (struct access *) data;
3658 repr->grp_maybe_modified = 1;
3659 return true;
3662 /* Analyze what representatives (in linked lists accessible from
3663 REPRESENTATIVES) can be modified by side effects of statements in the
3664 current function. */
3666 static void
3667 analyze_modified_params (vec<access_p> representatives)
3669 int i;
3671 for (i = 0; i < func_param_count; i++)
3673 struct access *repr;
3675 for (repr = representatives[i];
3676 repr;
3677 repr = repr->next_grp)
3679 struct access *access;
3680 bitmap visited;
3681 ao_ref ar;
3683 if (no_accesses_p (repr))
3684 continue;
3685 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3686 || repr->grp_maybe_modified)
3687 continue;
3689 ao_ref_init (&ar, repr->expr);
3690 visited = BITMAP_ALLOC (NULL);
3691 for (access = repr; access; access = access->next_sibling)
3693 /* All accesses are read ones, otherwise grp_maybe_modified would
3694 be trivially set. */
3695 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3696 mark_maybe_modified, repr, &visited);
3697 if (repr->grp_maybe_modified)
3698 break;
3700 BITMAP_FREE (visited);
3705 /* Propagate distances in bb_dereferences in the opposite direction than the
3706 control flow edges, in each step storing the maximum of the current value
3707 and the minimum of all successors. These steps are repeated until the table
3708 stabilizes. Note that BBs which might terminate the functions (according to
3709 final_bbs bitmap) never updated in this way. */
3711 static void
3712 propagate_dereference_distances (void)
3714 vec<basic_block> queue;
3715 basic_block bb;
3717 queue.create (last_basic_block_for_function (cfun));
3718 queue.quick_push (ENTRY_BLOCK_PTR);
3719 FOR_EACH_BB (bb)
3721 queue.quick_push (bb);
3722 bb->aux = bb;
3725 while (!queue.is_empty ())
3727 edge_iterator ei;
3728 edge e;
3729 bool change = false;
3730 int i;
3732 bb = queue.pop ();
3733 bb->aux = NULL;
3735 if (bitmap_bit_p (final_bbs, bb->index))
3736 continue;
3738 for (i = 0; i < func_param_count; i++)
3740 int idx = bb->index * func_param_count + i;
3741 bool first = true;
3742 HOST_WIDE_INT inh = 0;
3744 FOR_EACH_EDGE (e, ei, bb->succs)
3746 int succ_idx = e->dest->index * func_param_count + i;
3748 if (e->src == EXIT_BLOCK_PTR)
3749 continue;
3751 if (first)
3753 first = false;
3754 inh = bb_dereferences [succ_idx];
3756 else if (bb_dereferences [succ_idx] < inh)
3757 inh = bb_dereferences [succ_idx];
3760 if (!first && bb_dereferences[idx] < inh)
3762 bb_dereferences[idx] = inh;
3763 change = true;
3767 if (change && !bitmap_bit_p (final_bbs, bb->index))
3768 FOR_EACH_EDGE (e, ei, bb->preds)
3770 if (e->src->aux)
3771 continue;
3773 e->src->aux = e->src;
3774 queue.quick_push (e->src);
3778 queue.release ();
3781 /* Dump a dereferences TABLE with heading STR to file F. */
3783 static void
3784 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3786 basic_block bb;
3788 fprintf (dump_file, str);
3789 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3791 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3792 if (bb != EXIT_BLOCK_PTR)
3794 int i;
3795 for (i = 0; i < func_param_count; i++)
3797 int idx = bb->index * func_param_count + i;
3798 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3801 fprintf (f, "\n");
3803 fprintf (dump_file, "\n");
3806 /* Determine what (parts of) parameters passed by reference that are not
3807 assigned to are not certainly dereferenced in this function and thus the
3808 dereferencing cannot be safely moved to the caller without potentially
3809 introducing a segfault. Mark such REPRESENTATIVES as
3810 grp_not_necessarilly_dereferenced.
3812 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3813 part is calculated rather than simple booleans are calculated for each
3814 pointer parameter to handle cases when only a fraction of the whole
3815 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3816 an example).
3818 The maximum dereference distances for each pointer parameter and BB are
3819 already stored in bb_dereference. This routine simply propagates these
3820 values upwards by propagate_dereference_distances and then compares the
3821 distances of individual parameters in the ENTRY BB to the equivalent
3822 distances of each representative of a (fraction of a) parameter. */
3824 static void
3825 analyze_caller_dereference_legality (vec<access_p> representatives)
3827 int i;
3829 if (dump_file && (dump_flags & TDF_DETAILS))
3830 dump_dereferences_table (dump_file,
3831 "Dereference table before propagation:\n",
3832 bb_dereferences);
3834 propagate_dereference_distances ();
3836 if (dump_file && (dump_flags & TDF_DETAILS))
3837 dump_dereferences_table (dump_file,
3838 "Dereference table after propagation:\n",
3839 bb_dereferences);
3841 for (i = 0; i < func_param_count; i++)
3843 struct access *repr = representatives[i];
3844 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3846 if (!repr || no_accesses_p (repr))
3847 continue;
3851 if ((repr->offset + repr->size) > bb_dereferences[idx])
3852 repr->grp_not_necessarilly_dereferenced = 1;
3853 repr = repr->next_grp;
3855 while (repr);
3859 /* Return the representative access for the parameter declaration PARM if it is
3860 a scalar passed by reference which is not written to and the pointer value
3861 is not used directly. Thus, if it is legal to dereference it in the caller
3862 and we can rule out modifications through aliases, such parameter should be
3863 turned into one passed by value. Return NULL otherwise. */
3865 static struct access *
3866 unmodified_by_ref_scalar_representative (tree parm)
3868 int i, access_count;
3869 struct access *repr;
3870 vec<access_p> *access_vec;
3872 access_vec = get_base_access_vector (parm);
3873 gcc_assert (access_vec);
3874 repr = (*access_vec)[0];
3875 if (repr->write)
3876 return NULL;
3877 repr->group_representative = repr;
3879 access_count = access_vec->length ();
3880 for (i = 1; i < access_count; i++)
3882 struct access *access = (*access_vec)[i];
3883 if (access->write)
3884 return NULL;
3885 access->group_representative = repr;
3886 access->next_sibling = repr->next_sibling;
3887 repr->next_sibling = access;
3890 repr->grp_read = 1;
3891 repr->grp_scalar_ptr = 1;
3892 return repr;
3895 /* Return true iff this access precludes IPA-SRA of the parameter it is
3896 associated with. */
3898 static bool
3899 access_precludes_ipa_sra_p (struct access *access)
3901 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3902 is incompatible assign in a call statement (and possibly even in asm
3903 statements). This can be relaxed by using a new temporary but only for
3904 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3905 intraprocedural SRA we deal with this by keeping the old aggregate around,
3906 something we cannot do in IPA-SRA.) */
3907 if (access->write
3908 && (is_gimple_call (access->stmt)
3909 || gimple_code (access->stmt) == GIMPLE_ASM))
3910 return true;
3912 return false;
3916 /* Sort collected accesses for parameter PARM, identify representatives for
3917 each accessed region and link them together. Return NULL if there are
3918 different but overlapping accesses, return the special ptr value meaning
3919 there are no accesses for this parameter if that is the case and return the
3920 first representative otherwise. Set *RO_GRP if there is a group of accesses
3921 with only read (i.e. no write) accesses. */
3923 static struct access *
3924 splice_param_accesses (tree parm, bool *ro_grp)
3926 int i, j, access_count, group_count;
3927 int agg_size, total_size = 0;
3928 struct access *access, *res, **prev_acc_ptr = &res;
3929 vec<access_p> *access_vec;
3931 access_vec = get_base_access_vector (parm);
3932 if (!access_vec)
3933 return &no_accesses_representant;
3934 access_count = access_vec->length ();
3936 access_vec->qsort (compare_access_positions);
3938 i = 0;
3939 total_size = 0;
3940 group_count = 0;
3941 while (i < access_count)
3943 bool modification;
3944 tree a1_alias_type;
3945 access = (*access_vec)[i];
3946 modification = access->write;
3947 if (access_precludes_ipa_sra_p (access))
3948 return NULL;
3949 a1_alias_type = reference_alias_ptr_type (access->expr);
3951 /* Access is about to become group representative unless we find some
3952 nasty overlap which would preclude us from breaking this parameter
3953 apart. */
3955 j = i + 1;
3956 while (j < access_count)
3958 struct access *ac2 = (*access_vec)[j];
3959 if (ac2->offset != access->offset)
3961 /* All or nothing law for parameters. */
3962 if (access->offset + access->size > ac2->offset)
3963 return NULL;
3964 else
3965 break;
3967 else if (ac2->size != access->size)
3968 return NULL;
3970 if (access_precludes_ipa_sra_p (ac2)
3971 || (ac2->type != access->type
3972 && (TREE_ADDRESSABLE (ac2->type)
3973 || TREE_ADDRESSABLE (access->type)))
3974 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
3975 return NULL;
3977 modification |= ac2->write;
3978 ac2->group_representative = access;
3979 ac2->next_sibling = access->next_sibling;
3980 access->next_sibling = ac2;
3981 j++;
3984 group_count++;
3985 access->grp_maybe_modified = modification;
3986 if (!modification)
3987 *ro_grp = true;
3988 *prev_acc_ptr = access;
3989 prev_acc_ptr = &access->next_grp;
3990 total_size += access->size;
3991 i = j;
3994 if (POINTER_TYPE_P (TREE_TYPE (parm)))
3995 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
3996 else
3997 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
3998 if (total_size >= agg_size)
3999 return NULL;
4001 gcc_assert (group_count > 0);
4002 return res;
4005 /* Decide whether parameters with representative accesses given by REPR should
4006 be reduced into components. */
4008 static int
4009 decide_one_param_reduction (struct access *repr)
4011 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4012 bool by_ref;
4013 tree parm;
4015 parm = repr->base;
4016 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4017 gcc_assert (cur_parm_size > 0);
4019 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4021 by_ref = true;
4022 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4024 else
4026 by_ref = false;
4027 agg_size = cur_parm_size;
4030 if (dump_file)
4032 struct access *acc;
4033 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4034 print_generic_expr (dump_file, parm, 0);
4035 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4036 for (acc = repr; acc; acc = acc->next_grp)
4037 dump_access (dump_file, acc, true);
4040 total_size = 0;
4041 new_param_count = 0;
4043 for (; repr; repr = repr->next_grp)
4045 gcc_assert (parm == repr->base);
4047 /* Taking the address of a non-addressable field is verboten. */
4048 if (by_ref && repr->non_addressable)
4049 return 0;
4051 /* Do not decompose a non-BLKmode param in a way that would
4052 create BLKmode params. Especially for by-reference passing
4053 (thus, pointer-type param) this is hardly worthwhile. */
4054 if (DECL_MODE (parm) != BLKmode
4055 && TYPE_MODE (repr->type) == BLKmode)
4056 return 0;
4058 if (!by_ref || (!repr->grp_maybe_modified
4059 && !repr->grp_not_necessarilly_dereferenced))
4060 total_size += repr->size;
4061 else
4062 total_size += cur_parm_size;
4064 new_param_count++;
4067 gcc_assert (new_param_count > 0);
4069 if (optimize_function_for_size_p (cfun))
4070 parm_size_limit = cur_parm_size;
4071 else
4072 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4073 * cur_parm_size);
4075 if (total_size < agg_size
4076 && total_size <= parm_size_limit)
4078 if (dump_file)
4079 fprintf (dump_file, " ....will be split into %i components\n",
4080 new_param_count);
4081 return new_param_count;
4083 else
4084 return 0;
4087 /* The order of the following enums is important, we need to do extra work for
4088 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4089 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4090 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4092 /* Identify representatives of all accesses to all candidate parameters for
4093 IPA-SRA. Return result based on what representatives have been found. */
4095 static enum ipa_splicing_result
4096 splice_all_param_accesses (vec<access_p> &representatives)
4098 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4099 tree parm;
4100 struct access *repr;
4102 representatives.create (func_param_count);
4104 for (parm = DECL_ARGUMENTS (current_function_decl);
4105 parm;
4106 parm = DECL_CHAIN (parm))
4108 if (is_unused_scalar_param (parm))
4110 representatives.quick_push (&no_accesses_representant);
4111 if (result == NO_GOOD_ACCESS)
4112 result = UNUSED_PARAMS;
4114 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4115 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4116 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4118 repr = unmodified_by_ref_scalar_representative (parm);
4119 representatives.quick_push (repr);
4120 if (repr)
4121 result = UNMODIF_BY_REF_ACCESSES;
4123 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4125 bool ro_grp = false;
4126 repr = splice_param_accesses (parm, &ro_grp);
4127 representatives.quick_push (repr);
4129 if (repr && !no_accesses_p (repr))
4131 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4133 if (ro_grp)
4134 result = UNMODIF_BY_REF_ACCESSES;
4135 else if (result < MODIF_BY_REF_ACCESSES)
4136 result = MODIF_BY_REF_ACCESSES;
4138 else if (result < BY_VAL_ACCESSES)
4139 result = BY_VAL_ACCESSES;
4141 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4142 result = UNUSED_PARAMS;
4144 else
4145 representatives.quick_push (NULL);
4148 if (result == NO_GOOD_ACCESS)
4150 representatives.release ();
4151 return NO_GOOD_ACCESS;
4154 return result;
4157 /* Return the index of BASE in PARMS. Abort if it is not found. */
4159 static inline int
4160 get_param_index (tree base, vec<tree> parms)
4162 int i, len;
4164 len = parms.length ();
4165 for (i = 0; i < len; i++)
4166 if (parms[i] == base)
4167 return i;
4168 gcc_unreachable ();
4171 /* Convert the decisions made at the representative level into compact
4172 parameter adjustments. REPRESENTATIVES are pointers to first
4173 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4174 final number of adjustments. */
4176 static ipa_parm_adjustment_vec
4177 turn_representatives_into_adjustments (vec<access_p> representatives,
4178 int adjustments_count)
4180 vec<tree> parms;
4181 ipa_parm_adjustment_vec adjustments;
4182 tree parm;
4183 int i;
4185 gcc_assert (adjustments_count > 0);
4186 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4187 adjustments.create (adjustments_count);
4188 parm = DECL_ARGUMENTS (current_function_decl);
4189 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4191 struct access *repr = representatives[i];
4193 if (!repr || no_accesses_p (repr))
4195 struct ipa_parm_adjustment adj;
4197 memset (&adj, 0, sizeof (adj));
4198 adj.base_index = get_param_index (parm, parms);
4199 adj.base = parm;
4200 if (!repr)
4201 adj.copy_param = 1;
4202 else
4203 adj.remove_param = 1;
4204 adjustments.quick_push (adj);
4206 else
4208 struct ipa_parm_adjustment adj;
4209 int index = get_param_index (parm, parms);
4211 for (; repr; repr = repr->next_grp)
4213 memset (&adj, 0, sizeof (adj));
4214 gcc_assert (repr->base == parm);
4215 adj.base_index = index;
4216 adj.base = repr->base;
4217 adj.type = repr->type;
4218 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4219 adj.offset = repr->offset;
4220 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4221 && (repr->grp_maybe_modified
4222 || repr->grp_not_necessarilly_dereferenced));
4223 adjustments.quick_push (adj);
4227 parms.release ();
4228 return adjustments;
4231 /* Analyze the collected accesses and produce a plan what to do with the
4232 parameters in the form of adjustments, NULL meaning nothing. */
4234 static ipa_parm_adjustment_vec
4235 analyze_all_param_acesses (void)
4237 enum ipa_splicing_result repr_state;
4238 bool proceed = false;
4239 int i, adjustments_count = 0;
4240 vec<access_p> representatives;
4241 ipa_parm_adjustment_vec adjustments;
4243 repr_state = splice_all_param_accesses (representatives);
4244 if (repr_state == NO_GOOD_ACCESS)
4245 return ipa_parm_adjustment_vec();
4247 /* If there are any parameters passed by reference which are not modified
4248 directly, we need to check whether they can be modified indirectly. */
4249 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4251 analyze_caller_dereference_legality (representatives);
4252 analyze_modified_params (representatives);
4255 for (i = 0; i < func_param_count; i++)
4257 struct access *repr = representatives[i];
4259 if (repr && !no_accesses_p (repr))
4261 if (repr->grp_scalar_ptr)
4263 adjustments_count++;
4264 if (repr->grp_not_necessarilly_dereferenced
4265 || repr->grp_maybe_modified)
4266 representatives[i] = NULL;
4267 else
4269 proceed = true;
4270 sra_stats.scalar_by_ref_to_by_val++;
4273 else
4275 int new_components = decide_one_param_reduction (repr);
4277 if (new_components == 0)
4279 representatives[i] = NULL;
4280 adjustments_count++;
4282 else
4284 adjustments_count += new_components;
4285 sra_stats.aggregate_params_reduced++;
4286 sra_stats.param_reductions_created += new_components;
4287 proceed = true;
4291 else
4293 if (no_accesses_p (repr))
4295 proceed = true;
4296 sra_stats.deleted_unused_parameters++;
4298 adjustments_count++;
4302 if (!proceed && dump_file)
4303 fprintf (dump_file, "NOT proceeding to change params.\n");
4305 if (proceed)
4306 adjustments = turn_representatives_into_adjustments (representatives,
4307 adjustments_count);
4308 else
4309 adjustments = ipa_parm_adjustment_vec();
4311 representatives.release ();
4312 return adjustments;
4315 /* If a parameter replacement identified by ADJ does not yet exist in the form
4316 of declaration, create it and record it, otherwise return the previously
4317 created one. */
4319 static tree
4320 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4322 tree repl;
4323 if (!adj->new_ssa_base)
4325 char *pretty_name = make_fancy_name (adj->base);
4327 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4328 DECL_NAME (repl) = get_identifier (pretty_name);
4329 obstack_free (&name_obstack, pretty_name);
4331 adj->new_ssa_base = repl;
4333 else
4334 repl = adj->new_ssa_base;
4335 return repl;
4338 /* Find the first adjustment for a particular parameter BASE in a vector of
4339 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4340 adjustment. */
4342 static struct ipa_parm_adjustment *
4343 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4345 int i, len;
4347 len = adjustments.length ();
4348 for (i = 0; i < len; i++)
4350 struct ipa_parm_adjustment *adj;
4352 adj = &adjustments[i];
4353 if (!adj->copy_param && adj->base == base)
4354 return adj;
4357 return NULL;
4360 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4361 removed because its value is not used, replace the SSA_NAME with a one
4362 relating to a created VAR_DECL together all of its uses and return true.
4363 ADJUSTMENTS is a pointer to an adjustments vector. */
4365 static bool
4366 replace_removed_params_ssa_names (gimple stmt,
4367 ipa_parm_adjustment_vec adjustments)
4369 struct ipa_parm_adjustment *adj;
4370 tree lhs, decl, repl, name;
4372 if (gimple_code (stmt) == GIMPLE_PHI)
4373 lhs = gimple_phi_result (stmt);
4374 else if (is_gimple_assign (stmt))
4375 lhs = gimple_assign_lhs (stmt);
4376 else if (is_gimple_call (stmt))
4377 lhs = gimple_call_lhs (stmt);
4378 else
4379 gcc_unreachable ();
4381 if (TREE_CODE (lhs) != SSA_NAME)
4382 return false;
4384 decl = SSA_NAME_VAR (lhs);
4385 if (decl == NULL_TREE
4386 || TREE_CODE (decl) != PARM_DECL)
4387 return false;
4389 adj = get_adjustment_for_base (adjustments, decl);
4390 if (!adj)
4391 return false;
4393 repl = get_replaced_param_substitute (adj);
4394 name = make_ssa_name (repl, stmt);
4396 if (dump_file)
4398 fprintf (dump_file, "replacing an SSA name of a removed param ");
4399 print_generic_expr (dump_file, lhs, 0);
4400 fprintf (dump_file, " with ");
4401 print_generic_expr (dump_file, name, 0);
4402 fprintf (dump_file, "\n");
4405 if (is_gimple_assign (stmt))
4406 gimple_assign_set_lhs (stmt, name);
4407 else if (is_gimple_call (stmt))
4408 gimple_call_set_lhs (stmt, name);
4409 else
4410 gimple_phi_set_result (stmt, name);
4412 replace_uses_by (lhs, name);
4413 release_ssa_name (lhs);
4414 return true;
4417 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4418 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4419 specifies whether the function should care about type incompatibility the
4420 current and new expressions. If it is false, the function will leave
4421 incompatibility issues to the caller. Return true iff the expression
4422 was modified. */
4424 static bool
4425 sra_ipa_modify_expr (tree *expr, bool convert,
4426 ipa_parm_adjustment_vec adjustments)
4428 int i, len;
4429 struct ipa_parm_adjustment *adj, *cand = NULL;
4430 HOST_WIDE_INT offset, size, max_size;
4431 tree base, src;
4433 len = adjustments.length ();
4435 if (TREE_CODE (*expr) == BIT_FIELD_REF
4436 || TREE_CODE (*expr) == IMAGPART_EXPR
4437 || TREE_CODE (*expr) == REALPART_EXPR)
4439 expr = &TREE_OPERAND (*expr, 0);
4440 convert = true;
4443 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4444 if (!base || size == -1 || max_size == -1)
4445 return false;
4447 if (TREE_CODE (base) == MEM_REF)
4449 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4450 base = TREE_OPERAND (base, 0);
4453 base = get_ssa_base_param (base);
4454 if (!base || TREE_CODE (base) != PARM_DECL)
4455 return false;
4457 for (i = 0; i < len; i++)
4459 adj = &adjustments[i];
4461 if (adj->base == base &&
4462 (adj->offset == offset || adj->remove_param))
4464 cand = adj;
4465 break;
4468 if (!cand || cand->copy_param || cand->remove_param)
4469 return false;
4471 if (cand->by_ref)
4472 src = build_simple_mem_ref (cand->reduction);
4473 else
4474 src = cand->reduction;
4476 if (dump_file && (dump_flags & TDF_DETAILS))
4478 fprintf (dump_file, "About to replace expr ");
4479 print_generic_expr (dump_file, *expr, 0);
4480 fprintf (dump_file, " with ");
4481 print_generic_expr (dump_file, src, 0);
4482 fprintf (dump_file, "\n");
4485 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4487 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4488 *expr = vce;
4490 else
4491 *expr = src;
4492 return true;
4495 /* If the statement pointed to by STMT_PTR contains any expressions that need
4496 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4497 potential type incompatibilities (GSI is used to accommodate conversion
4498 statements and must point to the statement). Return true iff the statement
4499 was modified. */
4501 static bool
4502 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4503 ipa_parm_adjustment_vec adjustments)
4505 gimple stmt = *stmt_ptr;
4506 tree *lhs_p, *rhs_p;
4507 bool any;
4509 if (!gimple_assign_single_p (stmt))
4510 return false;
4512 rhs_p = gimple_assign_rhs1_ptr (stmt);
4513 lhs_p = gimple_assign_lhs_ptr (stmt);
4515 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4516 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4517 if (any)
4519 tree new_rhs = NULL_TREE;
4521 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4523 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4525 /* V_C_Es of constructors can cause trouble (PR 42714). */
4526 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4527 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4528 else
4529 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4530 NULL);
4532 else
4533 new_rhs = fold_build1_loc (gimple_location (stmt),
4534 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4535 *rhs_p);
4537 else if (REFERENCE_CLASS_P (*rhs_p)
4538 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4539 && !is_gimple_reg (*lhs_p))
4540 /* This can happen when an assignment in between two single field
4541 structures is turned into an assignment in between two pointers to
4542 scalars (PR 42237). */
4543 new_rhs = *rhs_p;
4545 if (new_rhs)
4547 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4548 true, GSI_SAME_STMT);
4550 gimple_assign_set_rhs_from_tree (gsi, tmp);
4553 return true;
4556 return false;
4559 /* Traverse the function body and all modifications as described in
4560 ADJUSTMENTS. Return true iff the CFG has been changed. */
4562 static bool
4563 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4565 bool cfg_changed = false;
4566 basic_block bb;
4568 FOR_EACH_BB (bb)
4570 gimple_stmt_iterator gsi;
4572 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4573 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4575 gsi = gsi_start_bb (bb);
4576 while (!gsi_end_p (gsi))
4578 gimple stmt = gsi_stmt (gsi);
4579 bool modified = false;
4580 tree *t;
4581 unsigned i;
4583 switch (gimple_code (stmt))
4585 case GIMPLE_RETURN:
4586 t = gimple_return_retval_ptr (stmt);
4587 if (*t != NULL_TREE)
4588 modified |= sra_ipa_modify_expr (t, true, adjustments);
4589 break;
4591 case GIMPLE_ASSIGN:
4592 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4593 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4594 break;
4596 case GIMPLE_CALL:
4597 /* Operands must be processed before the lhs. */
4598 for (i = 0; i < gimple_call_num_args (stmt); i++)
4600 t = gimple_call_arg_ptr (stmt, i);
4601 modified |= sra_ipa_modify_expr (t, true, adjustments);
4604 if (gimple_call_lhs (stmt))
4606 t = gimple_call_lhs_ptr (stmt);
4607 modified |= sra_ipa_modify_expr (t, false, adjustments);
4608 modified |= replace_removed_params_ssa_names (stmt,
4609 adjustments);
4611 break;
4613 case GIMPLE_ASM:
4614 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4616 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4617 modified |= sra_ipa_modify_expr (t, true, adjustments);
4619 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4621 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4622 modified |= sra_ipa_modify_expr (t, false, adjustments);
4624 break;
4626 default:
4627 break;
4630 if (modified)
4632 update_stmt (stmt);
4633 if (maybe_clean_eh_stmt (stmt)
4634 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4635 cfg_changed = true;
4637 gsi_next (&gsi);
4641 return cfg_changed;
4644 /* Call gimple_debug_bind_reset_value on all debug statements describing
4645 gimple register parameters that are being removed or replaced. */
4647 static void
4648 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4650 int i, len;
4651 gimple_stmt_iterator *gsip = NULL, gsi;
4653 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4655 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4656 gsip = &gsi;
4658 len = adjustments.length ();
4659 for (i = 0; i < len; i++)
4661 struct ipa_parm_adjustment *adj;
4662 imm_use_iterator ui;
4663 gimple stmt, def_temp;
4664 tree name, vexpr, copy = NULL_TREE;
4665 use_operand_p use_p;
4667 adj = &adjustments[i];
4668 if (adj->copy_param || !is_gimple_reg (adj->base))
4669 continue;
4670 name = ssa_default_def (cfun, adj->base);
4671 vexpr = NULL;
4672 if (name)
4673 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4675 /* All other users must have been removed by
4676 ipa_sra_modify_function_body. */
4677 gcc_assert (is_gimple_debug (stmt));
4678 if (vexpr == NULL && gsip != NULL)
4680 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4681 vexpr = make_node (DEBUG_EXPR_DECL);
4682 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4683 NULL);
4684 DECL_ARTIFICIAL (vexpr) = 1;
4685 TREE_TYPE (vexpr) = TREE_TYPE (name);
4686 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4687 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4689 if (vexpr)
4691 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4692 SET_USE (use_p, vexpr);
4694 else
4695 gimple_debug_bind_reset_value (stmt);
4696 update_stmt (stmt);
4698 /* Create a VAR_DECL for debug info purposes. */
4699 if (!DECL_IGNORED_P (adj->base))
4701 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4702 VAR_DECL, DECL_NAME (adj->base),
4703 TREE_TYPE (adj->base));
4704 if (DECL_PT_UID_SET_P (adj->base))
4705 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4706 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4707 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4708 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4709 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4710 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4711 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4712 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4713 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4714 SET_DECL_RTL (copy, 0);
4715 TREE_USED (copy) = 1;
4716 DECL_CONTEXT (copy) = current_function_decl;
4717 add_local_decl (cfun, copy);
4718 DECL_CHAIN (copy) =
4719 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4720 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4722 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4724 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4725 if (vexpr)
4726 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4727 else
4728 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4729 NULL);
4730 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4735 /* Return false iff all callers have at least as many actual arguments as there
4736 are formal parameters in the current function. */
4738 static bool
4739 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4740 void *data ATTRIBUTE_UNUSED)
4742 struct cgraph_edge *cs;
4743 for (cs = node->callers; cs; cs = cs->next_caller)
4744 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4745 return true;
4747 return false;
4750 /* Convert all callers of NODE. */
4752 static bool
4753 convert_callers_for_node (struct cgraph_node *node,
4754 void *data)
4756 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4757 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4758 struct cgraph_edge *cs;
4760 for (cs = node->callers; cs; cs = cs->next_caller)
4762 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4764 if (dump_file)
4765 fprintf (dump_file, "Adjusting call (%i -> %i) %s -> %s\n",
4766 cs->caller->uid, cs->callee->uid,
4767 xstrdup (cgraph_node_name (cs->caller)),
4768 xstrdup (cgraph_node_name (cs->callee)));
4770 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4772 pop_cfun ();
4775 for (cs = node->callers; cs; cs = cs->next_caller)
4776 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4777 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4778 compute_inline_parameters (cs->caller, true);
4779 BITMAP_FREE (recomputed_callers);
4781 return true;
4784 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4786 static void
4787 convert_callers (struct cgraph_node *node, tree old_decl,
4788 ipa_parm_adjustment_vec adjustments)
4790 basic_block this_block;
4792 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4793 &adjustments, false);
4795 if (!encountered_recursive_call)
4796 return;
4798 FOR_EACH_BB (this_block)
4800 gimple_stmt_iterator gsi;
4802 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4804 gimple stmt = gsi_stmt (gsi);
4805 tree call_fndecl;
4806 if (gimple_code (stmt) != GIMPLE_CALL)
4807 continue;
4808 call_fndecl = gimple_call_fndecl (stmt);
4809 if (call_fndecl == old_decl)
4811 if (dump_file)
4812 fprintf (dump_file, "Adjusting recursive call");
4813 gimple_call_set_fndecl (stmt, node->symbol.decl);
4814 ipa_modify_call_arguments (NULL, stmt, adjustments);
4819 return;
4822 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4823 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4825 static bool
4826 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4828 struct cgraph_node *new_node;
4829 bool cfg_changed;
4830 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4832 rebuild_cgraph_edges ();
4833 free_dominance_info (CDI_DOMINATORS);
4834 pop_cfun ();
4836 new_node = cgraph_function_versioning (node, redirect_callers,
4837 NULL,
4838 NULL, false, NULL, NULL, "isra");
4839 redirect_callers.release ();
4841 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4842 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4843 cfg_changed = ipa_sra_modify_function_body (adjustments);
4844 sra_ipa_reset_debug_stmts (adjustments);
4845 convert_callers (new_node, node->symbol.decl, adjustments);
4846 cgraph_make_node_local (new_node);
4847 return cfg_changed;
4850 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4851 attributes, return true otherwise. NODE is the cgraph node of the current
4852 function. */
4854 static bool
4855 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4857 if (!cgraph_node_can_be_local_p (node))
4859 if (dump_file)
4860 fprintf (dump_file, "Function not local to this compilation unit.\n");
4861 return false;
4864 if (!node->local.can_change_signature)
4866 if (dump_file)
4867 fprintf (dump_file, "Function can not change signature.\n");
4868 return false;
4871 if (!tree_versionable_function_p (node->symbol.decl))
4873 if (dump_file)
4874 fprintf (dump_file, "Function is not versionable.\n");
4875 return false;
4878 if (DECL_VIRTUAL_P (current_function_decl))
4880 if (dump_file)
4881 fprintf (dump_file, "Function is a virtual method.\n");
4882 return false;
4885 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4886 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4888 if (dump_file)
4889 fprintf (dump_file, "Function too big to be made truly local.\n");
4890 return false;
4893 if (!node->callers)
4895 if (dump_file)
4896 fprintf (dump_file,
4897 "Function has no callers in this compilation unit.\n");
4898 return false;
4901 if (cfun->stdarg)
4903 if (dump_file)
4904 fprintf (dump_file, "Function uses stdarg. \n");
4905 return false;
4908 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4909 return false;
4911 return true;
4914 /* Perform early interprocedural SRA. */
4916 static unsigned int
4917 ipa_early_sra (void)
4919 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4920 ipa_parm_adjustment_vec adjustments;
4921 int ret = 0;
4923 if (!ipa_sra_preliminary_function_checks (node))
4924 return 0;
4926 sra_initialize ();
4927 sra_mode = SRA_MODE_EARLY_IPA;
4929 if (!find_param_candidates ())
4931 if (dump_file)
4932 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4933 goto simple_out;
4936 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4937 NULL, true))
4939 if (dump_file)
4940 fprintf (dump_file, "There are callers with insufficient number of "
4941 "arguments.\n");
4942 goto simple_out;
4945 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4946 func_param_count
4947 * last_basic_block_for_function (cfun));
4948 final_bbs = BITMAP_ALLOC (NULL);
4950 scan_function ();
4951 if (encountered_apply_args)
4953 if (dump_file)
4954 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
4955 goto out;
4958 if (encountered_unchangable_recursive_call)
4960 if (dump_file)
4961 fprintf (dump_file, "Function calls itself with insufficient "
4962 "number of arguments.\n");
4963 goto out;
4966 adjustments = analyze_all_param_acesses ();
4967 if (!adjustments.exists ())
4968 goto out;
4969 if (dump_file)
4970 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
4972 if (modify_function (node, adjustments))
4973 ret = TODO_update_ssa | TODO_cleanup_cfg;
4974 else
4975 ret = TODO_update_ssa;
4976 adjustments.release ();
4978 statistics_counter_event (cfun, "Unused parameters deleted",
4979 sra_stats.deleted_unused_parameters);
4980 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
4981 sra_stats.scalar_by_ref_to_by_val);
4982 statistics_counter_event (cfun, "Aggregate parameters broken up",
4983 sra_stats.aggregate_params_reduced);
4984 statistics_counter_event (cfun, "Aggregate parameter components created",
4985 sra_stats.param_reductions_created);
4987 out:
4988 BITMAP_FREE (final_bbs);
4989 free (bb_dereferences);
4990 simple_out:
4991 sra_deinitialize ();
4992 return ret;
4995 /* Return if early ipa sra shall be performed. */
4996 static bool
4997 ipa_early_sra_gate (void)
4999 return flag_ipa_sra && dbg_cnt (eipa_sra);
5002 struct gimple_opt_pass pass_early_ipa_sra =
5005 GIMPLE_PASS,
5006 "eipa_sra", /* name */
5007 OPTGROUP_NONE, /* optinfo_flags */
5008 ipa_early_sra_gate, /* gate */
5009 ipa_early_sra, /* execute */
5010 NULL, /* sub */
5011 NULL, /* next */
5012 0, /* static_pass_number */
5013 TV_IPA_SRA, /* tv_id */
5014 0, /* properties_required */
5015 0, /* properties_provided */
5016 0, /* properties_destroyed */
5017 0, /* todo_flags_start */
5018 TODO_dump_symtab /* todo_flags_finish */