OSDN Git Service

2009-04-08 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / tree-sra.c
1 /* Scalar Replacement of Aggregates (SRA) converts some structure
2    references into scalar references, exposing them to the scalar
3    optimizers.
4    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009
5    Free Software Foundation, Inc.
6    Contributed by Diego Novillo <dnovillo@redhat.com>
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by the
12 Free Software Foundation; either version 3, or (at your option) any
13 later version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT
16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "ggc.h"
29 #include "tree.h"
30
31 /* These RTL headers are needed for basic-block.h.  */
32 #include "rtl.h"
33 #include "tm_p.h"
34 #include "hard-reg-set.h"
35 #include "basic-block.h"
36 #include "diagnostic.h"
37 #include "langhooks.h"
38 #include "tree-inline.h"
39 #include "tree-flow.h"
40 #include "gimple.h"
41 #include "tree-dump.h"
42 #include "tree-pass.h"
43 #include "timevar.h"
44 #include "flags.h"
45 #include "bitmap.h"
46 #include "obstack.h"
47 #include "target.h"
48 /* expr.h is needed for MOVE_RATIO.  */
49 #include "expr.h"
50 #include "params.h"
51
52
53 /* This object of this pass is to replace a non-addressable aggregate with a
54    set of independent variables.  Most of the time, all of these variables
55    will be scalars.  But a secondary objective is to break up larger
56    aggregates into smaller aggregates.  In the process we may find that some
57    bits of the larger aggregate can be deleted as unreferenced.
58
59    This substitution is done globally.  More localized substitutions would
60    be the purvey of a load-store motion pass.
61
62    The optimization proceeds in phases:
63
64      (1) Identify variables that have types that are candidates for
65          decomposition.
66
67      (2) Scan the function looking for the ways these variables are used.
68          In particular we're interested in the number of times a variable
69          (or member) is needed as a complete unit, and the number of times
70          a variable (or member) is copied.
71
72      (3) Based on the usage profile, instantiate substitution variables.
73
74      (4) Scan the function making replacements.
75 */
76
77
78 /* True if this is the "early" pass, before inlining.  */
79 static bool early_sra;
80
81 /* The set of aggregate variables that are candidates for scalarization.  */
82 static bitmap sra_candidates;
83
84 /* Set of scalarizable PARM_DECLs that need copy-in operations at the
85    beginning of the function.  */
86 static bitmap needs_copy_in;
87
88 /* Sets of bit pairs that cache type decomposition and instantiation.  */
89 static bitmap sra_type_decomp_cache;
90 static bitmap sra_type_inst_cache;
91
92 /* One of these structures is created for each candidate aggregate and
93    each (accessed) member or group of members of such an aggregate.  */
94 struct sra_elt
95 {
96   /* A tree of the elements.  Used when we want to traverse everything.  */
97   struct sra_elt *parent;
98   struct sra_elt *groups;
99   struct sra_elt *children;
100   struct sra_elt *sibling;
101
102   /* If this element is a root, then this is the VAR_DECL.  If this is
103      a sub-element, this is some token used to identify the reference.
104      In the case of COMPONENT_REF, this is the FIELD_DECL.  In the case
105      of an ARRAY_REF, this is the (constant) index.  In the case of an
106      ARRAY_RANGE_REF, this is the (constant) RANGE_EXPR.  In the case
107      of a complex number, this is a zero or one.  */
108   tree element;
109
110   /* The type of the element.  */
111   tree type;
112
113   /* A VAR_DECL, for any sub-element we've decided to replace.  */
114   tree replacement;
115
116   /* The number of times the element is referenced as a whole.  I.e.
117      given "a.b.c", this would be incremented for C, but not for A or B.  */
118   unsigned int n_uses;
119
120   /* The number of times the element is copied to or from another
121      scalarizable element.  */
122   unsigned int n_copies;
123
124   /* True if TYPE is scalar.  */
125   bool is_scalar;
126
127   /* True if this element is a group of members of its parent.  */
128   bool is_group;
129
130   /* True if we saw something about this element that prevents scalarization,
131      such as non-constant indexing.  */
132   bool cannot_scalarize;
133
134   /* True if we've decided that structure-to-structure assignment
135      should happen via memcpy and not per-element.  */
136   bool use_block_copy;
137
138   /* True if everything under this element has been marked TREE_NO_WARNING.  */
139   bool all_no_warning;
140
141   /* A flag for use with/after random access traversals.  */
142   bool visited;
143
144   /* True if there is BIT_FIELD_REF on the lhs with a vector. */
145   bool is_vector_lhs;
146
147   /* 1 if the element is a field that is part of a block, 2 if the field
148      is the block itself, 0 if it's neither.  */
149   char in_bitfld_block;
150 };
151
152 #define IS_ELEMENT_FOR_GROUP(ELEMENT) (TREE_CODE (ELEMENT) == RANGE_EXPR)
153
154 #define FOR_EACH_ACTUAL_CHILD(CHILD, ELT)                       \
155   for ((CHILD) = (ELT)->is_group                                \
156                  ? next_child_for_group (NULL, (ELT))           \
157                  : (ELT)->children;                             \
158        (CHILD);                                                 \
159        (CHILD) = (ELT)->is_group                                \
160                  ? next_child_for_group ((CHILD), (ELT))        \
161                  : (CHILD)->sibling)
162
163 /* Helper function for above macro.  Return next child in group.  */
164 static struct sra_elt *
165 next_child_for_group (struct sra_elt *child, struct sra_elt *group)
166 {
167   gcc_assert (group->is_group);
168
169   /* Find the next child in the parent.  */
170   if (child)
171     child = child->sibling;
172   else
173     child = group->parent->children;
174
175   /* Skip siblings that do not belong to the group.  */
176   while (child)
177     {
178       tree g_elt = group->element;
179       if (TREE_CODE (g_elt) == RANGE_EXPR)
180         {
181           if (!tree_int_cst_lt (child->element, TREE_OPERAND (g_elt, 0))
182               && !tree_int_cst_lt (TREE_OPERAND (g_elt, 1), child->element))
183             break;
184         }
185       else
186         gcc_unreachable ();
187
188       child = child->sibling;
189     }
190
191   return child;
192 }
193
194 /* Random access to the child of a parent is performed by hashing.
195    This prevents quadratic behavior, and allows SRA to function
196    reasonably on larger records.  */
197 static htab_t sra_map;
198
199 /* All structures are allocated out of the following obstack.  */
200 static struct obstack sra_obstack;
201
202 /* Debugging functions.  */
203 static void dump_sra_elt_name (FILE *, struct sra_elt *);
204 extern void debug_sra_elt_name (struct sra_elt *);
205
206 /* Forward declarations.  */
207 static tree generate_element_ref (struct sra_elt *);
208 static gimple_seq sra_build_assignment (tree dst, tree src);
209 static void mark_all_v_defs_seq (gimple_seq);
210
211 \f
212 /* Return true if DECL is an SRA candidate.  */
213
214 static bool
215 is_sra_candidate_decl (tree decl)
216 {
217   return DECL_P (decl) && bitmap_bit_p (sra_candidates, DECL_UID (decl));
218 }
219
220 /* Return true if TYPE is a scalar type.  */
221
222 static bool
223 is_sra_scalar_type (tree type)
224 {
225   enum tree_code code = TREE_CODE (type);
226   return (code == INTEGER_TYPE || code == REAL_TYPE || code == VECTOR_TYPE
227           || code == FIXED_POINT_TYPE
228           || code == ENUMERAL_TYPE || code == BOOLEAN_TYPE
229           || code == POINTER_TYPE || code == OFFSET_TYPE
230           || code == REFERENCE_TYPE);
231 }
232
233 /* Return true if TYPE can be decomposed into a set of independent variables.
234
235    Note that this doesn't imply that all elements of TYPE can be
236    instantiated, just that if we decide to break up the type into
237    separate pieces that it can be done.  */
238
239 bool
240 sra_type_can_be_decomposed_p (tree type)
241 {
242   unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
243   tree t;
244
245   /* Avoid searching the same type twice.  */
246   if (bitmap_bit_p (sra_type_decomp_cache, cache+0))
247     return true;
248   if (bitmap_bit_p (sra_type_decomp_cache, cache+1))
249     return false;
250
251   /* The type must have a definite nonzero size.  */
252   if (TYPE_SIZE (type) == NULL || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
253       || integer_zerop (TYPE_SIZE (type)))
254     goto fail;
255
256   /* The type must be a non-union aggregate.  */
257   switch (TREE_CODE (type))
258     {
259     case RECORD_TYPE:
260       {
261         bool saw_one_field = false;
262
263         for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
264           if (TREE_CODE (t) == FIELD_DECL)
265             {
266               /* Reject incorrectly represented bit fields.  */
267               if (DECL_BIT_FIELD (t)
268                   && INTEGRAL_TYPE_P (TREE_TYPE (t))
269                   && (tree_low_cst (DECL_SIZE (t), 1)
270                       != TYPE_PRECISION (TREE_TYPE (t))))
271                 goto fail;
272
273               saw_one_field = true;
274             }
275
276         /* Record types must have at least one field.  */
277         if (!saw_one_field)
278           goto fail;
279       }
280       break;
281
282     case ARRAY_TYPE:
283       /* Array types must have a fixed lower and upper bound.  */
284       t = TYPE_DOMAIN (type);
285       if (t == NULL)
286         goto fail;
287       if (TYPE_MIN_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MIN_VALUE (t)))
288         goto fail;
289       if (TYPE_MAX_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MAX_VALUE (t)))
290         goto fail;
291       break;
292
293     case COMPLEX_TYPE:
294       break;
295
296     default:
297       goto fail;
298     }
299
300   bitmap_set_bit (sra_type_decomp_cache, cache+0);
301   return true;
302
303  fail:
304   bitmap_set_bit (sra_type_decomp_cache, cache+1);
305   return false;
306 }
307
308 /* Returns true if the TYPE is one of the available va_list types.
309    Otherwise it returns false.
310    Note, that for multiple calling conventions there can be more
311    than just one va_list type present.  */
312
313 static bool
314 is_va_list_type (tree type)
315 {
316   tree h;
317
318   if (type == NULL_TREE)
319     return false;
320   h = targetm.canonical_va_list_type (type);
321   if (h == NULL_TREE)
322     return false;
323   if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (h))
324          return true;
325   return false;
326 }
327
328 /* Return true if DECL can be decomposed into a set of independent
329    (though not necessarily scalar) variables.  */
330
331 static bool
332 decl_can_be_decomposed_p (tree var)
333 {
334   /* Early out for scalars.  */
335   if (is_sra_scalar_type (TREE_TYPE (var)))
336     return false;
337
338   /* The variable must not be aliased.  */
339   if (!is_gimple_non_addressable (var))
340     {
341       if (dump_file && (dump_flags & TDF_DETAILS))
342         {
343           fprintf (dump_file, "Cannot scalarize variable ");
344           print_generic_expr (dump_file, var, dump_flags);
345           fprintf (dump_file, " because it must live in memory\n");
346         }
347       return false;
348     }
349
350   /* The variable must not be volatile.  */
351   if (TREE_THIS_VOLATILE (var))
352     {
353       if (dump_file && (dump_flags & TDF_DETAILS))
354         {
355           fprintf (dump_file, "Cannot scalarize variable ");
356           print_generic_expr (dump_file, var, dump_flags);
357           fprintf (dump_file, " because it is declared volatile\n");
358         }
359       return false;
360     }
361
362   /* We must be able to decompose the variable's type.  */
363   if (!sra_type_can_be_decomposed_p (TREE_TYPE (var)))
364     {
365       if (dump_file && (dump_flags & TDF_DETAILS))
366         {
367           fprintf (dump_file, "Cannot scalarize variable ");
368           print_generic_expr (dump_file, var, dump_flags);
369           fprintf (dump_file, " because its type cannot be decomposed\n");
370         }
371       return false;
372     }
373
374   /* HACK: if we decompose a va_list_type_node before inlining, then we'll
375      confuse tree-stdarg.c, and we won't be able to figure out which and
376      how many arguments are accessed.  This really should be improved in
377      tree-stdarg.c, as the decomposition is truly a win.  This could also
378      be fixed if the stdarg pass ran early, but this can't be done until
379      we've aliasing information early too.  See PR 30791.  */
380   if (early_sra && is_va_list_type (TREE_TYPE (var)))
381     return false;
382
383   return true;
384 }
385
386 /* Return true if TYPE can be *completely* decomposed into scalars.  */
387
388 static bool
389 type_can_instantiate_all_elements (tree type)
390 {
391   if (is_sra_scalar_type (type))
392     return true;
393   if (!sra_type_can_be_decomposed_p (type))
394     return false;
395
396   switch (TREE_CODE (type))
397     {
398     case RECORD_TYPE:
399       {
400         unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
401         tree f;
402
403         if (bitmap_bit_p (sra_type_inst_cache, cache+0))
404           return true;
405         if (bitmap_bit_p (sra_type_inst_cache, cache+1))
406           return false;
407
408         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
409           if (TREE_CODE (f) == FIELD_DECL)
410             {
411               if (!type_can_instantiate_all_elements (TREE_TYPE (f)))
412                 {
413                   bitmap_set_bit (sra_type_inst_cache, cache+1);
414                   return false;
415                 }
416             }
417
418         bitmap_set_bit (sra_type_inst_cache, cache+0);
419         return true;
420       }
421
422     case ARRAY_TYPE:
423       return type_can_instantiate_all_elements (TREE_TYPE (type));
424
425     case COMPLEX_TYPE:
426       return true;
427
428     default:
429       gcc_unreachable ();
430     }
431 }
432
433 /* Test whether ELT or some sub-element cannot be scalarized.  */
434
435 static bool
436 can_completely_scalarize_p (struct sra_elt *elt)
437 {
438   struct sra_elt *c;
439
440   if (elt->cannot_scalarize)
441     return false;
442
443   for (c = elt->children; c; c = c->sibling)
444     if (!can_completely_scalarize_p (c))
445       return false;
446
447   for (c = elt->groups; c; c = c->sibling)
448     if (!can_completely_scalarize_p (c))
449       return false;
450
451   return true;
452 }
453
454 \f
455 /* A simplified tree hashing algorithm that only handles the types of
456    trees we expect to find in sra_elt->element.  */
457
458 static hashval_t
459 sra_hash_tree (tree t)
460 {
461   hashval_t h;
462
463   switch (TREE_CODE (t))
464     {
465     case VAR_DECL:
466     case PARM_DECL:
467     case RESULT_DECL:
468       h = DECL_UID (t);
469       break;
470
471     case INTEGER_CST:
472       h = TREE_INT_CST_LOW (t) ^ TREE_INT_CST_HIGH (t);
473       break;
474
475     case RANGE_EXPR:
476       h = iterative_hash_expr (TREE_OPERAND (t, 0), 0);
477       h = iterative_hash_expr (TREE_OPERAND (t, 1), h);
478       break;
479
480     case FIELD_DECL:
481       /* We can have types that are compatible, but have different member
482          lists, so we can't hash fields by ID.  Use offsets instead.  */
483       h = iterative_hash_expr (DECL_FIELD_OFFSET (t), 0);
484       h = iterative_hash_expr (DECL_FIELD_BIT_OFFSET (t), h);
485       break;
486
487     case BIT_FIELD_REF:
488       /* Don't take operand 0 into account, that's our parent.  */
489       h = iterative_hash_expr (TREE_OPERAND (t, 1), 0);
490       h = iterative_hash_expr (TREE_OPERAND (t, 2), h);
491       break;
492
493     default:
494       gcc_unreachable ();
495     }
496
497   return h;
498 }
499
500 /* Hash function for type SRA_PAIR.  */
501
502 static hashval_t
503 sra_elt_hash (const void *x)
504 {
505   const struct sra_elt *const e = (const struct sra_elt *) x;
506   const struct sra_elt *p;
507   hashval_t h;
508
509   h = sra_hash_tree (e->element);
510
511   /* Take into account everything except bitfield blocks back up the
512      chain.  Given that chain lengths are rarely very long, this
513      should be acceptable.  If we truly identify this as a performance
514      problem, it should work to hash the pointer value
515      "e->parent".  */
516   for (p = e->parent; p ; p = p->parent)
517     if (!p->in_bitfld_block)
518       h = (h * 65521) ^ sra_hash_tree (p->element);
519
520   return h;
521 }
522
523 /* Equality function for type SRA_PAIR.  */
524
525 static int
526 sra_elt_eq (const void *x, const void *y)
527 {
528   const struct sra_elt *const a = (const struct sra_elt *) x;
529   const struct sra_elt *const b = (const struct sra_elt *) y;
530   tree ae, be;
531   const struct sra_elt *ap = a->parent;
532   const struct sra_elt *bp = b->parent;
533
534   if (ap)
535     while (ap->in_bitfld_block)
536       ap = ap->parent;
537   if (bp)
538     while (bp->in_bitfld_block)
539       bp = bp->parent;
540
541   if (ap != bp)
542     return false;
543
544   ae = a->element;
545   be = b->element;
546
547   if (ae == be)
548     return true;
549   if (TREE_CODE (ae) != TREE_CODE (be))
550     return false;
551
552   switch (TREE_CODE (ae))
553     {
554     case VAR_DECL:
555     case PARM_DECL:
556     case RESULT_DECL:
557       /* These are all pointer unique.  */
558       return false;
559
560     case INTEGER_CST:
561       /* Integers are not pointer unique, so compare their values.  */
562       return tree_int_cst_equal (ae, be);
563
564     case RANGE_EXPR:
565       return
566         tree_int_cst_equal (TREE_OPERAND (ae, 0), TREE_OPERAND (be, 0))
567         && tree_int_cst_equal (TREE_OPERAND (ae, 1), TREE_OPERAND (be, 1));
568
569     case FIELD_DECL:
570       /* Fields are unique within a record, but not between
571          compatible records.  */
572       if (DECL_FIELD_CONTEXT (ae) == DECL_FIELD_CONTEXT (be))
573         return false;
574       return fields_compatible_p (ae, be);
575
576     case BIT_FIELD_REF:
577       return
578         tree_int_cst_equal (TREE_OPERAND (ae, 1), TREE_OPERAND (be, 1))
579         && tree_int_cst_equal (TREE_OPERAND (ae, 2), TREE_OPERAND (be, 2));
580
581     default:
582       gcc_unreachable ();
583     }
584 }
585
586 /* Create or return the SRA_ELT structure for CHILD in PARENT.  PARENT
587    may be null, in which case CHILD must be a DECL.  */
588
589 static struct sra_elt *
590 lookup_element (struct sra_elt *parent, tree child, tree type,
591                 enum insert_option insert)
592 {
593   struct sra_elt dummy;
594   struct sra_elt **slot;
595   struct sra_elt *elt;
596
597   if (parent)
598     dummy.parent = parent->is_group ? parent->parent : parent;
599   else
600     dummy.parent = NULL;
601   dummy.element = child;
602
603   slot = (struct sra_elt **) htab_find_slot (sra_map, &dummy, insert);
604   if (!slot && insert == NO_INSERT)
605     return NULL;
606
607   elt = *slot;
608   if (!elt && insert == INSERT)
609     {
610       *slot = elt = XOBNEW (&sra_obstack, struct sra_elt);
611       memset (elt, 0, sizeof (*elt));
612
613       elt->parent = parent;
614       elt->element = child;
615       elt->type = type;
616       elt->is_scalar = is_sra_scalar_type (type);
617
618       if (parent)
619         {
620           if (IS_ELEMENT_FOR_GROUP (elt->element))
621             {
622               elt->is_group = true;
623               elt->sibling = parent->groups;
624               parent->groups = elt;
625             }
626           else
627             {
628               elt->sibling = parent->children;
629               parent->children = elt;
630             }
631         }
632
633       /* If this is a parameter, then if we want to scalarize, we have
634          one copy from the true function parameter.  Count it now.  */
635       if (TREE_CODE (child) == PARM_DECL)
636         {
637           elt->n_copies = 1;
638           bitmap_set_bit (needs_copy_in, DECL_UID (child));
639         }
640     }
641
642   return elt;
643 }
644
645 /* Create or return the SRA_ELT structure for EXPR if the expression
646    refers to a scalarizable variable.  */
647
648 static struct sra_elt *
649 maybe_lookup_element_for_expr (tree expr)
650 {
651   struct sra_elt *elt;
652   tree child;
653
654   switch (TREE_CODE (expr))
655     {
656     case VAR_DECL:
657     case PARM_DECL:
658     case RESULT_DECL:
659       if (is_sra_candidate_decl (expr))
660         return lookup_element (NULL, expr, TREE_TYPE (expr), INSERT);
661       return NULL;
662
663     case ARRAY_REF:
664       /* We can't scalarize variable array indices.  */
665       if (in_array_bounds_p (expr))
666         child = TREE_OPERAND (expr, 1);
667       else
668         return NULL;
669       break;
670
671     case ARRAY_RANGE_REF:
672       /* We can't scalarize variable array indices.  */
673       if (range_in_array_bounds_p (expr))
674         {
675           tree domain = TYPE_DOMAIN (TREE_TYPE (expr));
676           child = build2 (RANGE_EXPR, integer_type_node,
677                           TYPE_MIN_VALUE (domain), TYPE_MAX_VALUE (domain));
678         }
679       else
680         return NULL;
681       break;
682
683     case COMPONENT_REF:
684       {
685         tree type = TREE_TYPE (TREE_OPERAND (expr, 0));
686         /* Don't look through unions.  */
687         if (TREE_CODE (type) != RECORD_TYPE)
688           return NULL;
689         /* Neither through variable-sized records.  */
690         if (TYPE_SIZE (type) == NULL_TREE
691             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
692           return NULL;
693         child = TREE_OPERAND (expr, 1);
694       }
695       break;
696
697     case REALPART_EXPR:
698       child = integer_zero_node;
699       break;
700     case IMAGPART_EXPR:
701       child = integer_one_node;
702       break;
703
704     default:
705       return NULL;
706     }
707
708   elt = maybe_lookup_element_for_expr (TREE_OPERAND (expr, 0));
709   if (elt)
710     return lookup_element (elt, child, TREE_TYPE (expr), INSERT);
711   return NULL;
712 }
713
714 \f
715 /* Functions to walk just enough of the tree to see all scalarizable
716    references, and categorize them.  */
717
718 /* A set of callbacks for phases 2 and 4.  They'll be invoked for the
719    various kinds of references seen.  In all cases, *GSI is an iterator
720    pointing to the statement being processed.  */
721 struct sra_walk_fns
722 {
723   /* Invoked when ELT is required as a unit.  Note that ELT might refer to
724      a leaf node, in which case this is a simple scalar reference.  *EXPR_P
725      points to the location of the expression.  IS_OUTPUT is true if this
726      is a left-hand-side reference.  USE_ALL is true if we saw something we
727      couldn't quite identify and had to force the use of the entire object.  */
728   void (*use) (struct sra_elt *elt, tree *expr_p,
729                gimple_stmt_iterator *gsi, bool is_output, bool use_all);
730
731   /* Invoked when we have a copy between two scalarizable references.  */
732   void (*copy) (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
733                 gimple_stmt_iterator *gsi);
734
735   /* Invoked when ELT is initialized from a constant.  VALUE may be NULL,
736      in which case it should be treated as an empty CONSTRUCTOR.  */
737   void (*init) (struct sra_elt *elt, tree value, gimple_stmt_iterator *gsi);
738
739   /* Invoked when we have a copy between one scalarizable reference ELT
740      and one non-scalarizable reference OTHER without side-effects. 
741      IS_OUTPUT is true if ELT is on the left-hand side.  */
742   void (*ldst) (struct sra_elt *elt, tree other,
743                 gimple_stmt_iterator *gsi, bool is_output);
744
745   /* True during phase 2, false during phase 4.  */
746   /* ??? This is a hack.  */
747   bool initial_scan;
748 };
749
750 #ifdef ENABLE_CHECKING
751 /* Invoked via walk_tree, if *TP contains a candidate decl, return it.  */
752
753 static tree
754 sra_find_candidate_decl (tree *tp, int *walk_subtrees,
755                          void *data ATTRIBUTE_UNUSED)
756 {
757   tree t = *tp;
758   enum tree_code code = TREE_CODE (t);
759
760   if (code == VAR_DECL || code == PARM_DECL || code == RESULT_DECL)
761     {
762       *walk_subtrees = 0;
763       if (is_sra_candidate_decl (t))
764         return t;
765     }
766   else if (TYPE_P (t))
767     *walk_subtrees = 0;
768
769   return NULL;
770 }
771 #endif
772
773 /* Walk most expressions looking for a scalarizable aggregate.
774    If we find one, invoke FNS->USE.  */
775
776 static void
777 sra_walk_expr (tree *expr_p, gimple_stmt_iterator *gsi, bool is_output,
778                const struct sra_walk_fns *fns)
779 {
780   tree expr = *expr_p;
781   tree inner = expr;
782   bool disable_scalarization = false;
783   bool use_all_p = false;
784
785   /* We're looking to collect a reference expression between EXPR and INNER,
786      such that INNER is a scalarizable decl and all other nodes through EXPR
787      are references that we can scalarize.  If we come across something that
788      we can't scalarize, we reset EXPR.  This has the effect of making it
789      appear that we're referring to the larger expression as a whole.  */
790
791   while (1)
792     switch (TREE_CODE (inner))
793       {
794       case VAR_DECL:
795       case PARM_DECL:
796       case RESULT_DECL:
797         /* If there is a scalarizable decl at the bottom, then process it.  */
798         if (is_sra_candidate_decl (inner))
799           {
800             struct sra_elt *elt = maybe_lookup_element_for_expr (expr);
801             if (disable_scalarization)
802               elt->cannot_scalarize = true;
803             else
804               fns->use (elt, expr_p, gsi, is_output, use_all_p);
805           }
806         return;
807
808       case ARRAY_REF:
809         /* Non-constant index means any member may be accessed.  Prevent the
810            expression from being scalarized.  If we were to treat this as a
811            reference to the whole array, we can wind up with a single dynamic
812            index reference inside a loop being overridden by several constant
813            index references during loop setup.  It's possible that this could
814            be avoided by using dynamic usage counts based on BB trip counts
815            (based on loop analysis or profiling), but that hardly seems worth
816            the effort.  */
817         /* ??? Hack.  Figure out how to push this into the scan routines
818            without duplicating too much code.  */
819         if (!in_array_bounds_p (inner))
820           {
821             disable_scalarization = true;
822             goto use_all;
823           }
824         /* ??? Are we assured that non-constant bounds and stride will have
825            the same value everywhere?  I don't think Fortran will...  */
826         if (TREE_OPERAND (inner, 2) || TREE_OPERAND (inner, 3))
827           goto use_all;
828         inner = TREE_OPERAND (inner, 0);
829         break;
830
831       case ARRAY_RANGE_REF:
832         if (!range_in_array_bounds_p (inner))
833           {
834             disable_scalarization = true;
835             goto use_all;
836           }
837         /* ??? See above non-constant bounds and stride .  */
838         if (TREE_OPERAND (inner, 2) || TREE_OPERAND (inner, 3))
839           goto use_all;
840         inner = TREE_OPERAND (inner, 0);
841         break;
842
843       case COMPONENT_REF:
844         {
845           tree type = TREE_TYPE (TREE_OPERAND (inner, 0));
846           /* Don't look through unions.  */
847           if (TREE_CODE (type) != RECORD_TYPE)
848             goto use_all;
849           /* Neither through variable-sized records.  */
850           if (TYPE_SIZE (type) == NULL_TREE
851               || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
852             goto use_all;
853           inner = TREE_OPERAND (inner, 0);
854         }
855         break;
856
857       case REALPART_EXPR:
858       case IMAGPART_EXPR:
859         inner = TREE_OPERAND (inner, 0);
860         break;
861
862       case BIT_FIELD_REF:
863         /* A bit field reference to a specific vector is scalarized but for
864            ones for inputs need to be marked as used on the left hand size so
865            when we scalarize it, we can mark that variable as non renamable.  */
866         if (is_output
867             && TREE_CODE (TREE_TYPE (TREE_OPERAND (inner, 0))) == VECTOR_TYPE)
868           {
869             struct sra_elt *elt
870               = maybe_lookup_element_for_expr (TREE_OPERAND (inner, 0));
871             if (elt)
872               elt->is_vector_lhs = true;
873           }
874
875         /* A bit field reference (access to *multiple* fields simultaneously)
876            is not currently scalarized.  Consider this an access to the full
877            outer element, to which walk_tree will bring us next.  */
878         goto use_all;
879
880       CASE_CONVERT:
881         /* Similarly, a nop explicitly wants to look at an object in a
882            type other than the one we've scalarized.  */
883         goto use_all;
884
885       case VIEW_CONVERT_EXPR:
886         /* Likewise for a view conversion, but with an additional twist:
887            it can be on the LHS and, in this case, an access to the full
888            outer element would mean a killing def.  So we need to punt
889            if we haven't already a full access to the current element,
890            because we cannot pretend to have a killing def if we only
891            have a partial access at some level.  */
892         if (is_output && !use_all_p && inner != expr)
893           disable_scalarization = true;
894         goto use_all;
895
896       case WITH_SIZE_EXPR:
897         /* This is a transparent wrapper.  The entire inner expression really
898            is being used.  */
899         goto use_all;
900
901       use_all:
902         expr_p = &TREE_OPERAND (inner, 0);
903         inner = expr = *expr_p;
904         use_all_p = true;
905         break;
906
907       default:
908 #ifdef ENABLE_CHECKING
909         /* Validate that we're not missing any references.  */
910         gcc_assert (!walk_tree (&inner, sra_find_candidate_decl, NULL, NULL));
911 #endif
912         return;
913       }
914 }
915
916 /* Walk the arguments of a GIMPLE_CALL looking for scalarizable aggregates.
917    If we find one, invoke FNS->USE.  */
918
919 static void
920 sra_walk_gimple_call (gimple stmt, gimple_stmt_iterator *gsi,
921                     const struct sra_walk_fns *fns)
922 {
923   int i;
924   int nargs = gimple_call_num_args (stmt);
925
926   for (i = 0; i < nargs; i++)
927     sra_walk_expr (gimple_call_arg_ptr (stmt, i), gsi, false, fns);
928
929   if (gimple_call_lhs (stmt))
930     sra_walk_expr (gimple_call_lhs_ptr (stmt), gsi, true, fns);
931 }
932
933 /* Walk the inputs and outputs of a GIMPLE_ASM looking for scalarizable
934    aggregates.  If we find one, invoke FNS->USE.  */
935
936 static void
937 sra_walk_gimple_asm (gimple stmt, gimple_stmt_iterator *gsi,
938                    const struct sra_walk_fns *fns)
939 {
940   size_t i;
941   for (i = 0; i < gimple_asm_ninputs (stmt); i++)
942     sra_walk_expr (&TREE_VALUE (gimple_asm_input_op (stmt, i)), gsi, false, fns);
943   for (i = 0; i < gimple_asm_noutputs (stmt); i++)
944     sra_walk_expr (&TREE_VALUE (gimple_asm_output_op (stmt, i)), gsi, true, fns);
945 }
946
947 /* Walk a GIMPLE_ASSIGN and categorize the assignment appropriately.  */
948
949 static void
950 sra_walk_gimple_assign (gimple stmt, gimple_stmt_iterator *gsi,
951                         const struct sra_walk_fns *fns)
952 {
953   struct sra_elt *lhs_elt = NULL, *rhs_elt = NULL;
954   tree lhs, rhs;
955
956   /* If there is more than 1 element on the RHS, only walk the lhs.  */
957   if (!gimple_assign_single_p (stmt))
958     {
959       sra_walk_expr (gimple_assign_lhs_ptr (stmt), gsi, true, fns);
960       return;
961     }
962
963   lhs = gimple_assign_lhs (stmt);
964   rhs = gimple_assign_rhs1 (stmt);
965   lhs_elt = maybe_lookup_element_for_expr (lhs);
966   rhs_elt = maybe_lookup_element_for_expr (rhs);
967
968   /* If both sides are scalarizable, this is a COPY operation.  */
969   if (lhs_elt && rhs_elt)
970     {
971       fns->copy (lhs_elt, rhs_elt, gsi);
972       return;
973     }
974
975   /* If the RHS is scalarizable, handle it.  There are only two cases.  */
976   if (rhs_elt)
977     {
978       if (!rhs_elt->is_scalar && !TREE_SIDE_EFFECTS (lhs))
979         fns->ldst (rhs_elt, lhs, gsi, false);
980       else
981         fns->use (rhs_elt, gimple_assign_rhs1_ptr (stmt), gsi, false, false);
982     }
983
984   /* If it isn't scalarizable, there may be scalarizable variables within, so
985      check for a call or else walk the RHS to see if we need to do any
986      copy-in operations.  We need to do it before the LHS is scalarized so
987      that the statements get inserted in the proper place, before any
988      copy-out operations.  */
989   else
990     sra_walk_expr (gimple_assign_rhs1_ptr (stmt), gsi, false, fns);
991
992   /* Likewise, handle the LHS being scalarizable.  We have cases similar
993      to those above, but also want to handle RHS being constant.  */
994   if (lhs_elt)
995     {
996       /* If this is an assignment from a constant, or constructor, then
997          we have access to all of the elements individually.  Invoke INIT.  */
998       if (TREE_CODE (rhs) == COMPLEX_EXPR
999           || TREE_CODE (rhs) == COMPLEX_CST
1000           || TREE_CODE (rhs) == CONSTRUCTOR)
1001         fns->init (lhs_elt, rhs, gsi);
1002
1003       /* If this is an assignment from read-only memory, treat this as if
1004          we'd been passed the constructor directly.  Invoke INIT.  */
1005       else if (TREE_CODE (rhs) == VAR_DECL
1006                && TREE_STATIC (rhs)
1007                && !DECL_EXTERNAL (rhs)
1008                && TREE_READONLY (rhs)
1009                && targetm.binds_local_p (rhs))
1010         fns->init (lhs_elt, DECL_INITIAL (rhs), gsi);
1011
1012       /* If this is a copy from a non-scalarizable lvalue, invoke LDST.
1013          The lvalue requirement prevents us from trying to directly scalarize
1014          the result of a function call.  Which would result in trying to call
1015          the function multiple times, and other evil things.  */
1016       else if (!lhs_elt->is_scalar
1017                && !TREE_SIDE_EFFECTS (rhs) && is_gimple_addressable (rhs))
1018         fns->ldst (lhs_elt, rhs, gsi, true);
1019
1020       /* Otherwise we're being used in some context that requires the
1021          aggregate to be seen as a whole.  Invoke USE.  */
1022       else
1023         fns->use (lhs_elt, gimple_assign_lhs_ptr (stmt), gsi, true, false);
1024     }
1025
1026   /* Similarly to above, LHS_ELT being null only means that the LHS as a
1027      whole is not a scalarizable reference.  There may be occurrences of
1028      scalarizable variables within, which implies a USE.  */
1029   else
1030     sra_walk_expr (gimple_assign_lhs_ptr (stmt), gsi, true, fns);
1031 }
1032
1033 /* Entry point to the walk functions.  Search the entire function,
1034    invoking the callbacks in FNS on each of the references to
1035    scalarizable variables.  */
1036
1037 static void
1038 sra_walk_function (const struct sra_walk_fns *fns)
1039 {
1040   basic_block bb;
1041   gimple_stmt_iterator si, ni;
1042
1043   /* ??? Phase 4 could derive some benefit to walking the function in
1044      dominator tree order.  */
1045
1046   FOR_EACH_BB (bb)
1047     for (si = gsi_start_bb (bb); !gsi_end_p (si); si = ni)
1048       {
1049         gimple stmt;
1050
1051         stmt = gsi_stmt (si);
1052
1053         ni = si;
1054         gsi_next (&ni);
1055
1056         /* If the statement does not reference memory, then it doesn't
1057            make any structure references that we care about.  */
1058         if (!gimple_references_memory_p (stmt))
1059           continue;
1060
1061         switch (gimple_code (stmt))
1062           {
1063           case GIMPLE_RETURN:
1064             /* If we have "return <retval>" then the return value is
1065                already exposed for our pleasure.  Walk it as a USE to
1066                force all the components back in place for the return.
1067                */
1068             if (gimple_return_retval (stmt)  == NULL_TREE)
1069               ;
1070             else
1071               sra_walk_expr (gimple_return_retval_ptr (stmt), &si, false,
1072                              fns);
1073             break;
1074
1075           case GIMPLE_ASSIGN:
1076             sra_walk_gimple_assign (stmt, &si, fns);
1077             break;
1078           case GIMPLE_CALL:
1079             sra_walk_gimple_call (stmt, &si, fns);
1080             break;
1081           case GIMPLE_ASM:
1082             sra_walk_gimple_asm (stmt, &si, fns);
1083             break;
1084
1085           default:
1086             break;
1087           }
1088       }
1089 }
1090 \f
1091 /* Phase One: Scan all referenced variables in the program looking for
1092    structures that could be decomposed.  */
1093
1094 static bool
1095 find_candidates_for_sra (void)
1096 {
1097   bool any_set = false;
1098   tree var;
1099   referenced_var_iterator rvi;
1100
1101   FOR_EACH_REFERENCED_VAR (var, rvi)
1102     {
1103       if (decl_can_be_decomposed_p (var))
1104         {
1105           bitmap_set_bit (sra_candidates, DECL_UID (var));
1106           any_set = true;
1107         }
1108     }
1109
1110   return any_set;
1111 }
1112
1113 \f
1114 /* Phase Two: Scan all references to scalarizable variables.  Count the
1115    number of times they are used or copied respectively.  */
1116
1117 /* Callbacks to fill in SRA_WALK_FNS.  Everything but USE is
1118    considered a copy, because we can decompose the reference such that
1119    the sub-elements needn't be contiguous.  */
1120
1121 static void
1122 scan_use (struct sra_elt *elt, tree *expr_p ATTRIBUTE_UNUSED,
1123           gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
1124           bool is_output ATTRIBUTE_UNUSED, bool use_all ATTRIBUTE_UNUSED)
1125 {
1126   elt->n_uses += 1;
1127 }
1128
1129 static void
1130 scan_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
1131            gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED)
1132 {
1133   lhs_elt->n_copies += 1;
1134   rhs_elt->n_copies += 1;
1135 }
1136
1137 static void
1138 scan_init (struct sra_elt *lhs_elt, tree rhs ATTRIBUTE_UNUSED,
1139            gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED)
1140 {
1141   lhs_elt->n_copies += 1;
1142 }
1143
1144 static void
1145 scan_ldst (struct sra_elt *elt, tree other ATTRIBUTE_UNUSED,
1146            gimple_stmt_iterator *gsi ATTRIBUTE_UNUSED,
1147            bool is_output ATTRIBUTE_UNUSED)
1148 {
1149   elt->n_copies += 1;
1150 }
1151
1152 /* Dump the values we collected during the scanning phase.  */
1153
1154 static void
1155 scan_dump (struct sra_elt *elt)
1156 {
1157   struct sra_elt *c;
1158
1159   dump_sra_elt_name (dump_file, elt);
1160   fprintf (dump_file, ": n_uses=%u n_copies=%u\n", elt->n_uses, elt->n_copies);
1161
1162   for (c = elt->children; c ; c = c->sibling)
1163     scan_dump (c);
1164
1165   for (c = elt->groups; c ; c = c->sibling)
1166     scan_dump (c);
1167 }
1168
1169 /* Entry point to phase 2.  Scan the entire function, building up
1170    scalarization data structures, recording copies and uses.  */
1171
1172 static void
1173 scan_function (void)
1174 {
1175   static const struct sra_walk_fns fns = {
1176     scan_use, scan_copy, scan_init, scan_ldst, true
1177   };
1178   bitmap_iterator bi;
1179
1180   sra_walk_function (&fns);
1181
1182   if (dump_file && (dump_flags & TDF_DETAILS))
1183     {
1184       unsigned i;
1185
1186       fputs ("\nScan results:\n", dump_file);
1187       EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1188         {
1189           tree var = referenced_var (i);
1190           struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1191           if (elt)
1192             scan_dump (elt);
1193         }
1194       fputc ('\n', dump_file);
1195     }
1196 }
1197 \f
1198 /* Phase Three: Make decisions about which variables to scalarize, if any.
1199    All elements to be scalarized have replacement variables made for them.  */
1200
1201 /* A subroutine of build_element_name.  Recursively build the element
1202    name on the obstack.  */
1203
1204 static void
1205 build_element_name_1 (struct sra_elt *elt)
1206 {
1207   tree t;
1208   char buffer[32];
1209
1210   if (elt->parent)
1211     {
1212       build_element_name_1 (elt->parent);
1213       obstack_1grow (&sra_obstack, '$');
1214
1215       if (TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
1216         {
1217           if (elt->element == integer_zero_node)
1218             obstack_grow (&sra_obstack, "real", 4);
1219           else
1220             obstack_grow (&sra_obstack, "imag", 4);
1221           return;
1222         }
1223     }
1224
1225   t = elt->element;
1226   if (TREE_CODE (t) == INTEGER_CST)
1227     {
1228       /* ??? Eh.  Don't bother doing double-wide printing.  */
1229       sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (t));
1230       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1231     }
1232   else if (TREE_CODE (t) == BIT_FIELD_REF)
1233     {
1234       sprintf (buffer, "B" HOST_WIDE_INT_PRINT_DEC,
1235                tree_low_cst (TREE_OPERAND (t, 2), 1));
1236       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1237       sprintf (buffer, "F" HOST_WIDE_INT_PRINT_DEC,
1238                tree_low_cst (TREE_OPERAND (t, 1), 1));
1239       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1240     }
1241   else
1242     {
1243       tree name = DECL_NAME (t);
1244       if (name)
1245         obstack_grow (&sra_obstack, IDENTIFIER_POINTER (name),
1246                       IDENTIFIER_LENGTH (name));
1247       else
1248         {
1249           sprintf (buffer, "D%u", DECL_UID (t));
1250           obstack_grow (&sra_obstack, buffer, strlen (buffer));
1251         }
1252     }
1253 }
1254
1255 /* Construct a pretty variable name for an element's replacement variable.
1256    The name is built on the obstack.  */
1257
1258 static char *
1259 build_element_name (struct sra_elt *elt)
1260 {
1261   build_element_name_1 (elt);
1262   obstack_1grow (&sra_obstack, '\0');
1263   return XOBFINISH (&sra_obstack, char *);
1264 }
1265
1266 /* Instantiate an element as an independent variable.  */
1267
1268 static void
1269 instantiate_element (struct sra_elt *elt)
1270 {
1271   struct sra_elt *base_elt;
1272   tree var, base;
1273   bool nowarn = TREE_NO_WARNING (elt->element);
1274
1275   for (base_elt = elt; base_elt->parent; base_elt = base_elt->parent)
1276     if (!nowarn)
1277       nowarn = TREE_NO_WARNING (base_elt->parent->element);
1278   base = base_elt->element;
1279
1280   elt->replacement = var = make_rename_temp (elt->type, "SR");
1281
1282   if (DECL_P (elt->element)
1283       && !tree_int_cst_equal (DECL_SIZE (var), DECL_SIZE (elt->element)))
1284     {
1285       DECL_SIZE (var) = DECL_SIZE (elt->element);
1286       DECL_SIZE_UNIT (var) = DECL_SIZE_UNIT (elt->element);
1287
1288       elt->in_bitfld_block = 1;
1289       elt->replacement = fold_build3 (BIT_FIELD_REF, elt->type, var,
1290                                       DECL_SIZE (var),
1291                                       BYTES_BIG_ENDIAN
1292                                       ? size_binop (MINUS_EXPR,
1293                                                     TYPE_SIZE (elt->type),
1294                                                     DECL_SIZE (var))
1295                                       : bitsize_int (0));
1296     }
1297
1298   /* For vectors, if used on the left hand side with BIT_FIELD_REF,
1299      they are not a gimple register.  */
1300   if (TREE_CODE (TREE_TYPE (var)) == VECTOR_TYPE && elt->is_vector_lhs)
1301     DECL_GIMPLE_REG_P (var) = 0;
1302
1303   DECL_SOURCE_LOCATION (var) = DECL_SOURCE_LOCATION (base);
1304   DECL_ARTIFICIAL (var) = 1;
1305
1306   if (TREE_THIS_VOLATILE (elt->type))
1307     {
1308       TREE_THIS_VOLATILE (var) = 1;
1309       TREE_SIDE_EFFECTS (var) = 1;
1310     }
1311
1312   if (DECL_NAME (base) && !DECL_IGNORED_P (base))
1313     {
1314       char *pretty_name = build_element_name (elt);
1315       DECL_NAME (var) = get_identifier (pretty_name);
1316       obstack_free (&sra_obstack, pretty_name);
1317
1318       SET_DECL_DEBUG_EXPR (var, generate_element_ref (elt));
1319       DECL_DEBUG_EXPR_IS_FROM (var) = 1;
1320       
1321       DECL_IGNORED_P (var) = 0;
1322       TREE_NO_WARNING (var) = nowarn;
1323     }
1324   else
1325     {
1326       DECL_IGNORED_P (var) = 1;
1327       /* ??? We can't generate any warning that would be meaningful.  */
1328       TREE_NO_WARNING (var) = 1;
1329     }
1330
1331   /* Zero-initialize bit-field scalarization variables, to avoid
1332      triggering undefined behavior.  */
1333   if (TREE_CODE (elt->element) == BIT_FIELD_REF
1334       || (var != elt->replacement
1335           && TREE_CODE (elt->replacement) == BIT_FIELD_REF))
1336     {
1337       gimple_seq init = sra_build_assignment (var,
1338                                               fold_convert (TREE_TYPE (var),
1339                                                             integer_zero_node)
1340                                              );
1341       insert_edge_copies_seq (init, ENTRY_BLOCK_PTR);
1342       mark_all_v_defs_seq (init);
1343     }
1344
1345   if (dump_file)
1346     {
1347       fputs ("  ", dump_file);
1348       dump_sra_elt_name (dump_file, elt);
1349       fputs (" -> ", dump_file);
1350       print_generic_expr (dump_file, var, dump_flags);
1351       fputc ('\n', dump_file);
1352     }
1353 }
1354
1355 /* Make one pass across an element tree deciding whether or not it's
1356    profitable to instantiate individual leaf scalars.
1357
1358    PARENT_USES and PARENT_COPIES are the sum of the N_USES and N_COPIES
1359    fields all the way up the tree.  */
1360
1361 static void
1362 decide_instantiation_1 (struct sra_elt *elt, unsigned int parent_uses,
1363                         unsigned int parent_copies)
1364 {
1365   if (dump_file && !elt->parent)
1366     {
1367       fputs ("Initial instantiation for ", dump_file);
1368       dump_sra_elt_name (dump_file, elt);
1369       fputc ('\n', dump_file);
1370     }
1371
1372   if (elt->cannot_scalarize)
1373     return;
1374
1375   if (elt->is_scalar)
1376     {
1377       /* The decision is simple: instantiate if we're used more frequently
1378          than the parent needs to be seen as a complete unit.  */
1379       if (elt->n_uses + elt->n_copies + parent_copies > parent_uses)
1380         instantiate_element (elt);
1381     }
1382   else
1383     {
1384       struct sra_elt *c, *group;
1385       unsigned int this_uses = elt->n_uses + parent_uses;
1386       unsigned int this_copies = elt->n_copies + parent_copies;
1387
1388       /* Consider groups of sub-elements as weighing in favour of
1389          instantiation whatever their size.  */
1390       for (group = elt->groups; group ; group = group->sibling)
1391         FOR_EACH_ACTUAL_CHILD (c, group)
1392           {
1393             c->n_uses += group->n_uses;
1394             c->n_copies += group->n_copies;
1395           }
1396
1397       for (c = elt->children; c ; c = c->sibling)
1398         decide_instantiation_1 (c, this_uses, this_copies);
1399     }
1400 }
1401
1402 /* Compute the size and number of all instantiated elements below ELT.
1403    We will only care about this if the size of the complete structure
1404    fits in a HOST_WIDE_INT, so we don't have to worry about overflow.  */
1405
1406 static unsigned int
1407 sum_instantiated_sizes (struct sra_elt *elt, unsigned HOST_WIDE_INT *sizep)
1408 {
1409   if (elt->replacement)
1410     {
1411       *sizep += TREE_INT_CST_LOW (TYPE_SIZE_UNIT (elt->type));
1412       return 1;
1413     }
1414   else
1415     {
1416       struct sra_elt *c;
1417       unsigned int count = 0;
1418
1419       for (c = elt->children; c ; c = c->sibling)
1420         count += sum_instantiated_sizes (c, sizep);
1421
1422       return count;
1423     }
1424 }
1425
1426 /* Instantiate fields in ELT->TYPE that are not currently present as
1427    children of ELT.  */
1428
1429 static void instantiate_missing_elements (struct sra_elt *elt);
1430
1431 static struct sra_elt *
1432 instantiate_missing_elements_1 (struct sra_elt *elt, tree child, tree type)
1433 {
1434   struct sra_elt *sub = lookup_element (elt, child, type, INSERT);
1435   if (sub->is_scalar)
1436     {
1437       if (sub->replacement == NULL)
1438         instantiate_element (sub);
1439     }
1440   else
1441     instantiate_missing_elements (sub);
1442   return sub;
1443 }
1444
1445 /* Obtain the canonical type for field F of ELEMENT.  */
1446
1447 static tree
1448 canon_type_for_field (tree f, tree element)
1449 {
1450   tree field_type = TREE_TYPE (f);
1451
1452   /* canonicalize_component_ref() unwidens some bit-field types (not
1453      marked as DECL_BIT_FIELD in C++), so we must do the same, lest we
1454      may introduce type mismatches.  */
1455   if (INTEGRAL_TYPE_P (field_type)
1456       && DECL_MODE (f) != TYPE_MODE (field_type))
1457     field_type = TREE_TYPE (get_unwidened (build3 (COMPONENT_REF,
1458                                                    field_type,
1459                                                    element,
1460                                                    f, NULL_TREE),
1461                                            NULL_TREE));
1462
1463   return field_type;
1464 }
1465
1466 /* Look for adjacent fields of ELT starting at F that we'd like to
1467    scalarize as a single variable.  Return the last field of the
1468    group.  */
1469
1470 static tree
1471 try_instantiate_multiple_fields (struct sra_elt *elt, tree f)
1472 {
1473   int count;
1474   unsigned HOST_WIDE_INT align, bit, size, alchk;
1475   enum machine_mode mode;
1476   tree first = f, prev;
1477   tree type, var;
1478   struct sra_elt *block;
1479
1480   /* Point fields are typically best handled as standalone entities.  */
1481   if (POINTER_TYPE_P (TREE_TYPE (f)))
1482     return f;
1483     
1484   if (!is_sra_scalar_type (TREE_TYPE (f))
1485       || !host_integerp (DECL_FIELD_OFFSET (f), 1)
1486       || !host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)
1487       || !host_integerp (DECL_SIZE (f), 1)
1488       || lookup_element (elt, f, NULL, NO_INSERT))
1489     return f;
1490
1491   block = elt;
1492
1493   /* For complex and array objects, there are going to be integer
1494      literals as child elements.  In this case, we can't just take the
1495      alignment and mode of the decl, so we instead rely on the element
1496      type.
1497
1498      ??? We could try to infer additional alignment from the full
1499      object declaration and the location of the sub-elements we're
1500      accessing.  */
1501   for (count = 0; !DECL_P (block->element); count++)
1502     block = block->parent;
1503
1504   align = DECL_ALIGN (block->element);
1505   alchk = GET_MODE_BITSIZE (DECL_MODE (block->element));
1506
1507   if (count)
1508     {
1509       type = TREE_TYPE (block->element);
1510       while (count--)
1511         type = TREE_TYPE (type);
1512
1513       align = TYPE_ALIGN (type);
1514       alchk = GET_MODE_BITSIZE (TYPE_MODE (type));
1515     }
1516
1517   if (align < alchk)
1518     align = alchk;
1519
1520   /* Coalescing wider fields is probably pointless and
1521      inefficient.  */
1522   if (align > BITS_PER_WORD)
1523     align = BITS_PER_WORD;
1524
1525   bit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1526     + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1527   size = tree_low_cst (DECL_SIZE (f), 1);
1528
1529   alchk = align - 1;
1530   alchk = ~alchk;
1531
1532   if ((bit & alchk) != ((bit + size - 1) & alchk))
1533     return f;
1534
1535   /* Find adjacent fields in the same alignment word.  */
1536
1537   for (prev = f, f = TREE_CHAIN (f);
1538        f && TREE_CODE (f) == FIELD_DECL
1539          && is_sra_scalar_type (TREE_TYPE (f))
1540          && host_integerp (DECL_FIELD_OFFSET (f), 1)
1541          && host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)
1542          && host_integerp (DECL_SIZE (f), 1)
1543          && !lookup_element (elt, f, NULL, NO_INSERT);
1544        prev = f, f = TREE_CHAIN (f))
1545     {
1546       unsigned HOST_WIDE_INT nbit, nsize;
1547
1548       nbit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1549         + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1550       nsize = tree_low_cst (DECL_SIZE (f), 1);
1551
1552       if (bit + size == nbit)
1553         {
1554           if ((bit & alchk) != ((nbit + nsize - 1) & alchk))
1555             {
1556               /* If we're at an alignment boundary, don't bother
1557                  growing alignment such that we can include this next
1558                  field.  */
1559               if ((nbit & alchk)
1560                   || GET_MODE_BITSIZE (DECL_MODE (f)) <= align)
1561                 break;
1562
1563               align = GET_MODE_BITSIZE (DECL_MODE (f));
1564               alchk = align - 1;
1565               alchk = ~alchk;
1566
1567               if ((bit & alchk) != ((nbit + nsize - 1) & alchk))
1568                 break;
1569             }
1570           size += nsize;
1571         }
1572       else if (nbit + nsize == bit)
1573         {
1574           if ((nbit & alchk) != ((bit + size - 1) & alchk))
1575             {
1576               if ((bit & alchk)
1577                   || GET_MODE_BITSIZE (DECL_MODE (f)) <= align)
1578                 break;
1579
1580               align = GET_MODE_BITSIZE (DECL_MODE (f));
1581               alchk = align - 1;
1582               alchk = ~alchk;
1583
1584               if ((nbit & alchk) != ((bit + size - 1) & alchk))
1585                 break;
1586             }
1587           bit = nbit;
1588           size += nsize;
1589         }
1590       else
1591         break;
1592     }
1593
1594   f = prev;
1595
1596   if (f == first)
1597     return f;
1598
1599   gcc_assert ((bit & alchk) == ((bit + size - 1) & alchk));
1600
1601   /* Try to widen the bit range so as to cover padding bits as well.  */
1602
1603   if ((bit & ~alchk) || size != align)
1604     {
1605       unsigned HOST_WIDE_INT mbit = bit & alchk;
1606       unsigned HOST_WIDE_INT msize = align;
1607
1608       for (f = TYPE_FIELDS (elt->type);
1609            f; f = TREE_CHAIN (f))
1610         {
1611           unsigned HOST_WIDE_INT fbit, fsize;
1612
1613           /* Skip the fields from first to prev.  */
1614           if (f == first)
1615             {
1616               f = prev;
1617               continue;
1618             }
1619
1620           if (!(TREE_CODE (f) == FIELD_DECL
1621                 && host_integerp (DECL_FIELD_OFFSET (f), 1)
1622                 && host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)))
1623             continue;
1624
1625           fbit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1626             + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1627
1628           /* If we're past the selected word, we're fine.  */
1629           if ((bit & alchk) < (fbit & alchk))
1630             continue;
1631
1632           if (host_integerp (DECL_SIZE (f), 1))
1633             fsize = tree_low_cst (DECL_SIZE (f), 1);
1634           else
1635             /* Assume a variable-sized field takes up all space till
1636                the end of the word.  ??? Endianness issues?  */
1637             fsize = align - (fbit & alchk);
1638
1639           if ((fbit & alchk) < (bit & alchk))
1640             {
1641               /* A large field might start at a previous word and
1642                  extend into the selected word.  Exclude those
1643                  bits.  ??? Endianness issues? */
1644               HOST_WIDE_INT diff = fbit + fsize - mbit;
1645
1646               if (diff <= 0)
1647                 continue;
1648
1649               mbit += diff;
1650               msize -= diff;
1651             }
1652           else
1653             {
1654               /* Non-overlapping, great.  */
1655               if (fbit + fsize <= mbit
1656                   || mbit + msize <= fbit)
1657                 continue;
1658
1659               if (fbit <= mbit)
1660                 {
1661                   unsigned HOST_WIDE_INT diff = fbit + fsize - mbit;
1662                   mbit += diff;
1663                   msize -= diff;
1664                 }
1665               else if (fbit > mbit)
1666                 msize -= (mbit + msize - fbit);
1667               else
1668                 gcc_unreachable ();
1669             }
1670         }
1671
1672       bit = mbit;
1673       size = msize;
1674     }
1675
1676   /* Now we know the bit range we're interested in.  Find the smallest
1677      machine mode we can use to access it.  */
1678
1679   for (mode = smallest_mode_for_size (size, MODE_INT);
1680        ;
1681        mode = GET_MODE_WIDER_MODE (mode))
1682     {
1683       gcc_assert (mode != VOIDmode);
1684
1685       alchk = GET_MODE_PRECISION (mode) - 1;
1686       alchk = ~alchk;
1687
1688       if ((bit & alchk) == ((bit + size - 1) & alchk))
1689         break;
1690     }
1691
1692   gcc_assert (~alchk < align);
1693
1694   /* Create the field group as a single variable.  */
1695
1696   /* We used to create a type for the mode above, but size turns
1697      to be out not of mode-size.  As we need a matching type
1698      to build a BIT_FIELD_REF, use a nonstandard integer type as
1699      fallback.  */
1700   type = lang_hooks.types.type_for_size (size, 1);
1701   if (!type || TYPE_PRECISION (type) != size)
1702     type = build_nonstandard_integer_type (size, 1);
1703   gcc_assert (type);
1704   var = build3 (BIT_FIELD_REF, type, NULL_TREE,
1705                 bitsize_int (size), bitsize_int (bit));
1706
1707   block = instantiate_missing_elements_1 (elt, var, type);
1708   gcc_assert (block && block->is_scalar);
1709
1710   var = block->replacement;
1711   block->in_bitfld_block = 2;
1712
1713   /* Add the member fields to the group, such that they access
1714      portions of the group variable.  */
1715
1716   for (f = first; f != TREE_CHAIN (prev); f = TREE_CHAIN (f))
1717     {
1718       tree field_type = canon_type_for_field (f, elt->element);
1719       struct sra_elt *fld = lookup_element (block, f, field_type, INSERT);
1720
1721       gcc_assert (fld && fld->is_scalar && !fld->replacement);
1722
1723       fld->replacement = fold_build3 (BIT_FIELD_REF, field_type, var,
1724                                       bitsize_int (TYPE_PRECISION (field_type)),
1725                                       bitsize_int
1726                                       ((TREE_INT_CST_LOW (DECL_FIELD_OFFSET (f))
1727                                         * BITS_PER_UNIT
1728                                         + (TREE_INT_CST_LOW
1729                                            (DECL_FIELD_BIT_OFFSET (f)))
1730                                         - (TREE_INT_CST_LOW
1731                                            (TREE_OPERAND (block->element, 2))))
1732                                        & ~alchk));
1733       fld->in_bitfld_block = 1;
1734     }
1735
1736   return prev;
1737 }
1738
1739 static void
1740 instantiate_missing_elements (struct sra_elt *elt)
1741 {
1742   tree type = elt->type;
1743
1744   switch (TREE_CODE (type))
1745     {
1746     case RECORD_TYPE:
1747       {
1748         tree f;
1749         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
1750           if (TREE_CODE (f) == FIELD_DECL)
1751             {
1752               tree last = try_instantiate_multiple_fields (elt, f);
1753
1754               if (last != f)
1755                 {
1756                   f = last;
1757                   continue;
1758                 }
1759
1760               instantiate_missing_elements_1 (elt, f,
1761                                               canon_type_for_field
1762                                               (f, elt->element));
1763             }
1764         break;
1765       }
1766
1767     case ARRAY_TYPE:
1768       {
1769         tree i, max, subtype;
1770
1771         i = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1772         max = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1773         subtype = TREE_TYPE (type);
1774
1775         while (1)
1776           {
1777             instantiate_missing_elements_1 (elt, i, subtype);
1778             if (tree_int_cst_equal (i, max))
1779               break;
1780             i = int_const_binop (PLUS_EXPR, i, integer_one_node, true);
1781           }
1782
1783         break;
1784       }
1785
1786     case COMPLEX_TYPE:
1787       type = TREE_TYPE (type);
1788       instantiate_missing_elements_1 (elt, integer_zero_node, type);
1789       instantiate_missing_elements_1 (elt, integer_one_node, type);
1790       break;
1791
1792     default:
1793       gcc_unreachable ();
1794     }
1795 }
1796
1797 /* Return true if there is only one non aggregate field in the record, TYPE.
1798    Return false otherwise.  */
1799
1800 static bool
1801 single_scalar_field_in_record_p (tree type)
1802 {
1803    int num_fields = 0;
1804    tree field;
1805    if (TREE_CODE (type) != RECORD_TYPE)
1806      return false;
1807
1808    for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1809      if (TREE_CODE (field) == FIELD_DECL)
1810        {
1811          num_fields++;
1812
1813          if (num_fields == 2)
1814            return false;
1815          
1816          if (AGGREGATE_TYPE_P (TREE_TYPE (field)))
1817            return false;
1818        }
1819
1820    return true;
1821 }
1822
1823 /* Make one pass across an element tree deciding whether to perform block
1824    or element copies.  If we decide on element copies, instantiate all
1825    elements.  Return true if there are any instantiated sub-elements.  */
1826
1827 static bool
1828 decide_block_copy (struct sra_elt *elt)
1829 {
1830   struct sra_elt *c;
1831   bool any_inst;
1832
1833   /* We shouldn't be invoked on groups of sub-elements as they must
1834      behave like their parent as far as block copy is concerned.  */
1835   gcc_assert (!elt->is_group);
1836
1837   /* If scalarization is disabled, respect it.  */
1838   if (elt->cannot_scalarize)
1839     {
1840       elt->use_block_copy = 1;
1841
1842       if (dump_file)
1843         {
1844           fputs ("Scalarization disabled for ", dump_file);
1845           dump_sra_elt_name (dump_file, elt);
1846           fputc ('\n', dump_file);
1847         }
1848
1849       /* Disable scalarization of sub-elements */
1850       for (c = elt->children; c; c = c->sibling)
1851         {
1852           c->cannot_scalarize = 1;
1853           decide_block_copy (c);
1854         }
1855
1856       /* Groups behave like their parent.  */
1857       for (c = elt->groups; c; c = c->sibling)
1858         {
1859           c->cannot_scalarize = 1;
1860           c->use_block_copy = 1;
1861         }
1862
1863       return false;
1864     }
1865
1866   /* Don't decide if we've no uses and no groups.  */
1867   if (elt->n_uses == 0 && elt->n_copies == 0 && elt->groups == NULL)
1868     ;
1869
1870   else if (!elt->is_scalar)
1871     {
1872       tree size_tree = TYPE_SIZE_UNIT (elt->type);
1873       bool use_block_copy = true;
1874
1875       /* Tradeoffs for COMPLEX types pretty much always make it better
1876          to go ahead and split the components.  */
1877       if (TREE_CODE (elt->type) == COMPLEX_TYPE)
1878         use_block_copy = false;
1879
1880       /* Don't bother trying to figure out the rest if the structure is
1881          so large we can't do easy arithmetic.  This also forces block
1882          copies for variable sized structures.  */
1883       else if (host_integerp (size_tree, 1))
1884         {
1885           unsigned HOST_WIDE_INT full_size, inst_size = 0;
1886           unsigned int max_size, max_count, inst_count, full_count;
1887
1888           /* If the sra-max-structure-size parameter is 0, then the
1889              user has not overridden the parameter and we can choose a
1890              sensible default.  */
1891           max_size = SRA_MAX_STRUCTURE_SIZE
1892             ? SRA_MAX_STRUCTURE_SIZE
1893             : MOVE_RATIO (optimize_function_for_speed_p (cfun)) * UNITS_PER_WORD;
1894           max_count = SRA_MAX_STRUCTURE_COUNT
1895             ? SRA_MAX_STRUCTURE_COUNT
1896             : MOVE_RATIO (optimize_function_for_speed_p (cfun));
1897
1898           full_size = tree_low_cst (size_tree, 1);
1899           full_count = count_type_elements (elt->type, false);
1900           inst_count = sum_instantiated_sizes (elt, &inst_size);
1901
1902           /* If there is only one scalar field in the record, don't block copy.  */
1903           if (single_scalar_field_in_record_p (elt->type))
1904             use_block_copy = false;
1905
1906           /* ??? What to do here.  If there are two fields, and we've only
1907              instantiated one, then instantiating the other is clearly a win.
1908              If there are a large number of fields then the size of the copy
1909              is much more of a factor.  */
1910
1911           /* If the structure is small, and we've made copies, go ahead
1912              and instantiate, hoping that the copies will go away.  */
1913           if (full_size <= max_size
1914               && (full_count - inst_count) <= max_count
1915               && elt->n_copies > elt->n_uses)
1916             use_block_copy = false;
1917           else if (inst_count * 100 >= full_count * SRA_FIELD_STRUCTURE_RATIO
1918                    && inst_size * 100 >= full_size * SRA_FIELD_STRUCTURE_RATIO)
1919             use_block_copy = false;
1920
1921           /* In order to avoid block copy, we have to be able to instantiate
1922              all elements of the type.  See if this is possible.  */
1923           if (!use_block_copy
1924               && (!can_completely_scalarize_p (elt)
1925                   || !type_can_instantiate_all_elements (elt->type)))
1926             use_block_copy = true;
1927         }
1928
1929       elt->use_block_copy = use_block_copy;
1930
1931       /* Groups behave like their parent.  */
1932       for (c = elt->groups; c; c = c->sibling)
1933         c->use_block_copy = use_block_copy;
1934
1935       if (dump_file)
1936         {
1937           fprintf (dump_file, "Using %s for ",
1938                    use_block_copy ? "block-copy" : "element-copy");
1939           dump_sra_elt_name (dump_file, elt);
1940           fputc ('\n', dump_file);
1941         }
1942
1943       if (!use_block_copy)
1944         {
1945           instantiate_missing_elements (elt);
1946           return true;
1947         }
1948     }
1949
1950   any_inst = elt->replacement != NULL;
1951
1952   for (c = elt->children; c ; c = c->sibling)
1953     any_inst |= decide_block_copy (c);
1954
1955   return any_inst;
1956 }
1957
1958 /* Entry point to phase 3.  Instantiate scalar replacement variables.  */
1959
1960 static void
1961 decide_instantiations (void)
1962 {
1963   unsigned int i;
1964   bool cleared_any;
1965   bitmap_head done_head;
1966   bitmap_iterator bi;
1967
1968   /* We cannot clear bits from a bitmap we're iterating over,
1969      so save up all the bits to clear until the end.  */
1970   bitmap_initialize (&done_head, &bitmap_default_obstack);
1971   cleared_any = false;
1972
1973   EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1974     {
1975       tree var = referenced_var (i);
1976       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1977       if (elt)
1978         {
1979           decide_instantiation_1 (elt, 0, 0);
1980           if (!decide_block_copy (elt))
1981             elt = NULL;
1982         }
1983       if (!elt)
1984         {
1985           bitmap_set_bit (&done_head, i);
1986           cleared_any = true;
1987         }
1988     }
1989
1990   if (cleared_any)
1991     {
1992       bitmap_and_compl_into (sra_candidates, &done_head);
1993       bitmap_and_compl_into (needs_copy_in, &done_head);
1994     }
1995   bitmap_clear (&done_head);
1996   
1997   mark_set_for_renaming (sra_candidates);
1998
1999   if (dump_file)
2000     fputc ('\n', dump_file);
2001 }
2002
2003 \f
2004 /* Phase Four: Update the function to match the replacements created.  */
2005
2006 /* Mark all the variables in virtual operands in all the statements in
2007    LIST for renaming.  */
2008
2009 static void
2010 mark_all_v_defs_seq (gimple_seq seq)
2011 {
2012   gimple_stmt_iterator gsi;
2013
2014   for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
2015     update_stmt_if_modified (gsi_stmt (gsi));
2016 }
2017
2018 /* Mark every replacement under ELT with TREE_NO_WARNING.  */
2019
2020 static void
2021 mark_no_warning (struct sra_elt *elt)
2022 {
2023   if (!elt->all_no_warning)
2024     {
2025       if (elt->replacement)
2026         TREE_NO_WARNING (elt->replacement) = 1;
2027       else
2028         {
2029           struct sra_elt *c;
2030           FOR_EACH_ACTUAL_CHILD (c, elt)
2031             mark_no_warning (c);
2032         }
2033       elt->all_no_warning = true;
2034     }
2035 }
2036
2037 /* Build a single level component reference to ELT rooted at BASE.  */
2038
2039 static tree
2040 generate_one_element_ref (struct sra_elt *elt, tree base)
2041 {
2042   switch (TREE_CODE (TREE_TYPE (base)))
2043     {
2044     case RECORD_TYPE:
2045       {
2046         tree field = elt->element;
2047
2048         /* We can't test elt->in_bitfld_block here because, when this is
2049            called from instantiate_element, we haven't set this field
2050            yet.  */
2051         if (TREE_CODE (field) == BIT_FIELD_REF)
2052           {
2053             tree ret = unshare_expr (field);
2054             TREE_OPERAND (ret, 0) = base;
2055             return ret;
2056           }
2057
2058         /* Watch out for compatible records with differing field lists.  */
2059         if (DECL_FIELD_CONTEXT (field) != TYPE_MAIN_VARIANT (TREE_TYPE (base)))
2060           field = find_compatible_field (TREE_TYPE (base), field);
2061
2062         return build3 (COMPONENT_REF, elt->type, base, field, NULL);
2063       }
2064
2065     case ARRAY_TYPE:
2066       if (TREE_CODE (elt->element) == RANGE_EXPR)
2067         return build4 (ARRAY_RANGE_REF, elt->type, base,
2068                        TREE_OPERAND (elt->element, 0), NULL, NULL);
2069       else
2070         return build4 (ARRAY_REF, elt->type, base, elt->element, NULL, NULL);
2071
2072     case COMPLEX_TYPE:
2073       if (elt->element == integer_zero_node)
2074         return build1 (REALPART_EXPR, elt->type, base);
2075       else
2076         return build1 (IMAGPART_EXPR, elt->type, base);
2077
2078     default:
2079       gcc_unreachable ();
2080     }
2081 }
2082
2083 /* Build a full component reference to ELT rooted at its native variable.  */
2084
2085 static tree
2086 generate_element_ref (struct sra_elt *elt)
2087 {
2088   if (elt->parent)
2089     return generate_one_element_ref (elt, generate_element_ref (elt->parent));
2090   else
2091     return elt->element;
2092 }
2093
2094 /* Return true if BF is a bit-field that we can handle like a scalar.  */
2095
2096 static bool
2097 scalar_bitfield_p (tree bf)
2098 {
2099   return (TREE_CODE (bf) == BIT_FIELD_REF
2100           && (is_gimple_reg (TREE_OPERAND (bf, 0))
2101               || (TYPE_MODE (TREE_TYPE (TREE_OPERAND (bf, 0))) != BLKmode
2102                   && (!TREE_SIDE_EFFECTS (TREE_OPERAND (bf, 0))
2103                       || (GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE
2104                                                        (TREE_OPERAND (bf, 0))))
2105                           <= BITS_PER_WORD)))));
2106 }
2107
2108 /* Create an assignment statement from SRC to DST.  */
2109
2110 static gimple_seq
2111 sra_build_assignment (tree dst, tree src)
2112 {
2113   gimple stmt;
2114   gimple_seq seq = NULL, seq2 = NULL;
2115   /* Turning BIT_FIELD_REFs into bit operations enables other passes
2116      to do a much better job at optimizing the code.
2117      From dst = BIT_FIELD_REF <var, sz, off> we produce
2118
2119         SR.1 = (scalar type) var;
2120         SR.2 = SR.1 >> off;
2121         SR.3 = SR.2 & ((1 << sz) - 1);
2122         ... possible sign extension of SR.3 ...
2123         dst = (destination type) SR.3;
2124    */
2125   if (scalar_bitfield_p (src))
2126     {
2127       tree var, shift, width;
2128       tree utype, stype;
2129       bool unsignedp = (INTEGRAL_TYPE_P (TREE_TYPE (src))
2130                         ? TYPE_UNSIGNED (TREE_TYPE (src)) : true);
2131       struct gimplify_ctx gctx;
2132
2133       var = TREE_OPERAND (src, 0);
2134       width = TREE_OPERAND (src, 1);
2135       /* The offset needs to be adjusted to a right shift quantity
2136          depending on the endianness.  */
2137       if (BYTES_BIG_ENDIAN)
2138         {
2139           tree tmp = size_binop (PLUS_EXPR, width, TREE_OPERAND (src, 2));
2140           shift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), tmp);
2141         }
2142       else
2143         shift = TREE_OPERAND (src, 2);
2144
2145       /* In weird cases we have non-integral types for the source or
2146          destination object.
2147          ???  For unknown reasons we also want an unsigned scalar type.  */
2148       stype = TREE_TYPE (var);
2149       if (!INTEGRAL_TYPE_P (stype))
2150         stype = lang_hooks.types.type_for_size (TREE_INT_CST_LOW
2151                                                 (TYPE_SIZE (stype)), 1);
2152       else if (!TYPE_UNSIGNED (stype))
2153         stype = unsigned_type_for (stype);
2154
2155       utype = TREE_TYPE (dst);
2156       if (!INTEGRAL_TYPE_P (utype))
2157         utype = lang_hooks.types.type_for_size (TREE_INT_CST_LOW
2158                                                 (TYPE_SIZE (utype)), 1);
2159       else if (!TYPE_UNSIGNED (utype))
2160         utype = unsigned_type_for (utype);
2161
2162       /* Convert the base var of the BIT_FIELD_REF to the scalar type
2163          we use for computation if we cannot use it directly.  */
2164       if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
2165         var = fold_convert (stype, var);
2166       else
2167         var = fold_build1 (VIEW_CONVERT_EXPR, stype, var);
2168
2169       if (!integer_zerop (shift))
2170         var = fold_build2 (RSHIFT_EXPR, stype, var, shift);
2171
2172       /* If we need a masking operation, produce one.  */
2173       if (TREE_INT_CST_LOW (width) == TYPE_PRECISION (stype))
2174         unsignedp = true;
2175       else
2176         {
2177           tree one = build_int_cst_wide (stype, 1, 0);
2178           tree mask = int_const_binop (LSHIFT_EXPR, one, width, 0);
2179           mask = int_const_binop (MINUS_EXPR, mask, one, 0);
2180           var = fold_build2 (BIT_AND_EXPR, stype, var, mask);
2181         }
2182
2183       /* After shifting and masking, convert to the target type.  */
2184       var = fold_convert (utype, var);
2185
2186       /* Perform sign extension, if required.
2187          ???  This should never be necessary.  */
2188       if (!unsignedp)
2189         {
2190           tree signbit = int_const_binop (LSHIFT_EXPR,
2191                                           build_int_cst_wide (utype, 1, 0),
2192                                           size_binop (MINUS_EXPR, width,
2193                                                       bitsize_int (1)), 0);
2194
2195           var = fold_build2 (BIT_XOR_EXPR, utype, var, signbit);
2196           var = fold_build2 (MINUS_EXPR, utype, var, signbit);
2197         }
2198
2199       /* fold_build3 (BIT_FIELD_REF, ...) sometimes returns a cast.  */
2200       STRIP_NOPS (dst);
2201
2202       /* Finally, move and convert to the destination.  */
2203       if (INTEGRAL_TYPE_P (TREE_TYPE (dst)))
2204         var = fold_convert (TREE_TYPE (dst), var);
2205       else
2206         var = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (dst), var);
2207
2208       push_gimplify_context (&gctx);
2209       gctx.into_ssa = true;
2210       gctx.allow_rhs_cond_expr = true;
2211
2212       gimplify_assign (dst, var, &seq);
2213
2214       if (gimple_referenced_vars (cfun))
2215         for (var = gctx.temps; var; var = TREE_CHAIN (var))
2216           add_referenced_var (var);
2217       pop_gimplify_context (NULL);
2218
2219       return seq;
2220     }
2221
2222   /* fold_build3 (BIT_FIELD_REF, ...) sometimes returns a cast.  */
2223   if (CONVERT_EXPR_P (dst))
2224     {
2225       STRIP_NOPS (dst);
2226       src = fold_convert (TREE_TYPE (dst), src);
2227     }
2228   /* It was hoped that we could perform some type sanity checking
2229      here, but since front-ends can emit accesses of fields in types
2230      different from their nominal types and copy structures containing
2231      them as a whole, we'd have to handle such differences here.
2232      Since such accesses under different types require compatibility
2233      anyway, there's little point in making tests and/or adding
2234      conversions to ensure the types of src and dst are the same.
2235      So we just assume type differences at this point are ok.
2236      The only exception we make here are pointer types, which can be different
2237      in e.g. structurally equal, but non-identical RECORD_TYPEs.  */
2238   else if (POINTER_TYPE_P (TREE_TYPE (dst))
2239            && !useless_type_conversion_p (TREE_TYPE (dst), TREE_TYPE (src)))
2240     src = fold_convert (TREE_TYPE (dst), src);
2241
2242   /* ???  Only call the gimplifier if we need to.  Otherwise we may 
2243      end up substituting with DECL_VALUE_EXPR - see PR37380.  */
2244   if (!handled_component_p (src)
2245       && !SSA_VAR_P (src))
2246     {
2247       src = force_gimple_operand (src, &seq2, false, NULL_TREE);
2248       gimple_seq_add_seq (&seq, seq2);
2249     }
2250   stmt = gimple_build_assign (dst, src);
2251   gimple_seq_add_stmt (&seq, stmt);
2252   return seq;
2253 }
2254
2255 /* BIT_FIELD_REFs must not be shared.  sra_build_elt_assignment()
2256    takes care of assignments, but we must create copies for uses.  */
2257 #define REPLDUP(t) (TREE_CODE (t) != BIT_FIELD_REF ? (t) : unshare_expr (t))
2258
2259 /* Emit an assignment from SRC to DST, but if DST is a scalarizable
2260    BIT_FIELD_REF, turn it into bit operations.  */
2261
2262 static gimple_seq
2263 sra_build_bf_assignment (tree dst, tree src)
2264 {
2265   tree var, type, utype, tmp, tmp2, tmp3;
2266   gimple_seq seq;
2267   gimple stmt;
2268   tree cst, cst2, mask;
2269   tree minshift, maxshift;
2270
2271   if (TREE_CODE (dst) != BIT_FIELD_REF)
2272     return sra_build_assignment (dst, src);
2273
2274   var = TREE_OPERAND (dst, 0);
2275
2276   if (!scalar_bitfield_p (dst))
2277     return sra_build_assignment (REPLDUP (dst), src);
2278
2279   seq = NULL;
2280
2281   cst = fold_convert (bitsizetype, TREE_OPERAND (dst, 2));
2282   cst2 = size_binop (PLUS_EXPR,
2283                      fold_convert (bitsizetype, TREE_OPERAND (dst, 1)),
2284                      cst);
2285
2286   if (BYTES_BIG_ENDIAN)
2287     {
2288       maxshift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), cst);
2289       minshift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), cst2);
2290     }
2291   else
2292     {
2293       maxshift = cst2;
2294       minshift = cst;
2295     }
2296
2297   type = TREE_TYPE (var);
2298   if (!INTEGRAL_TYPE_P (type))
2299     type = lang_hooks.types.type_for_size
2300       (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (var))), 1);
2301   if (TYPE_UNSIGNED (type))
2302     utype = type;
2303   else
2304     utype = unsigned_type_for (type);
2305
2306   mask = build_int_cst_wide (utype, 1, 0);
2307   if (TREE_INT_CST_LOW (maxshift) == TYPE_PRECISION (utype))
2308     cst = build_int_cst_wide (utype, 0, 0);
2309   else
2310     cst = int_const_binop (LSHIFT_EXPR, mask, maxshift, true);
2311   if (integer_zerop (minshift))
2312     cst2 = mask;
2313   else
2314     cst2 = int_const_binop (LSHIFT_EXPR, mask, minshift, true);
2315   mask = int_const_binop (MINUS_EXPR, cst, cst2, true);
2316   mask = fold_build1 (BIT_NOT_EXPR, utype, mask);
2317
2318   if (TYPE_MAIN_VARIANT (utype) != TYPE_MAIN_VARIANT (TREE_TYPE (var))
2319       && !integer_zerop (mask))
2320     {
2321       tmp = var;
2322       if (!is_gimple_variable (tmp))
2323         tmp = unshare_expr (var);
2324       else
2325         TREE_NO_WARNING (var) = true;
2326
2327       tmp2 = make_rename_temp (utype, "SR");
2328
2329       if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
2330         tmp = fold_convert (utype, tmp);
2331       else
2332         tmp = fold_build1 (VIEW_CONVERT_EXPR, utype, tmp);
2333
2334       stmt = gimple_build_assign (tmp2, tmp);
2335       gimple_seq_add_stmt (&seq, stmt);
2336     }
2337   else
2338     tmp2 = var;
2339
2340   if (!integer_zerop (mask))
2341     {
2342       tmp = make_rename_temp (utype, "SR");
2343       stmt = gimple_build_assign (tmp, fold_build2 (BIT_AND_EXPR, utype,
2344                                                     tmp2, mask));
2345       gimple_seq_add_stmt (&seq, stmt);
2346     }
2347   else
2348     tmp = mask;
2349
2350   if (is_gimple_reg (src) && INTEGRAL_TYPE_P (TREE_TYPE (src)))
2351     tmp2 = src;
2352   else if (INTEGRAL_TYPE_P (TREE_TYPE (src)))
2353     {
2354       gimple_seq tmp_seq;
2355       tmp2 = make_rename_temp (TREE_TYPE (src), "SR");
2356       tmp_seq = sra_build_assignment (tmp2, src);
2357       gimple_seq_add_seq (&seq, tmp_seq);
2358     }
2359   else
2360     {
2361       gimple_seq tmp_seq;
2362       tmp2 = make_rename_temp
2363         (lang_hooks.types.type_for_size
2364          (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (src))),
2365           1), "SR");
2366       tmp_seq = sra_build_assignment (tmp2, fold_build1 (VIEW_CONVERT_EXPR,
2367                                                       TREE_TYPE (tmp2), src));
2368       gimple_seq_add_seq (&seq, tmp_seq);
2369     }
2370
2371   if (!TYPE_UNSIGNED (TREE_TYPE (tmp2)))
2372     {
2373       gimple_seq tmp_seq;
2374       tree ut = unsigned_type_for (TREE_TYPE (tmp2));
2375       tmp3 = make_rename_temp (ut, "SR");
2376       tmp2 = fold_convert (ut, tmp2);
2377       tmp_seq = sra_build_assignment (tmp3, tmp2);
2378       gimple_seq_add_seq (&seq, tmp_seq);
2379
2380       tmp2 = fold_build1 (BIT_NOT_EXPR, utype, mask);
2381       tmp2 = int_const_binop (RSHIFT_EXPR, tmp2, minshift, true);
2382       tmp2 = fold_convert (ut, tmp2);
2383       tmp2 = fold_build2 (BIT_AND_EXPR, ut, tmp3, tmp2);
2384
2385       if (tmp3 != tmp2)
2386         {
2387           tmp3 = make_rename_temp (ut, "SR");
2388           tmp_seq = sra_build_assignment (tmp3, tmp2);
2389           gimple_seq_add_seq (&seq, tmp_seq);
2390         }
2391
2392       tmp2 = tmp3;
2393     }
2394
2395   if (TYPE_MAIN_VARIANT (TREE_TYPE (tmp2)) != TYPE_MAIN_VARIANT (utype))
2396     {
2397       gimple_seq tmp_seq;
2398       tmp3 = make_rename_temp (utype, "SR");
2399       tmp2 = fold_convert (utype, tmp2);
2400       tmp_seq = sra_build_assignment (tmp3, tmp2);
2401       gimple_seq_add_seq (&seq, tmp_seq);
2402       tmp2 = tmp3;
2403     }
2404
2405   if (!integer_zerop (minshift))
2406     {
2407       tmp3 = make_rename_temp (utype, "SR");
2408       stmt = gimple_build_assign (tmp3, fold_build2 (LSHIFT_EXPR, utype,
2409                                                      tmp2, minshift));
2410       gimple_seq_add_stmt (&seq, stmt);
2411       tmp2 = tmp3;
2412     }
2413
2414   if (utype != TREE_TYPE (var))
2415     tmp3 = make_rename_temp (utype, "SR");
2416   else
2417     tmp3 = var;
2418   stmt = gimple_build_assign (tmp3, fold_build2 (BIT_IOR_EXPR, utype,
2419                                                  tmp, tmp2));
2420       gimple_seq_add_stmt (&seq, stmt);
2421
2422   if (tmp3 != var)
2423     {
2424       if (TREE_TYPE (var) == type)
2425         stmt = gimple_build_assign (var, fold_convert (type, tmp3));
2426       else
2427         stmt = gimple_build_assign (var, fold_build1 (VIEW_CONVERT_EXPR,
2428                                                       TREE_TYPE (var), tmp3));
2429       gimple_seq_add_stmt (&seq, stmt);
2430     }
2431
2432   return seq;
2433 }
2434
2435 /* Expand an assignment of SRC to the scalarized representation of
2436    ELT.  If it is a field group, try to widen the assignment to cover
2437    the full variable.  */
2438
2439 static gimple_seq
2440 sra_build_elt_assignment (struct sra_elt *elt, tree src)
2441 {
2442   tree dst = elt->replacement;
2443   tree var, tmp, cst, cst2;
2444   gimple stmt;
2445   gimple_seq seq;
2446
2447   if (TREE_CODE (dst) != BIT_FIELD_REF
2448       || !elt->in_bitfld_block)
2449     return sra_build_assignment (REPLDUP (dst), src);
2450
2451   var = TREE_OPERAND (dst, 0);
2452
2453   /* Try to widen the assignment to the entire variable.
2454      We need the source to be a BIT_FIELD_REF as well, such that, for
2455      BIT_FIELD_REF<d,sz,dp> = BIT_FIELD_REF<s,sz,sp>,
2456      by design, conditions are met such that we can turn it into
2457      d = BIT_FIELD_REF<s,dw,sp-dp>.  */
2458   if (elt->in_bitfld_block == 2
2459       && TREE_CODE (src) == BIT_FIELD_REF)
2460     {
2461       tmp = src;
2462       cst = TYPE_SIZE (TREE_TYPE (var));
2463       cst2 = size_binop (MINUS_EXPR, TREE_OPERAND (src, 2),
2464                          TREE_OPERAND (dst, 2));
2465
2466       src = TREE_OPERAND (src, 0);
2467
2468       /* Avoid full-width bit-fields.  */
2469       if (integer_zerop (cst2)
2470           && tree_int_cst_equal (cst, TYPE_SIZE (TREE_TYPE (src))))
2471         {
2472           if (INTEGRAL_TYPE_P (TREE_TYPE (src))
2473               && !TYPE_UNSIGNED (TREE_TYPE (src)))
2474             src = fold_convert (unsigned_type_for (TREE_TYPE (src)), src);
2475
2476           /* If a single conversion won't do, we'll need a statement
2477              list.  */
2478           if (TYPE_MAIN_VARIANT (TREE_TYPE (var))
2479               != TYPE_MAIN_VARIANT (TREE_TYPE (src)))
2480             {
2481               gimple_seq tmp_seq;
2482               seq = NULL;
2483
2484               if (!INTEGRAL_TYPE_P (TREE_TYPE (src)))
2485                 src = fold_build1 (VIEW_CONVERT_EXPR,
2486                                    lang_hooks.types.type_for_size
2487                                    (TREE_INT_CST_LOW
2488                                     (TYPE_SIZE (TREE_TYPE (src))),
2489                                     1), src);
2490               gcc_assert (TYPE_UNSIGNED (TREE_TYPE (src)));
2491
2492               tmp = make_rename_temp (TREE_TYPE (src), "SR");
2493               stmt = gimple_build_assign (tmp, src);
2494               gimple_seq_add_stmt (&seq, stmt);
2495
2496               tmp_seq = sra_build_assignment (var,
2497                                               fold_convert (TREE_TYPE (var),
2498                                                             tmp));
2499               gimple_seq_add_seq (&seq, tmp_seq);
2500
2501               return seq;
2502             }
2503
2504           src = fold_convert (TREE_TYPE (var), src);
2505         }
2506       else
2507         {
2508           src = fold_convert (TREE_TYPE (var), tmp);
2509         }
2510
2511       return sra_build_assignment (var, src);
2512     }
2513
2514   return sra_build_bf_assignment (dst, src);
2515 }
2516
2517 /* Generate a set of assignment statements in *LIST_P to copy all
2518    instantiated elements under ELT to or from the equivalent structure
2519    rooted at EXPR.  COPY_OUT controls the direction of the copy, with
2520    true meaning to copy out of EXPR into ELT.  */
2521
2522 static void
2523 generate_copy_inout (struct sra_elt *elt, bool copy_out, tree expr,
2524                      gimple_seq *seq_p)
2525 {
2526   struct sra_elt *c;
2527   gimple_seq tmp_seq;
2528   tree t;
2529
2530   if (!copy_out && TREE_CODE (expr) == SSA_NAME
2531       && TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
2532     {
2533       tree r, i;
2534
2535       c = lookup_element (elt, integer_zero_node, NULL, NO_INSERT);
2536       r = c->replacement;
2537       c = lookup_element (elt, integer_one_node, NULL, NO_INSERT);
2538       i = c->replacement;
2539
2540       t = build2 (COMPLEX_EXPR, elt->type, r, i);
2541       tmp_seq = sra_build_bf_assignment (expr, t);
2542       SSA_NAME_DEF_STMT (expr) = gimple_seq_last_stmt (tmp_seq);
2543       gimple_seq_add_seq (seq_p, tmp_seq);
2544     }
2545   else if (elt->replacement)
2546     {
2547       if (copy_out)
2548         tmp_seq = sra_build_elt_assignment (elt, expr);
2549       else
2550         tmp_seq = sra_build_bf_assignment (expr, REPLDUP (elt->replacement));
2551       gimple_seq_add_seq (seq_p, tmp_seq);
2552     }
2553   else
2554     {
2555       FOR_EACH_ACTUAL_CHILD (c, elt)
2556         {
2557           t = generate_one_element_ref (c, unshare_expr (expr));
2558           generate_copy_inout (c, copy_out, t, seq_p);
2559         }
2560     }
2561 }
2562
2563 /* Generate a set of assignment statements in *LIST_P to copy all instantiated
2564    elements under SRC to their counterparts under DST.  There must be a 1-1
2565    correspondence of instantiated elements.  */
2566
2567 static void
2568 generate_element_copy (struct sra_elt *dst, struct sra_elt *src, gimple_seq *seq_p)
2569 {
2570   struct sra_elt *dc, *sc;
2571
2572   FOR_EACH_ACTUAL_CHILD (dc, dst)
2573     {
2574       sc = lookup_element (src, dc->element, NULL, NO_INSERT);
2575       if (!sc && dc->in_bitfld_block == 2)
2576         {
2577           struct sra_elt *dcs;
2578
2579           FOR_EACH_ACTUAL_CHILD (dcs, dc)
2580             {
2581               sc = lookup_element (src, dcs->element, NULL, NO_INSERT);
2582               gcc_assert (sc);
2583               generate_element_copy (dcs, sc, seq_p);
2584             }
2585
2586           continue;
2587         }
2588
2589       /* If DST and SRC are structs with the same elements, but do not have
2590          the same TYPE_MAIN_VARIANT, then lookup of DST FIELD_DECL in SRC
2591          will fail.  Try harder by finding the corresponding FIELD_DECL
2592          in SRC.  */
2593       if (!sc)
2594         {
2595           tree f;
2596
2597           gcc_assert (useless_type_conversion_p (dst->type, src->type));
2598           gcc_assert (TREE_CODE (dc->element) == FIELD_DECL);
2599           for (f = TYPE_FIELDS (src->type); f ; f = TREE_CHAIN (f))
2600             if (simple_cst_equal (DECL_FIELD_OFFSET (f),
2601                                   DECL_FIELD_OFFSET (dc->element)) > 0
2602                 && simple_cst_equal (DECL_FIELD_BIT_OFFSET (f),
2603                                      DECL_FIELD_BIT_OFFSET (dc->element)) > 0
2604                 && simple_cst_equal (DECL_SIZE (f),
2605                                      DECL_SIZE (dc->element)) > 0
2606                 && (useless_type_conversion_p (TREE_TYPE (dc->element),
2607                                                TREE_TYPE (f))
2608                     || (POINTER_TYPE_P (TREE_TYPE (dc->element))
2609                         && POINTER_TYPE_P (TREE_TYPE (f)))))
2610               break;
2611           gcc_assert (f != NULL_TREE);
2612           sc = lookup_element (src, f, NULL, NO_INSERT);
2613         }
2614
2615       generate_element_copy (dc, sc, seq_p);
2616     }
2617
2618   if (dst->replacement)
2619     {
2620       gimple_seq tmp_seq;
2621
2622       gcc_assert (src->replacement);
2623
2624       tmp_seq = sra_build_elt_assignment (dst, REPLDUP (src->replacement));
2625       gimple_seq_add_seq (seq_p, tmp_seq);
2626     }
2627 }
2628
2629 /* Generate a set of assignment statements in *LIST_P to zero all instantiated
2630    elements under ELT.  In addition, do not assign to elements that have been
2631    marked VISITED but do reset the visited flag; this allows easy coordination
2632    with generate_element_init.  */
2633
2634 static void
2635 generate_element_zero (struct sra_elt *elt, gimple_seq *seq_p)
2636 {
2637   struct sra_elt *c;
2638
2639   if (elt->visited)
2640     {
2641       elt->visited = false;
2642       return;
2643     }
2644
2645   if (!elt->in_bitfld_block)
2646     FOR_EACH_ACTUAL_CHILD (c, elt)
2647       generate_element_zero (c, seq_p);
2648
2649   if (elt->replacement)
2650     {
2651       tree t;
2652       gimple_seq tmp_seq;
2653
2654       gcc_assert (elt->is_scalar);
2655       t = fold_convert (elt->type, integer_zero_node);
2656
2657       tmp_seq = sra_build_elt_assignment (elt, t);
2658       gimple_seq_add_seq (seq_p, tmp_seq);
2659     }
2660 }
2661
2662 /* Generate an assignment VAR = INIT, where INIT may need gimplification.
2663    Add the result to *LIST_P.  */
2664
2665 static void
2666 generate_one_element_init (struct sra_elt *elt, tree init, gimple_seq *seq_p)
2667 {
2668   gimple_seq tmp_seq = sra_build_elt_assignment (elt, init);
2669   gimple_seq_add_seq (seq_p, tmp_seq);
2670 }
2671
2672 /* Generate a set of assignment statements in *LIST_P to set all instantiated
2673    elements under ELT with the contents of the initializer INIT.  In addition,
2674    mark all assigned elements VISITED; this allows easy coordination with
2675    generate_element_zero.  Return false if we found a case we couldn't
2676    handle.  */
2677
2678 static bool
2679 generate_element_init_1 (struct sra_elt *elt, tree init, gimple_seq *seq_p)
2680 {
2681   bool result = true;
2682   enum tree_code init_code;
2683   struct sra_elt *sub;
2684   tree t;
2685   unsigned HOST_WIDE_INT idx;
2686   tree value, purpose;
2687
2688   /* We can be passed DECL_INITIAL of a static variable.  It might have a
2689      conversion, which we strip off here.  */
2690   STRIP_USELESS_TYPE_CONVERSION (init);
2691   init_code = TREE_CODE (init);
2692
2693   if (elt->is_scalar)
2694     {
2695       if (elt->replacement)
2696         {
2697           generate_one_element_init (elt, init, seq_p);
2698           elt->visited = true;
2699         }
2700       return result;
2701     }
2702
2703   switch (init_code)
2704     {
2705     case COMPLEX_CST:
2706     case COMPLEX_EXPR:
2707       FOR_EACH_ACTUAL_CHILD (sub, elt)
2708         {
2709           if (sub->element == integer_zero_node)
2710             t = (init_code == COMPLEX_EXPR
2711                  ? TREE_OPERAND (init, 0) : TREE_REALPART (init));
2712           else
2713             t = (init_code == COMPLEX_EXPR
2714                  ? TREE_OPERAND (init, 1) : TREE_IMAGPART (init));
2715           result &= generate_element_init_1 (sub, t, seq_p);
2716         }
2717       break;
2718
2719     case CONSTRUCTOR:
2720       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, purpose, value)
2721         {
2722           /* Array constructors are routinely created with NULL indices.  */
2723           if (purpose == NULL_TREE)
2724             {
2725               result = false;
2726               break;
2727             }
2728           if (TREE_CODE (purpose) == RANGE_EXPR)
2729             {
2730               tree lower = TREE_OPERAND (purpose, 0);
2731               tree upper = TREE_OPERAND (purpose, 1);
2732
2733               while (1)
2734                 {
2735                   sub = lookup_element (elt, lower, NULL, NO_INSERT);
2736                   if (sub != NULL)
2737                     result &= generate_element_init_1 (sub, value, seq_p);
2738                   if (tree_int_cst_equal (lower, upper))
2739                     break;
2740                   lower = int_const_binop (PLUS_EXPR, lower,
2741                                            integer_one_node, true);
2742                 }
2743             }
2744           else
2745             {
2746               sub = lookup_element (elt, purpose, NULL, NO_INSERT);
2747               if (sub != NULL)
2748                 result &= generate_element_init_1 (sub, value, seq_p);
2749             }
2750         }
2751       break;
2752
2753     default:
2754       elt->visited = true;
2755       result = false;
2756     }
2757
2758   return result;
2759 }
2760
2761 /* A wrapper function for generate_element_init_1 that handles cleanup after
2762    gimplification.  */
2763
2764 static bool
2765 generate_element_init (struct sra_elt *elt, tree init, gimple_seq *seq_p)
2766 {
2767   bool ret;
2768   struct gimplify_ctx gctx;
2769
2770   push_gimplify_context (&gctx);
2771   ret = generate_element_init_1 (elt, init, seq_p);
2772   pop_gimplify_context (NULL);
2773
2774   /* The replacement can expose previously unreferenced variables.  */
2775   if (ret && *seq_p)
2776     {
2777       gimple_stmt_iterator i;
2778
2779       for (i = gsi_start (*seq_p); !gsi_end_p (i); gsi_next (&i))
2780         find_new_referenced_vars (gsi_stmt (i));
2781     }
2782
2783   return ret;
2784 }
2785
2786 /* Insert a gimple_seq SEQ on all the outgoing edges out of BB.  Note that
2787    if BB has more than one edge, STMT will be replicated for each edge.
2788    Also, abnormal edges will be ignored.  */
2789
2790 void
2791 insert_edge_copies_seq (gimple_seq seq, basic_block bb)
2792 {
2793   edge e;
2794   edge_iterator ei;
2795   unsigned n_copies = -1;
2796
2797   FOR_EACH_EDGE (e, ei, bb->succs)
2798     if (!(e->flags & EDGE_ABNORMAL)) 
2799       n_copies++;
2800
2801   FOR_EACH_EDGE (e, ei, bb->succs)
2802     if (!(e->flags & EDGE_ABNORMAL)) 
2803       gsi_insert_seq_on_edge (e, n_copies-- > 0 ? gimple_seq_copy (seq) : seq);
2804 }
2805
2806 /* Helper function to insert LIST before GSI, and set up line number info.  */
2807
2808 void
2809 sra_insert_before (gimple_stmt_iterator *gsi, gimple_seq seq)
2810 {
2811   gimple stmt = gsi_stmt (*gsi);
2812
2813   if (gimple_has_location (stmt))
2814     annotate_all_with_location (seq, gimple_location (stmt));
2815   gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
2816 }
2817
2818 /* Similarly, but insert after GSI.  Handles insertion onto edges as well.  */
2819
2820 void
2821 sra_insert_after (gimple_stmt_iterator *gsi, gimple_seq seq)
2822 {
2823   gimple stmt = gsi_stmt (*gsi);
2824
2825   if (gimple_has_location (stmt))
2826     annotate_all_with_location (seq, gimple_location (stmt));
2827
2828   if (stmt_ends_bb_p (stmt))
2829     insert_edge_copies_seq (seq, gsi_bb (*gsi));
2830   else
2831     gsi_insert_seq_after (gsi, seq, GSI_SAME_STMT);
2832 }
2833
2834 /* Similarly, but replace the statement at GSI.  */
2835
2836 static void
2837 sra_replace (gimple_stmt_iterator *gsi, gimple_seq seq)
2838 {
2839   sra_insert_before (gsi, seq);
2840   unlink_stmt_vdef (gsi_stmt (*gsi));
2841   gsi_remove (gsi, false);
2842   if (gsi_end_p (*gsi))
2843     *gsi = gsi_last (gsi_seq (*gsi));
2844   else
2845     gsi_prev (gsi);
2846 }
2847
2848 /* Data structure that bitfield_overlaps_p fills in with information
2849    about the element passed in and how much of it overlaps with the
2850    bit-range passed it to.  */
2851
2852 struct bitfield_overlap_info
2853 {
2854   /* The bit-length of an element.  */
2855   tree field_len;
2856
2857   /* The bit-position of the element in its parent.  */
2858   tree field_pos;
2859
2860   /* The number of bits of the element that overlap with the incoming
2861      bit range.  */
2862   tree overlap_len;
2863
2864   /* The first bit of the element that overlaps with the incoming bit
2865      range.  */
2866   tree overlap_pos;
2867 };
2868
2869 /* Return true if a BIT_FIELD_REF<(FLD->parent), BLEN, BPOS>
2870    expression (referenced as BF below) accesses any of the bits in FLD,
2871    false if it doesn't.  If DATA is non-null, its field_len and
2872    field_pos are filled in such that BIT_FIELD_REF<(FLD->parent),
2873    field_len, field_pos> (referenced as BFLD below) represents the
2874    entire field FLD->element, and BIT_FIELD_REF<BFLD, overlap_len,
2875    overlap_pos> represents the portion of the entire field that
2876    overlaps with BF.  */
2877
2878 static bool
2879 bitfield_overlaps_p (tree blen, tree bpos, struct sra_elt *fld,
2880                      struct bitfield_overlap_info *data)
2881 {
2882   tree flen, fpos;
2883   bool ret;
2884
2885   if (TREE_CODE (fld->element) == FIELD_DECL)
2886     {
2887       flen = fold_convert (bitsizetype, DECL_SIZE (fld->element));
2888       fpos = fold_convert (bitsizetype, DECL_FIELD_OFFSET (fld->element));
2889       fpos = size_binop (MULT_EXPR, fpos, bitsize_int (BITS_PER_UNIT));
2890       fpos = size_binop (PLUS_EXPR, fpos, DECL_FIELD_BIT_OFFSET (fld->element));
2891     }
2892   else if (TREE_CODE (fld->element) == BIT_FIELD_REF)
2893     {
2894       flen = fold_convert (bitsizetype, TREE_OPERAND (fld->element, 1));
2895       fpos = fold_convert (bitsizetype, TREE_OPERAND (fld->element, 2));
2896     }
2897   else if (TREE_CODE (fld->element) == INTEGER_CST)
2898     {
2899       tree domain_type = TYPE_DOMAIN (TREE_TYPE (fld->parent->element));
2900       flen = fold_convert (bitsizetype, TYPE_SIZE (fld->type));
2901       fpos = fold_convert (bitsizetype, fld->element);
2902       if (domain_type && TYPE_MIN_VALUE (domain_type))
2903         fpos = size_binop (MINUS_EXPR, fpos,
2904                            fold_convert (bitsizetype,
2905                                          TYPE_MIN_VALUE (domain_type)));
2906       fpos = size_binop (MULT_EXPR, flen, fpos);
2907     }
2908   else
2909     gcc_unreachable ();
2910
2911   gcc_assert (host_integerp (blen, 1)
2912               && host_integerp (bpos, 1)
2913               && host_integerp (flen, 1)
2914               && host_integerp (fpos, 1));
2915
2916   ret = ((!tree_int_cst_lt (fpos, bpos)
2917           && tree_int_cst_lt (size_binop (MINUS_EXPR, fpos, bpos),
2918                               blen))
2919          || (!tree_int_cst_lt (bpos, fpos)
2920              && tree_int_cst_lt (size_binop (MINUS_EXPR, bpos, fpos),
2921                                  flen)));
2922
2923   if (!ret)
2924     return ret;
2925
2926   if (data)
2927     {
2928       tree bend, fend;
2929
2930       data->field_len = flen;
2931       data->field_pos = fpos;
2932
2933       fend = size_binop (PLUS_EXPR, fpos, flen);
2934       bend = size_binop (PLUS_EXPR, bpos, blen);
2935
2936       if (tree_int_cst_lt (bend, fend))
2937         data->overlap_len = size_binop (MINUS_EXPR, bend, fpos);
2938       else
2939         data->overlap_len = NULL;
2940
2941       if (tree_int_cst_lt (fpos, bpos))
2942         {
2943           data->overlap_pos = size_binop (MINUS_EXPR, bpos, fpos);
2944           data->overlap_len = size_binop (MINUS_EXPR,
2945                                           data->overlap_len
2946                                           ? data->overlap_len
2947                                           : data->field_len,
2948                                           data->overlap_pos);
2949         }
2950       else
2951         data->overlap_pos = NULL;
2952     }
2953
2954   return ret;
2955 }
2956
2957 /* Add to LISTP a sequence of statements that copies BLEN bits between
2958    VAR and the scalarized elements of ELT, starting a bit VPOS of VAR
2959    and at bit BPOS of ELT.  The direction of the copy is given by
2960    TO_VAR.  */
2961
2962 static void
2963 sra_explode_bitfield_assignment (tree var, tree vpos, bool to_var,
2964                                  gimple_seq *seq_p, tree blen, tree bpos,
2965                                  struct sra_elt *elt)
2966 {
2967   struct sra_elt *fld;
2968   struct bitfield_overlap_info flp;
2969
2970   FOR_EACH_ACTUAL_CHILD (fld, elt)
2971     {
2972       tree flen, fpos;
2973
2974       if (!bitfield_overlaps_p (blen, bpos, fld, &flp))
2975         continue;
2976
2977       flen = flp.overlap_len ? flp.overlap_len : flp.field_len;
2978       fpos = flp.overlap_pos ? flp.overlap_pos : bitsize_int (0);
2979
2980       if (fld->replacement)
2981         {
2982           tree infld, invar, type;
2983           gimple_seq st;
2984
2985           infld = fld->replacement;
2986
2987           type = unsigned_type_for (TREE_TYPE (infld));
2988           if (TYPE_PRECISION (type) != TREE_INT_CST_LOW (flen))
2989             type = build_nonstandard_integer_type (TREE_INT_CST_LOW (flen), 1);
2990
2991           if (TREE_CODE (infld) == BIT_FIELD_REF)
2992             {
2993               fpos = size_binop (PLUS_EXPR, fpos, TREE_OPERAND (infld, 2));
2994               infld = TREE_OPERAND (infld, 0);
2995             }
2996           else if (BYTES_BIG_ENDIAN && DECL_P (fld->element)
2997                    && !tree_int_cst_equal (TYPE_SIZE (TREE_TYPE (infld)),
2998                                            DECL_SIZE (fld->element)))
2999             {
3000               fpos = size_binop (PLUS_EXPR, fpos,
3001                                  TYPE_SIZE (TREE_TYPE (infld)));
3002               fpos = size_binop (MINUS_EXPR, fpos,
3003                                  DECL_SIZE (fld->element));
3004             }
3005
3006           infld = fold_build3 (BIT_FIELD_REF, type, infld, flen, fpos);
3007
3008           invar = size_binop (MINUS_EXPR, flp.field_pos, bpos);
3009           if (flp.overlap_pos)
3010             invar = size_binop (PLUS_EXPR, invar, flp.overlap_pos);
3011           invar = size_binop (PLUS_EXPR, invar, vpos);
3012
3013           invar = fold_build3 (BIT_FIELD_REF, type, var, flen, invar);
3014
3015           if (to_var)
3016             st = sra_build_bf_assignment (invar, infld);
3017           else
3018             st = sra_build_bf_assignment (infld, invar);
3019
3020           gimple_seq_add_seq (seq_p, st);
3021         }
3022       else
3023         {
3024           tree sub = size_binop (MINUS_EXPR, flp.field_pos, bpos);
3025           sub = size_binop (PLUS_EXPR, vpos, sub);
3026           if (flp.overlap_pos)
3027             sub = size_binop (PLUS_EXPR, sub, flp.overlap_pos);
3028
3029           sra_explode_bitfield_assignment (var, sub, to_var, seq_p,
3030                                            flen, fpos, fld);
3031         }
3032     }
3033 }
3034
3035 /* Add to LISTBEFOREP statements that copy scalarized members of ELT
3036    that overlap with BIT_FIELD_REF<(ELT->element), BLEN, BPOS> back
3037    into the full variable, and to LISTAFTERP, if non-NULL, statements
3038    that copy the (presumably modified) overlapping portions of the
3039    full variable back to the scalarized variables.  */
3040
3041 static void
3042 sra_sync_for_bitfield_assignment (gimple_seq *seq_before_p,
3043                                   gimple_seq *seq_after_p,
3044                                   tree blen, tree bpos,
3045                                   struct sra_elt *elt)
3046 {
3047   struct sra_elt *fld;
3048   struct bitfield_overlap_info flp;
3049
3050   FOR_EACH_ACTUAL_CHILD (fld, elt)
3051     if (bitfield_overlaps_p (blen, bpos, fld, &flp))
3052       {
3053         if (fld->replacement || (!flp.overlap_len && !flp.overlap_pos))
3054           {
3055             generate_copy_inout (fld, false, generate_element_ref (fld),
3056                                  seq_before_p);
3057             mark_no_warning (fld);
3058             if (seq_after_p)
3059               generate_copy_inout (fld, true, generate_element_ref (fld),
3060                                    seq_after_p);
3061           }
3062         else
3063           {
3064             tree flen = flp.overlap_len ? flp.overlap_len : flp.field_len;
3065             tree fpos = flp.overlap_pos ? flp.overlap_pos : bitsize_int (0);
3066
3067             sra_sync_for_bitfield_assignment (seq_before_p, seq_after_p,
3068                                               flen, fpos, fld);
3069           }
3070       }
3071 }
3072
3073 /* Scalarize a USE.  To recap, this is either a simple reference to ELT,
3074    if elt is scalar, or some occurrence of ELT that requires a complete
3075    aggregate.  IS_OUTPUT is true if ELT is being modified.  */
3076
3077 static void
3078 scalarize_use (struct sra_elt *elt, tree *expr_p, gimple_stmt_iterator *gsi,
3079                bool is_output, bool use_all)
3080 {
3081   gimple stmt = gsi_stmt (*gsi);
3082   tree bfexpr;
3083
3084   if (elt->replacement)
3085     {
3086       tree replacement = elt->replacement;
3087
3088       /* If we have a replacement, then updating the reference is as
3089          simple as modifying the existing statement in place.  */
3090       if (is_output
3091           && TREE_CODE (elt->replacement) == BIT_FIELD_REF
3092           && is_gimple_reg (TREE_OPERAND (elt->replacement, 0))
3093           && is_gimple_assign (stmt)
3094           && gimple_assign_lhs_ptr (stmt) == expr_p)
3095         {
3096           gimple_seq newseq;
3097           /* RHS must be a single operand. */
3098           gcc_assert (gimple_assign_single_p (stmt));
3099           newseq = sra_build_elt_assignment (elt, gimple_assign_rhs1 (stmt));
3100           sra_replace (gsi, newseq);
3101           return;
3102         }
3103       else if (!is_output
3104                && TREE_CODE (elt->replacement) == BIT_FIELD_REF
3105                && is_gimple_assign (stmt)
3106                && gimple_assign_rhs1_ptr (stmt) == expr_p)
3107         {
3108           tree tmp = make_rename_temp
3109             (TREE_TYPE (gimple_assign_lhs (stmt)), "SR");
3110           gimple_seq newseq = sra_build_assignment (tmp, REPLDUP (elt->replacement));
3111
3112           sra_insert_before (gsi, newseq);
3113           replacement = tmp;
3114         }
3115       if (is_output)
3116           update_stmt_if_modified (stmt);
3117       *expr_p = REPLDUP (replacement);
3118       update_stmt (stmt);
3119     }
3120   else if (use_all && is_output
3121            && is_gimple_assign (stmt)
3122            && TREE_CODE (bfexpr
3123                          = gimple_assign_lhs (stmt)) == BIT_FIELD_REF
3124            && &TREE_OPERAND (bfexpr, 0) == expr_p
3125            && INTEGRAL_TYPE_P (TREE_TYPE (bfexpr))
3126            && TREE_CODE (TREE_TYPE (*expr_p)) == RECORD_TYPE)
3127     {
3128       gimple_seq seq_before = NULL;
3129       gimple_seq seq_after = NULL;
3130       tree blen = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 1));
3131       tree bpos = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 2));
3132       bool update = false;
3133
3134       if (!elt->use_block_copy)
3135         {
3136           tree type = TREE_TYPE (bfexpr);
3137           tree var = make_rename_temp (type, "SR"), tmp, vpos;
3138           gimple st;
3139
3140           gimple_assign_set_lhs (stmt, var);
3141           update = true;
3142
3143           if (!TYPE_UNSIGNED (type))
3144             {
3145               type = unsigned_type_for (type);
3146               tmp = make_rename_temp (type, "SR");
3147               st = gimple_build_assign (tmp, fold_convert (type, var));
3148               gimple_seq_add_stmt (&seq_after, st);
3149               var = tmp;
3150             }
3151
3152           /* If VAR is wider than BLEN bits, it is padded at the
3153              most-significant end.  We want to set VPOS such that
3154              <BIT_FIELD_REF VAR BLEN VPOS> would refer to the
3155              least-significant BLEN bits of VAR.  */
3156           if (BYTES_BIG_ENDIAN)
3157             vpos = size_binop (MINUS_EXPR, TYPE_SIZE (type), blen);
3158           else
3159             vpos = bitsize_int (0);
3160           sra_explode_bitfield_assignment
3161             (var, vpos, false, &seq_after, blen, bpos, elt);
3162         }
3163       else
3164         sra_sync_for_bitfield_assignment
3165           (&seq_before, &seq_after, blen, bpos, elt);
3166
3167       if (seq_before)
3168         {
3169           mark_all_v_defs_seq (seq_before);
3170           sra_insert_before (gsi, seq_before);
3171         }
3172       if (seq_after)
3173         {
3174           mark_all_v_defs_seq (seq_after);
3175           sra_insert_after (gsi, seq_after);
3176         }
3177
3178       if (update)
3179         update_stmt (stmt);
3180     }
3181   else if (use_all && !is_output
3182            && is_gimple_assign (stmt)
3183            && TREE_CODE (bfexpr
3184                          = gimple_assign_rhs1 (stmt)) == BIT_FIELD_REF
3185            && &TREE_OPERAND (gimple_assign_rhs1 (stmt), 0) == expr_p
3186            && INTEGRAL_TYPE_P (TREE_TYPE (bfexpr))
3187            && TREE_CODE (TREE_TYPE (*expr_p)) == RECORD_TYPE)
3188     {
3189       gimple_seq seq = NULL;
3190       tree blen = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 1));
3191       tree bpos = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 2));
3192       bool update = false;
3193
3194       if (!elt->use_block_copy)
3195         {
3196           tree type = TREE_TYPE (bfexpr);
3197           tree var = make_rename_temp (type, "SR"), tmp, vpos;
3198           gimple st = NULL;
3199
3200           gimple_assign_set_rhs1 (stmt, var);
3201           update = true;
3202
3203           if (!TYPE_UNSIGNED (type))
3204             {
3205               type = unsigned_type_for (type);
3206               tmp = make_rename_temp (type, "SR");
3207               st = gimple_build_assign (var,
3208                                         fold_convert (TREE_TYPE (var), tmp));
3209               var = tmp;
3210             }
3211
3212           gimple_seq_add_stmt (&seq,
3213                                gimple_build_assign
3214                                  (var, build_int_cst_wide (type, 0, 0)));
3215
3216           /* If VAR is wider than BLEN bits, it is padded at the
3217              most-significant end.  We want to set VPOS such that
3218              <BIT_FIELD_REF VAR BLEN VPOS> would refer to the
3219              least-significant BLEN bits of VAR.  */
3220           if (BYTES_BIG_ENDIAN)
3221             vpos = size_binop (MINUS_EXPR, TYPE_SIZE (type), blen);
3222           else
3223             vpos = bitsize_int (0);
3224           sra_explode_bitfield_assignment
3225             (var, vpos, true, &seq, blen, bpos, elt);
3226
3227           if (st)
3228             gimple_seq_add_stmt (&seq, st);
3229         }
3230       else
3231         sra_sync_for_bitfield_assignment
3232           (&seq, NULL, blen, bpos, elt);
3233
3234       if (seq)
3235         {
3236           mark_all_v_defs_seq (seq);
3237           sra_insert_before (gsi, seq);
3238         }
3239
3240       if (update)
3241         update_stmt (stmt);
3242     }
3243   else
3244     {
3245       gimple_seq seq = NULL;
3246
3247       /* Otherwise we need some copies.  If ELT is being read, then we
3248          want to store all (modified) sub-elements back into the
3249          structure before the reference takes place.  If ELT is being
3250          written, then we want to load the changed values back into
3251          our shadow variables.  */
3252       /* ??? We don't check modified for reads, we just always write all of
3253          the values.  We should be able to record the SSA number of the VOP
3254          for which the values were last read.  If that number matches the
3255          SSA number of the VOP in the current statement, then we needn't
3256          emit an assignment.  This would also eliminate double writes when
3257          a structure is passed as more than one argument to a function call.
3258          This optimization would be most effective if sra_walk_function
3259          processed the blocks in dominator order.  */
3260
3261       generate_copy_inout (elt, is_output, generate_element_ref (elt), &seq);
3262       if (seq == NULL)
3263         return;
3264       mark_all_v_defs_seq (seq);
3265       if (is_output)
3266         sra_insert_after (gsi, seq);
3267       else
3268         {
3269           sra_insert_before (gsi, seq);
3270           if (use_all)
3271             mark_no_warning (elt);
3272         }
3273     }
3274 }
3275
3276 /* Scalarize a COPY.  To recap, this is an assignment statement between
3277    two scalarizable references, LHS_ELT and RHS_ELT.  */
3278
3279 static void
3280 scalarize_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
3281                 gimple_stmt_iterator *gsi)
3282 {
3283   gimple_seq seq;
3284   gimple stmt;
3285
3286   if (lhs_elt->replacement && rhs_elt->replacement)
3287     {
3288       /* If we have two scalar operands, modify the existing statement.  */
3289       stmt = gsi_stmt (*gsi);
3290
3291       /* See the commentary in sra_walk_function concerning
3292          RETURN_EXPR, and why we should never see one here.  */
3293       gcc_assert (is_gimple_assign (stmt));
3294       gcc_assert (gimple_assign_copy_p (stmt));
3295
3296
3297       gimple_assign_set_lhs (stmt, lhs_elt->replacement);
3298       gimple_assign_set_rhs1 (stmt, REPLDUP (rhs_elt->replacement));
3299       update_stmt (stmt);
3300     }
3301   else if (lhs_elt->use_block_copy || rhs_elt->use_block_copy)
3302     {
3303       /* If either side requires a block copy, then sync the RHS back
3304          to the original structure, leave the original assignment
3305          statement (which will perform the block copy), then load the
3306          LHS values out of its now-updated original structure.  */
3307       /* ??? Could perform a modified pair-wise element copy.  That
3308          would at least allow those elements that are instantiated in
3309          both structures to be optimized well.  */
3310
3311       seq = NULL;
3312       generate_copy_inout (rhs_elt, false,
3313                            generate_element_ref (rhs_elt), &seq);
3314       if (seq)
3315         {
3316           mark_all_v_defs_seq (seq);
3317           sra_insert_before (gsi, seq);
3318         }
3319
3320       seq = NULL;
3321       generate_copy_inout (lhs_elt, true,
3322                            generate_element_ref (lhs_elt), &seq);
3323       if (seq)
3324         {
3325           mark_all_v_defs_seq (seq);
3326           sra_insert_after (gsi, seq);
3327         }
3328     }
3329   else
3330     {
3331       /* Otherwise both sides must be fully instantiated.  In which
3332          case perform pair-wise element assignments and replace the
3333          original block copy statement.  */
3334
3335       stmt = gsi_stmt (*gsi);
3336       update_stmt_if_modified (stmt);
3337
3338       seq = NULL;
3339       generate_element_copy (lhs_elt, rhs_elt, &seq);
3340       gcc_assert (seq);
3341       mark_all_v_defs_seq (seq);
3342       sra_replace (gsi, seq);
3343     }
3344 }
3345
3346 /* Scalarize an INIT.  To recap, this is an assignment to a scalarizable
3347    reference from some form of constructor: CONSTRUCTOR, COMPLEX_CST or
3348    COMPLEX_EXPR.  If RHS is NULL, it should be treated as an empty
3349    CONSTRUCTOR.  */
3350
3351 static void
3352 scalarize_init (struct sra_elt *lhs_elt, tree rhs, gimple_stmt_iterator *gsi)
3353 {
3354   bool result = true;
3355   gimple_seq seq = NULL, init_seq = NULL;
3356
3357   /* Generate initialization statements for all members extant in the RHS.  */
3358   if (rhs)
3359     {
3360       /* Unshare the expression just in case this is from a decl's initial.  */
3361       rhs = unshare_expr (rhs);
3362       result = generate_element_init (lhs_elt, rhs, &init_seq);
3363     }
3364
3365   if (!result)
3366     {
3367       /* If we failed to convert the entire initializer, then we must
3368          leave the structure assignment in place and must load values
3369          from the structure into the slots for which we did not find
3370          constants.  The easiest way to do this is to generate a complete
3371          copy-out, and then follow that with the constant assignments
3372          that we were able to build.  DCE will clean things up.  */
3373       gimple_seq seq0 = NULL;
3374       generate_copy_inout (lhs_elt, true, generate_element_ref (lhs_elt),
3375                            &seq0);
3376       gimple_seq_add_seq (&seq0, seq);
3377       seq = seq0;
3378     }
3379   else
3380     {
3381       /* CONSTRUCTOR is defined such that any member not mentioned is assigned
3382          a zero value.  Initialize the rest of the instantiated elements.  */
3383       generate_element_zero (lhs_elt, &seq);
3384       gimple_seq_add_seq (&seq, init_seq);
3385     }
3386
3387   if (lhs_elt->use_block_copy || !result)
3388     {
3389       /* Since LHS is not fully instantiated, we must leave the structure
3390          assignment in place.  Treating this case differently from a USE
3391          exposes constants to later optimizations.  */
3392       if (seq)
3393         {
3394           mark_all_v_defs_seq (seq);
3395           sra_insert_after (gsi, seq);
3396         }
3397     }
3398   else
3399     {
3400       /* The LHS is fully instantiated.  The list of initializations
3401          replaces the original structure assignment.  */
3402       gcc_assert (seq);
3403       update_stmt_if_modified (gsi_stmt (*gsi));
3404       mark_all_v_defs_seq (seq);
3405       sra_replace (gsi, seq);
3406     }
3407 }
3408
3409 /* A subroutine of scalarize_ldst called via walk_tree.  Set TREE_NO_TRAP
3410    on all INDIRECT_REFs.  */
3411
3412 static tree
3413 mark_notrap (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3414 {
3415   tree t = *tp;
3416
3417   if (TREE_CODE (t) == INDIRECT_REF)
3418     {
3419       TREE_THIS_NOTRAP (t) = 1;
3420       *walk_subtrees = 0;
3421     }
3422   else if (IS_TYPE_OR_DECL_P (t))
3423     *walk_subtrees = 0;
3424
3425   return NULL;
3426 }
3427
3428 /* Scalarize a LDST.  To recap, this is an assignment between one scalarizable
3429    reference ELT and one non-scalarizable reference OTHER.  IS_OUTPUT is true
3430    if ELT is on the left-hand side.  */
3431
3432 static void
3433 scalarize_ldst (struct sra_elt *elt, tree other,
3434                 gimple_stmt_iterator *gsi, bool is_output)
3435 {
3436   /* Shouldn't have gotten called for a scalar.  */
3437   gcc_assert (!elt->replacement);
3438
3439   if (elt->use_block_copy)
3440     {
3441       /* Since ELT is not fully instantiated, we have to leave the
3442          block copy in place.  Treat this as a USE.  */
3443       scalarize_use (elt, NULL, gsi, is_output, false);
3444     }
3445   else
3446     {
3447       /* The interesting case is when ELT is fully instantiated.  In this
3448          case we can have each element stored/loaded directly to/from the
3449          corresponding slot in OTHER.  This avoids a block copy.  */
3450
3451       gimple_seq seq = NULL;
3452       gimple stmt = gsi_stmt (*gsi);
3453
3454       update_stmt_if_modified (stmt);
3455       generate_copy_inout (elt, is_output, other, &seq);
3456       gcc_assert (seq);
3457       mark_all_v_defs_seq (seq);
3458
3459       /* Preserve EH semantics.  */
3460       if (stmt_ends_bb_p (stmt))
3461         {
3462           gimple_stmt_iterator si;
3463           gimple first;
3464           gimple_seq blist = NULL;
3465           bool thr = stmt_could_throw_p (stmt);
3466
3467           /* If the last statement of this BB created an EH edge
3468              before scalarization, we have to locate the first
3469              statement that can throw in the new statement list and
3470              use that as the last statement of this BB, such that EH
3471              semantics is preserved.  All statements up to this one
3472              are added to the same BB.  All other statements in the
3473              list will be added to normal outgoing edges of the same
3474              BB.  If they access any memory, it's the same memory, so
3475              we can assume they won't throw.  */
3476           si = gsi_start (seq);
3477           for (first = gsi_stmt (si);
3478                thr && !gsi_end_p (si) && !stmt_could_throw_p (first);
3479                first = gsi_stmt (si))
3480             {
3481               gsi_remove (&si, false);
3482               gimple_seq_add_stmt (&blist, first);
3483             }
3484
3485           /* Extract the first remaining statement from LIST, this is
3486              the EH statement if there is one.  */
3487           gsi_remove (&si, false);
3488
3489           if (blist)
3490             sra_insert_before (gsi, blist);
3491
3492           /* Replace the old statement with this new representative.  */
3493           gsi_replace (gsi, first, true);
3494
3495           if (!gsi_end_p (si))
3496             {
3497               /* If any reference would trap, then they all would.  And more
3498                  to the point, the first would.  Therefore none of the rest
3499                  will trap since the first didn't.  Indicate this by
3500                  iterating over the remaining statements and set
3501                  TREE_THIS_NOTRAP in all INDIRECT_REFs.  */
3502               do
3503                 {
3504                   walk_gimple_stmt (&si, NULL, mark_notrap, NULL);
3505                   gsi_next (&si);
3506                 }
3507               while (!gsi_end_p (si));
3508
3509               insert_edge_copies_seq (seq, gsi_bb (*gsi));
3510             }
3511         }
3512       else
3513         sra_replace (gsi, seq);
3514     }
3515 }
3516
3517 /* Generate initializations for all scalarizable parameters.  */
3518
3519 static void
3520 scalarize_parms (void)
3521 {
3522   gimple_seq seq = NULL;
3523   unsigned i;
3524   bitmap_iterator bi;
3525
3526   EXECUTE_IF_SET_IN_BITMAP (needs_copy_in, 0, i, bi)
3527     {
3528       tree var = referenced_var (i);
3529       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
3530       generate_copy_inout (elt, true, var, &seq);
3531     }
3532
3533   if (seq)
3534     {
3535       insert_edge_copies_seq (seq, ENTRY_BLOCK_PTR);
3536       mark_all_v_defs_seq (seq);
3537     }
3538 }
3539
3540 /* Entry point to phase 4.  Update the function to match replacements.  */
3541
3542 static void
3543 scalarize_function (void)
3544 {
3545   static const struct sra_walk_fns fns = {
3546     scalarize_use, scalarize_copy, scalarize_init, scalarize_ldst, false
3547   };
3548
3549   sra_walk_function (&fns);
3550   scalarize_parms ();
3551   gsi_commit_edge_inserts ();
3552 }
3553
3554 \f
3555 /* Debug helper function.  Print ELT in a nice human-readable format.  */
3556
3557 static void
3558 dump_sra_elt_name (FILE *f, struct sra_elt *elt)
3559 {
3560   if (elt->parent && TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
3561     {
3562       fputs (elt->element == integer_zero_node ? "__real__ " : "__imag__ ", f);
3563       dump_sra_elt_name (f, elt->parent);
3564     }
3565   else
3566     {
3567       if (elt->parent)
3568         dump_sra_elt_name (f, elt->parent);
3569       if (DECL_P (elt->element))
3570         {
3571           if (TREE_CODE (elt->element) == FIELD_DECL)
3572             fputc ('.', f);
3573           print_generic_expr (f, elt->element, dump_flags);
3574         }
3575       else if (TREE_CODE (elt->element) == BIT_FIELD_REF)
3576         fprintf (f, "$B" HOST_WIDE_INT_PRINT_DEC "F" HOST_WIDE_INT_PRINT_DEC,
3577                  tree_low_cst (TREE_OPERAND (elt->element, 2), 1),
3578                  tree_low_cst (TREE_OPERAND (elt->element, 1), 1));
3579       else if (TREE_CODE (elt->element) == RANGE_EXPR)
3580         fprintf (f, "["HOST_WIDE_INT_PRINT_DEC".."HOST_WIDE_INT_PRINT_DEC"]",
3581                  TREE_INT_CST_LOW (TREE_OPERAND (elt->element, 0)),
3582                  TREE_INT_CST_LOW (TREE_OPERAND (elt->element, 1)));
3583       else
3584         fprintf (f, "[" HOST_WIDE_INT_PRINT_DEC "]",
3585                  TREE_INT_CST_LOW (elt->element));
3586     }
3587 }
3588
3589 /* Likewise, but callable from the debugger.  */
3590
3591 void
3592 debug_sra_elt_name (struct sra_elt *elt)
3593 {
3594   dump_sra_elt_name (stderr, elt);
3595   fputc ('\n', stderr);
3596 }
3597
3598 void 
3599 sra_init_cache (void)
3600 {
3601   if (sra_type_decomp_cache)
3602     return;
3603
3604   sra_type_decomp_cache = BITMAP_ALLOC (NULL);
3605   sra_type_inst_cache = BITMAP_ALLOC (NULL);
3606 }
3607
3608
3609 /* Main entry point.  */
3610
3611 static unsigned int
3612 tree_sra (void)
3613 {
3614   /* Initialize local variables.  */
3615   gcc_obstack_init (&sra_obstack);
3616   sra_candidates = BITMAP_ALLOC (NULL);
3617   needs_copy_in = BITMAP_ALLOC (NULL);
3618   sra_init_cache ();
3619   sra_map = htab_create (101, sra_elt_hash, sra_elt_eq, NULL);
3620
3621   /* Scan.  If we find anything, instantiate and scalarize.  */
3622   if (find_candidates_for_sra ())
3623     {
3624       scan_function ();
3625       decide_instantiations ();
3626       scalarize_function ();
3627     }
3628
3629   /* Free allocated memory.  */
3630   htab_delete (sra_map);
3631   sra_map = NULL;
3632   BITMAP_FREE (sra_candidates);
3633   BITMAP_FREE (needs_copy_in);
3634   BITMAP_FREE (sra_type_decomp_cache);
3635   BITMAP_FREE (sra_type_inst_cache);
3636   obstack_free (&sra_obstack, NULL);
3637   return 0;
3638 }
3639
3640 static unsigned int
3641 tree_sra_early (void)
3642 {
3643   unsigned int ret;
3644
3645   early_sra = true;
3646   ret = tree_sra ();
3647   early_sra = false;
3648
3649   return ret;
3650 }
3651
3652 static bool
3653 gate_sra (void)
3654 {
3655   return flag_tree_sra != 0;
3656 }
3657
3658 struct gimple_opt_pass pass_sra_early =
3659 {
3660  {
3661   GIMPLE_PASS,
3662   "esra",                               /* name */
3663   gate_sra,                             /* gate */
3664   tree_sra_early,                       /* execute */
3665   NULL,                                 /* sub */
3666   NULL,                                 /* next */
3667   0,                                    /* static_pass_number */
3668   TV_TREE_SRA,                          /* tv_id */
3669   PROP_cfg | PROP_ssa,                  /* properties_required */
3670   0,                                    /* properties_provided */
3671   0,                                    /* properties_destroyed */
3672   0,                                    /* todo_flags_start */
3673   TODO_dump_func
3674   | TODO_update_ssa
3675   | TODO_ggc_collect
3676   | TODO_verify_ssa                     /* todo_flags_finish */
3677  }
3678 };
3679
3680 struct gimple_opt_pass pass_sra =
3681 {
3682  {
3683   GIMPLE_PASS,
3684   "sra",                                /* name */
3685   gate_sra,                             /* gate */
3686   tree_sra,                             /* execute */
3687   NULL,                                 /* sub */
3688   NULL,                                 /* next */
3689   0,                                    /* static_pass_number */
3690   TV_TREE_SRA,                          /* tv_id */
3691   PROP_cfg | PROP_ssa,                  /* properties_required */
3692   0,                                    /* properties_provided */
3693   0,                                    /* properties_destroyed */
3694   TODO_update_address_taken,            /* todo_flags_start */
3695   TODO_dump_func
3696   | TODO_update_ssa
3697   | TODO_ggc_collect
3698   | TODO_verify_ssa                     /* todo_flags_finish */
3699  }
3700 };