OSDN Git Service

2011-04-29 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / cfgexpand.c
1 /* A pass for lowering trees to RTL.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "basic-block.h"
29 #include "function.h"
30 #include "expr.h"
31 #include "langhooks.h"
32 #include "tree-flow.h"
33 #include "timevar.h"
34 #include "tree-dump.h"
35 #include "tree-pass.h"
36 #include "except.h"
37 #include "flags.h"
38 #include "diagnostic.h"
39 #include "tree-pretty-print.h"
40 #include "gimple-pretty-print.h"
41 #include "toplev.h"
42 #include "debug.h"
43 #include "params.h"
44 #include "tree-inline.h"
45 #include "value-prof.h"
46 #include "target.h"
47 #include "ssaexpand.h"
48 #include "bitmap.h"
49 #include "sbitmap.h"
50 #include "insn-attr.h" /* For INSN_SCHEDULING.  */
51
52 /* This variable holds information helping the rewriting of SSA trees
53    into RTL.  */
54 struct ssaexpand SA;
55
56 /* This variable holds the currently expanded gimple statement for purposes
57    of comminucating the profile info to the builtin expanders.  */
58 gimple currently_expanding_gimple_stmt;
59
60 /* Return an expression tree corresponding to the RHS of GIMPLE
61    statement STMT.  */
62
63 tree
64 gimple_assign_rhs_to_tree (gimple stmt)
65 {
66   tree t;
67   enum gimple_rhs_class grhs_class;
68
69   grhs_class = get_gimple_rhs_class (gimple_expr_code (stmt));
70
71   if (grhs_class == GIMPLE_TERNARY_RHS)
72     t = build3 (gimple_assign_rhs_code (stmt),
73                 TREE_TYPE (gimple_assign_lhs (stmt)),
74                 gimple_assign_rhs1 (stmt),
75                 gimple_assign_rhs2 (stmt),
76                 gimple_assign_rhs3 (stmt));
77   else if (grhs_class == GIMPLE_BINARY_RHS)
78     t = build2 (gimple_assign_rhs_code (stmt),
79                 TREE_TYPE (gimple_assign_lhs (stmt)),
80                 gimple_assign_rhs1 (stmt),
81                 gimple_assign_rhs2 (stmt));
82   else if (grhs_class == GIMPLE_UNARY_RHS)
83     t = build1 (gimple_assign_rhs_code (stmt),
84                 TREE_TYPE (gimple_assign_lhs (stmt)),
85                 gimple_assign_rhs1 (stmt));
86   else if (grhs_class == GIMPLE_SINGLE_RHS)
87     {
88       t = gimple_assign_rhs1 (stmt);
89       /* Avoid modifying this tree in place below.  */
90       if ((gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (t)
91            && gimple_location (stmt) != EXPR_LOCATION (t))
92           || (gimple_block (stmt)
93               && currently_expanding_to_rtl
94               && EXPR_P (t)
95               && gimple_block (stmt) != TREE_BLOCK (t)))
96         t = copy_node (t);
97     }
98   else
99     gcc_unreachable ();
100
101   if (gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (t))
102     SET_EXPR_LOCATION (t, gimple_location (stmt));
103   if (gimple_block (stmt) && currently_expanding_to_rtl && EXPR_P (t))
104     TREE_BLOCK (t) = gimple_block (stmt);
105
106   return t;
107 }
108
109
110 #ifndef STACK_ALIGNMENT_NEEDED
111 #define STACK_ALIGNMENT_NEEDED 1
112 #endif
113
114 #define SSAVAR(x) (TREE_CODE (x) == SSA_NAME ? SSA_NAME_VAR (x) : x)
115
116 /* Associate declaration T with storage space X.  If T is no
117    SSA name this is exactly SET_DECL_RTL, otherwise make the
118    partition of T associated with X.  */
119 static inline void
120 set_rtl (tree t, rtx x)
121 {
122   if (TREE_CODE (t) == SSA_NAME)
123     {
124       SA.partition_to_pseudo[var_to_partition (SA.map, t)] = x;
125       if (x && !MEM_P (x))
126         set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (t), x);
127       /* For the benefit of debug information at -O0 (where vartracking
128          doesn't run) record the place also in the base DECL if it's
129          a normal variable (not a parameter).  */
130       if (x && x != pc_rtx && TREE_CODE (SSA_NAME_VAR (t)) == VAR_DECL)
131         {
132           tree var = SSA_NAME_VAR (t);
133           /* If we don't yet have something recorded, just record it now.  */
134           if (!DECL_RTL_SET_P (var))
135             SET_DECL_RTL (var, x);
136           /* If we have it set alrady to "multiple places" don't
137              change this.  */
138           else if (DECL_RTL (var) == pc_rtx)
139             ;
140           /* If we have something recorded and it's not the same place
141              as we want to record now, we have multiple partitions for the
142              same base variable, with different places.  We can't just
143              randomly chose one, hence we have to say that we don't know.
144              This only happens with optimization, and there var-tracking
145              will figure out the right thing.  */
146           else if (DECL_RTL (var) != x)
147             SET_DECL_RTL (var, pc_rtx);
148         }
149     }
150   else
151     SET_DECL_RTL (t, x);
152 }
153
154 /* This structure holds data relevant to one variable that will be
155    placed in a stack slot.  */
156 struct stack_var
157 {
158   /* The Variable.  */
159   tree decl;
160
161   /* Initially, the size of the variable.  Later, the size of the partition,
162      if this variable becomes it's partition's representative.  */
163   HOST_WIDE_INT size;
164
165   /* The *byte* alignment required for this variable.  Or as, with the
166      size, the alignment for this partition.  */
167   unsigned int alignb;
168
169   /* The partition representative.  */
170   size_t representative;
171
172   /* The next stack variable in the partition, or EOC.  */
173   size_t next;
174
175   /* The numbers of conflicting stack variables.  */
176   bitmap conflicts;
177 };
178
179 #define EOC  ((size_t)-1)
180
181 /* We have an array of such objects while deciding allocation.  */
182 static struct stack_var *stack_vars;
183 static size_t stack_vars_alloc;
184 static size_t stack_vars_num;
185
186 /* An array of indices such that stack_vars[stack_vars_sorted[i]].size
187    is non-decreasing.  */
188 static size_t *stack_vars_sorted;
189
190 /* The phase of the stack frame.  This is the known misalignment of
191    virtual_stack_vars_rtx from PREFERRED_STACK_BOUNDARY.  That is,
192    (frame_offset+frame_phase) % PREFERRED_STACK_BOUNDARY == 0.  */
193 static int frame_phase;
194
195 /* Used during expand_used_vars to remember if we saw any decls for
196    which we'd like to enable stack smashing protection.  */
197 static bool has_protected_decls;
198
199 /* Used during expand_used_vars.  Remember if we say a character buffer
200    smaller than our cutoff threshold.  Used for -Wstack-protector.  */
201 static bool has_short_buffer;
202
203 /* Compute the byte alignment to use for DECL.  Ignore alignment
204    we can't do with expected alignment of the stack boundary.  */
205
206 static unsigned int
207 align_local_variable (tree decl)
208 {
209   unsigned int align = LOCAL_DECL_ALIGNMENT (decl);
210   DECL_ALIGN (decl) = align;
211   return align / BITS_PER_UNIT;
212 }
213
214 /* Allocate SIZE bytes at byte alignment ALIGN from the stack frame.
215    Return the frame offset.  */
216
217 static HOST_WIDE_INT
218 alloc_stack_frame_space (HOST_WIDE_INT size, unsigned HOST_WIDE_INT align)
219 {
220   HOST_WIDE_INT offset, new_frame_offset;
221
222   new_frame_offset = frame_offset;
223   if (FRAME_GROWS_DOWNWARD)
224     {
225       new_frame_offset -= size + frame_phase;
226       new_frame_offset &= -align;
227       new_frame_offset += frame_phase;
228       offset = new_frame_offset;
229     }
230   else
231     {
232       new_frame_offset -= frame_phase;
233       new_frame_offset += align - 1;
234       new_frame_offset &= -align;
235       new_frame_offset += frame_phase;
236       offset = new_frame_offset;
237       new_frame_offset += size;
238     }
239   frame_offset = new_frame_offset;
240
241   if (frame_offset_overflow (frame_offset, cfun->decl))
242     frame_offset = offset = 0;
243
244   return offset;
245 }
246
247 /* Accumulate DECL into STACK_VARS.  */
248
249 static void
250 add_stack_var (tree decl)
251 {
252   struct stack_var *v;
253
254   if (stack_vars_num >= stack_vars_alloc)
255     {
256       if (stack_vars_alloc)
257         stack_vars_alloc = stack_vars_alloc * 3 / 2;
258       else
259         stack_vars_alloc = 32;
260       stack_vars
261         = XRESIZEVEC (struct stack_var, stack_vars, stack_vars_alloc);
262     }
263   v = &stack_vars[stack_vars_num];
264
265   v->decl = decl;
266   v->size = tree_low_cst (DECL_SIZE_UNIT (SSAVAR (decl)), 1);
267   /* Ensure that all variables have size, so that &a != &b for any two
268      variables that are simultaneously live.  */
269   if (v->size == 0)
270     v->size = 1;
271   v->alignb = align_local_variable (SSAVAR (decl));
272
273   /* All variables are initially in their own partition.  */
274   v->representative = stack_vars_num;
275   v->next = EOC;
276
277   /* All variables initially conflict with no other.  */
278   v->conflicts = NULL;
279
280   /* Ensure that this decl doesn't get put onto the list twice.  */
281   set_rtl (decl, pc_rtx);
282
283   stack_vars_num++;
284 }
285
286 /* Make the decls associated with luid's X and Y conflict.  */
287
288 static void
289 add_stack_var_conflict (size_t x, size_t y)
290 {
291   struct stack_var *a = &stack_vars[x];
292   struct stack_var *b = &stack_vars[y];
293   if (!a->conflicts)
294     a->conflicts = BITMAP_ALLOC (NULL);
295   if (!b->conflicts)
296     b->conflicts = BITMAP_ALLOC (NULL);
297   bitmap_set_bit (a->conflicts, y);
298   bitmap_set_bit (b->conflicts, x);
299 }
300
301 /* Check whether the decls associated with luid's X and Y conflict.  */
302
303 static bool
304 stack_var_conflict_p (size_t x, size_t y)
305 {
306   struct stack_var *a = &stack_vars[x];
307   struct stack_var *b = &stack_vars[y];
308   if (!a->conflicts || !b->conflicts)
309     return false;
310   return bitmap_bit_p (a->conflicts, y);
311 }
312
313 /* Returns true if TYPE is or contains a union type.  */
314
315 static bool
316 aggregate_contains_union_type (tree type)
317 {
318   tree field;
319
320   if (TREE_CODE (type) == UNION_TYPE
321       || TREE_CODE (type) == QUAL_UNION_TYPE)
322     return true;
323   if (TREE_CODE (type) == ARRAY_TYPE)
324     return aggregate_contains_union_type (TREE_TYPE (type));
325   if (TREE_CODE (type) != RECORD_TYPE)
326     return false;
327
328   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
329     if (TREE_CODE (field) == FIELD_DECL)
330       if (aggregate_contains_union_type (TREE_TYPE (field)))
331         return true;
332
333   return false;
334 }
335
336 /* A subroutine of expand_used_vars.  If two variables X and Y have alias
337    sets that do not conflict, then do add a conflict for these variables
338    in the interference graph.  We also need to make sure to add conflicts
339    for union containing structures.  Else RTL alias analysis comes along
340    and due to type based aliasing rules decides that for two overlapping
341    union temporaries { short s; int i; } accesses to the same mem through
342    different types may not alias and happily reorders stores across
343    life-time boundaries of the temporaries (See PR25654).
344    We also have to mind MEM_IN_STRUCT_P and MEM_SCALAR_P.  */
345
346 static void
347 add_alias_set_conflicts (void)
348 {
349   size_t i, j, n = stack_vars_num;
350
351   for (i = 0; i < n; ++i)
352     {
353       tree type_i = TREE_TYPE (stack_vars[i].decl);
354       bool aggr_i = AGGREGATE_TYPE_P (type_i);
355       bool contains_union;
356
357       contains_union = aggregate_contains_union_type (type_i);
358       for (j = 0; j < i; ++j)
359         {
360           tree type_j = TREE_TYPE (stack_vars[j].decl);
361           bool aggr_j = AGGREGATE_TYPE_P (type_j);
362           if (aggr_i != aggr_j
363               /* Either the objects conflict by means of type based
364                  aliasing rules, or we need to add a conflict.  */
365               || !objects_must_conflict_p (type_i, type_j)
366               /* In case the types do not conflict ensure that access
367                  to elements will conflict.  In case of unions we have
368                  to be careful as type based aliasing rules may say
369                  access to the same memory does not conflict.  So play
370                  safe and add a conflict in this case when
371                  -fstrict-aliasing is used.  */
372               || (contains_union && flag_strict_aliasing))
373             add_stack_var_conflict (i, j);
374         }
375     }
376 }
377
378 /* A subroutine of partition_stack_vars.  A comparison function for qsort,
379    sorting an array of indices by the properties of the object.  */
380
381 static int
382 stack_var_cmp (const void *a, const void *b)
383 {
384   size_t ia = *(const size_t *)a;
385   size_t ib = *(const size_t *)b;
386   unsigned int aligna = stack_vars[ia].alignb;
387   unsigned int alignb = stack_vars[ib].alignb;
388   HOST_WIDE_INT sizea = stack_vars[ia].size;
389   HOST_WIDE_INT sizeb = stack_vars[ib].size;
390   tree decla = stack_vars[ia].decl;
391   tree declb = stack_vars[ib].decl;
392   bool largea, largeb;
393   unsigned int uida, uidb;
394
395   /* Primary compare on "large" alignment.  Large comes first.  */
396   largea = (aligna * BITS_PER_UNIT > MAX_SUPPORTED_STACK_ALIGNMENT);
397   largeb = (alignb * BITS_PER_UNIT > MAX_SUPPORTED_STACK_ALIGNMENT);
398   if (largea != largeb)
399     return (int)largeb - (int)largea;
400
401   /* Secondary compare on size, decreasing  */
402   if (sizea > sizeb)
403     return -1;
404   if (sizea < sizeb)
405     return 1;
406
407   /* Tertiary compare on true alignment, decreasing.  */
408   if (aligna < alignb)
409     return -1;
410   if (aligna > alignb)
411     return 1;
412
413   /* Final compare on ID for sort stability, increasing.
414      Two SSA names are compared by their version, SSA names come before
415      non-SSA names, and two normal decls are compared by their DECL_UID.  */
416   if (TREE_CODE (decla) == SSA_NAME)
417     {
418       if (TREE_CODE (declb) == SSA_NAME)
419         uida = SSA_NAME_VERSION (decla), uidb = SSA_NAME_VERSION (declb);
420       else
421         return -1;
422     }
423   else if (TREE_CODE (declb) == SSA_NAME)
424     return 1;
425   else
426     uida = DECL_UID (decla), uidb = DECL_UID (declb);
427   if (uida < uidb)
428     return 1;
429   if (uida > uidb)
430     return -1;
431   return 0;
432 }
433
434
435 /* If the points-to solution *PI points to variables that are in a partition
436    together with other variables add all partition members to the pointed-to
437    variables bitmap.  */
438
439 static void
440 add_partitioned_vars_to_ptset (struct pt_solution *pt,
441                                struct pointer_map_t *decls_to_partitions,
442                                struct pointer_set_t *visited, bitmap temp)
443 {
444   bitmap_iterator bi;
445   unsigned i;
446   bitmap *part;
447
448   if (pt->anything
449       || pt->vars == NULL
450       /* The pointed-to vars bitmap is shared, it is enough to
451          visit it once.  */
452       || pointer_set_insert(visited, pt->vars))
453     return;
454
455   bitmap_clear (temp);
456
457   /* By using a temporary bitmap to store all members of the partitions
458      we have to add we make sure to visit each of the partitions only
459      once.  */
460   EXECUTE_IF_SET_IN_BITMAP (pt->vars, 0, i, bi)
461     if ((!temp
462          || !bitmap_bit_p (temp, i))
463         && (part = (bitmap *) pointer_map_contains (decls_to_partitions,
464                                                     (void *)(size_t) i)))
465       bitmap_ior_into (temp, *part);
466   if (!bitmap_empty_p (temp))
467     bitmap_ior_into (pt->vars, temp);
468 }
469
470 /* Update points-to sets based on partition info, so we can use them on RTL.
471    The bitmaps representing stack partitions will be saved until expand,
472    where partitioned decls used as bases in memory expressions will be
473    rewritten.  */
474
475 static void
476 update_alias_info_with_stack_vars (void)
477 {
478   struct pointer_map_t *decls_to_partitions = NULL;
479   size_t i, j;
480   tree var = NULL_TREE;
481
482   for (i = 0; i < stack_vars_num; i++)
483     {
484       bitmap part = NULL;
485       tree name;
486       struct ptr_info_def *pi;
487
488       /* Not interested in partitions with single variable.  */
489       if (stack_vars[i].representative != i
490           || stack_vars[i].next == EOC)
491         continue;
492
493       if (!decls_to_partitions)
494         {
495           decls_to_partitions = pointer_map_create ();
496           cfun->gimple_df->decls_to_pointers = pointer_map_create ();
497         }
498
499       /* Create an SSA_NAME that points to the partition for use
500          as base during alias-oracle queries on RTL for bases that
501          have been partitioned.  */
502       if (var == NULL_TREE)
503         var = create_tmp_var (ptr_type_node, NULL);
504       name = make_ssa_name (var, NULL);
505
506       /* Create bitmaps representing partitions.  They will be used for
507          points-to sets later, so use GGC alloc.  */
508       part = BITMAP_GGC_ALLOC ();
509       for (j = i; j != EOC; j = stack_vars[j].next)
510         {
511           tree decl = stack_vars[j].decl;
512           unsigned int uid = DECL_PT_UID (decl);
513           /* We should never end up partitioning SSA names (though they
514              may end up on the stack).  Neither should we allocate stack
515              space to something that is unused and thus unreferenced, except
516              for -O0 where we are preserving even unreferenced variables.  */
517           gcc_assert (DECL_P (decl)
518                       && (!optimize
519                           || referenced_var_lookup (cfun, DECL_UID (decl))));
520           bitmap_set_bit (part, uid);
521           *((bitmap *) pointer_map_insert (decls_to_partitions,
522                                            (void *)(size_t) uid)) = part;
523           *((tree *) pointer_map_insert (cfun->gimple_df->decls_to_pointers,
524                                          decl)) = name;
525         }
526
527       /* Make the SSA name point to all partition members.  */
528       pi = get_ptr_info (name);
529       pt_solution_set (&pi->pt, part, false, false);
530     }
531
532   /* Make all points-to sets that contain one member of a partition
533      contain all members of the partition.  */
534   if (decls_to_partitions)
535     {
536       unsigned i;
537       struct pointer_set_t *visited = pointer_set_create ();
538       bitmap temp = BITMAP_ALLOC (NULL);
539
540       for (i = 1; i < num_ssa_names; i++)
541         {
542           tree name = ssa_name (i);
543           struct ptr_info_def *pi;
544
545           if (name
546               && POINTER_TYPE_P (TREE_TYPE (name))
547               && ((pi = SSA_NAME_PTR_INFO (name)) != NULL))
548             add_partitioned_vars_to_ptset (&pi->pt, decls_to_partitions,
549                                            visited, temp);
550         }
551
552       add_partitioned_vars_to_ptset (&cfun->gimple_df->escaped,
553                                      decls_to_partitions, visited, temp);
554
555       pointer_set_destroy (visited);
556       pointer_map_destroy (decls_to_partitions);
557       BITMAP_FREE (temp);
558     }
559 }
560
561 /* A subroutine of partition_stack_vars.  The UNION portion of a UNION/FIND
562    partitioning algorithm.  Partitions A and B are known to be non-conflicting.
563    Merge them into a single partition A.  */
564
565 static void
566 union_stack_vars (size_t a, size_t b)
567 {
568   struct stack_var *vb = &stack_vars[b];
569   bitmap_iterator bi;
570   unsigned u;
571
572   gcc_assert (stack_vars[b].next == EOC);
573    /* Add B to A's partition.  */
574   stack_vars[b].next = stack_vars[a].next;
575   stack_vars[b].representative = a;
576   stack_vars[a].next = b;
577
578   /* Update the required alignment of partition A to account for B.  */
579   if (stack_vars[a].alignb < stack_vars[b].alignb)
580     stack_vars[a].alignb = stack_vars[b].alignb;
581
582   /* Update the interference graph and merge the conflicts.  */
583   if (vb->conflicts)
584     {
585       EXECUTE_IF_SET_IN_BITMAP (vb->conflicts, 0, u, bi)
586         add_stack_var_conflict (a, stack_vars[u].representative);
587       BITMAP_FREE (vb->conflicts);
588     }
589 }
590
591 /* A subroutine of expand_used_vars.  Binpack the variables into
592    partitions constrained by the interference graph.  The overall
593    algorithm used is as follows:
594
595         Sort the objects by size in descending order.
596         For each object A {
597           S = size(A)
598           O = 0
599           loop {
600             Look for the largest non-conflicting object B with size <= S.
601             UNION (A, B)
602           }
603         }
604 */
605
606 static void
607 partition_stack_vars (void)
608 {
609   size_t si, sj, n = stack_vars_num;
610
611   stack_vars_sorted = XNEWVEC (size_t, stack_vars_num);
612   for (si = 0; si < n; ++si)
613     stack_vars_sorted[si] = si;
614
615   if (n == 1)
616     return;
617
618   qsort (stack_vars_sorted, n, sizeof (size_t), stack_var_cmp);
619
620   for (si = 0; si < n; ++si)
621     {
622       size_t i = stack_vars_sorted[si];
623       unsigned int ialign = stack_vars[i].alignb;
624
625       /* Ignore objects that aren't partition representatives. If we
626          see a var that is not a partition representative, it must
627          have been merged earlier.  */
628       if (stack_vars[i].representative != i)
629         continue;
630
631       for (sj = si + 1; sj < n; ++sj)
632         {
633           size_t j = stack_vars_sorted[sj];
634           unsigned int jalign = stack_vars[j].alignb;
635
636           /* Ignore objects that aren't partition representatives.  */
637           if (stack_vars[j].representative != j)
638             continue;
639
640           /* Ignore conflicting objects.  */
641           if (stack_var_conflict_p (i, j))
642             continue;
643
644           /* Do not mix objects of "small" (supported) alignment
645              and "large" (unsupported) alignment.  */
646           if ((ialign * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
647               != (jalign * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT))
648             continue;
649
650           /* UNION the objects, placing J at OFFSET.  */
651           union_stack_vars (i, j);
652         }
653     }
654
655   update_alias_info_with_stack_vars ();
656 }
657
658 /* A debugging aid for expand_used_vars.  Dump the generated partitions.  */
659
660 static void
661 dump_stack_var_partition (void)
662 {
663   size_t si, i, j, n = stack_vars_num;
664
665   for (si = 0; si < n; ++si)
666     {
667       i = stack_vars_sorted[si];
668
669       /* Skip variables that aren't partition representatives, for now.  */
670       if (stack_vars[i].representative != i)
671         continue;
672
673       fprintf (dump_file, "Partition %lu: size " HOST_WIDE_INT_PRINT_DEC
674                " align %u\n", (unsigned long) i, stack_vars[i].size,
675                stack_vars[i].alignb);
676
677       for (j = i; j != EOC; j = stack_vars[j].next)
678         {
679           fputc ('\t', dump_file);
680           print_generic_expr (dump_file, stack_vars[j].decl, dump_flags);
681         }
682       fputc ('\n', dump_file);
683     }
684 }
685
686 /* Assign rtl to DECL at BASE + OFFSET.  */
687
688 static void
689 expand_one_stack_var_at (tree decl, rtx base, unsigned base_align,
690                          HOST_WIDE_INT offset)
691 {
692   unsigned align;
693   rtx x;
694
695   /* If this fails, we've overflowed the stack frame.  Error nicely?  */
696   gcc_assert (offset == trunc_int_for_mode (offset, Pmode));
697
698   x = plus_constant (base, offset);
699   x = gen_rtx_MEM (DECL_MODE (SSAVAR (decl)), x);
700
701   if (TREE_CODE (decl) != SSA_NAME)
702     {
703       /* Set alignment we actually gave this decl if it isn't an SSA name.
704          If it is we generate stack slots only accidentally so it isn't as
705          important, we'll simply use the alignment that is already set.  */
706       if (base == virtual_stack_vars_rtx)
707         offset -= frame_phase;
708       align = offset & -offset;
709       align *= BITS_PER_UNIT;
710       if (align == 0 || align > base_align)
711         align = base_align;
712
713       /* One would think that we could assert that we're not decreasing
714          alignment here, but (at least) the i386 port does exactly this
715          via the MINIMUM_ALIGNMENT hook.  */
716
717       DECL_ALIGN (decl) = align;
718       DECL_USER_ALIGN (decl) = 0;
719     }
720
721   set_mem_attributes (x, SSAVAR (decl), true);
722   set_rtl (decl, x);
723 }
724
725 /* A subroutine of expand_used_vars.  Give each partition representative
726    a unique location within the stack frame.  Update each partition member
727    with that location.  */
728
729 static void
730 expand_stack_vars (bool (*pred) (tree))
731 {
732   size_t si, i, j, n = stack_vars_num;
733   HOST_WIDE_INT large_size = 0, large_alloc = 0;
734   rtx large_base = NULL;
735   unsigned large_align = 0;
736   tree decl;
737
738   /* Determine if there are any variables requiring "large" alignment.
739      Since these are dynamically allocated, we only process these if
740      no predicate involved.  */
741   large_align = stack_vars[stack_vars_sorted[0]].alignb * BITS_PER_UNIT;
742   if (pred == NULL && large_align > MAX_SUPPORTED_STACK_ALIGNMENT)
743     {
744       /* Find the total size of these variables.  */
745       for (si = 0; si < n; ++si)
746         {
747           unsigned alignb;
748
749           i = stack_vars_sorted[si];
750           alignb = stack_vars[i].alignb;
751
752           /* Stop when we get to the first decl with "small" alignment.  */
753           if (alignb * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
754             break;
755
756           /* Skip variables that aren't partition representatives.  */
757           if (stack_vars[i].representative != i)
758             continue;
759
760           /* Skip variables that have already had rtl assigned.  See also
761              add_stack_var where we perpetrate this pc_rtx hack.  */
762           decl = stack_vars[i].decl;
763           if ((TREE_CODE (decl) == SSA_NAME
764               ? SA.partition_to_pseudo[var_to_partition (SA.map, decl)]
765               : DECL_RTL (decl)) != pc_rtx)
766             continue;
767
768           large_size += alignb - 1;
769           large_size &= -(HOST_WIDE_INT)alignb;
770           large_size += stack_vars[i].size;
771         }
772
773       /* If there were any, allocate space.  */
774       if (large_size > 0)
775         large_base = allocate_dynamic_stack_space (GEN_INT (large_size), 0,
776                                                    large_align, true);
777     }
778
779   for (si = 0; si < n; ++si)
780     {
781       rtx base;
782       unsigned base_align, alignb;
783       HOST_WIDE_INT offset;
784
785       i = stack_vars_sorted[si];
786
787       /* Skip variables that aren't partition representatives, for now.  */
788       if (stack_vars[i].representative != i)
789         continue;
790
791       /* Skip variables that have already had rtl assigned.  See also
792          add_stack_var where we perpetrate this pc_rtx hack.  */
793       decl = stack_vars[i].decl;
794       if ((TREE_CODE (decl) == SSA_NAME
795            ? SA.partition_to_pseudo[var_to_partition (SA.map, decl)]
796            : DECL_RTL (decl)) != pc_rtx)
797         continue;
798
799       /* Check the predicate to see whether this variable should be
800          allocated in this pass.  */
801       if (pred && !pred (decl))
802         continue;
803
804       alignb = stack_vars[i].alignb;
805       if (alignb * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
806         {
807           offset = alloc_stack_frame_space (stack_vars[i].size, alignb);
808           base = virtual_stack_vars_rtx;
809           base_align = crtl->max_used_stack_slot_alignment;
810         }
811       else
812         {
813           /* Large alignment is only processed in the last pass.  */
814           if (pred)
815             continue;
816           gcc_assert (large_base != NULL);
817
818           large_alloc += alignb - 1;
819           large_alloc &= -(HOST_WIDE_INT)alignb;
820           offset = large_alloc;
821           large_alloc += stack_vars[i].size;
822
823           base = large_base;
824           base_align = large_align;
825         }
826
827       /* Create rtl for each variable based on their location within the
828          partition.  */
829       for (j = i; j != EOC; j = stack_vars[j].next)
830         {
831           expand_one_stack_var_at (stack_vars[j].decl,
832                                    base, base_align,
833                                    offset);
834         }
835     }
836
837   gcc_assert (large_alloc == large_size);
838 }
839
840 /* Take into account all sizes of partitions and reset DECL_RTLs.  */
841 static HOST_WIDE_INT
842 account_stack_vars (void)
843 {
844   size_t si, j, i, n = stack_vars_num;
845   HOST_WIDE_INT size = 0;
846
847   for (si = 0; si < n; ++si)
848     {
849       i = stack_vars_sorted[si];
850
851       /* Skip variables that aren't partition representatives, for now.  */
852       if (stack_vars[i].representative != i)
853         continue;
854
855       size += stack_vars[i].size;
856       for (j = i; j != EOC; j = stack_vars[j].next)
857         set_rtl (stack_vars[j].decl, NULL);
858     }
859   return size;
860 }
861
862 /* A subroutine of expand_one_var.  Called to immediately assign rtl
863    to a variable to be allocated in the stack frame.  */
864
865 static void
866 expand_one_stack_var (tree var)
867 {
868   HOST_WIDE_INT size, offset;
869   unsigned byte_align;
870
871   size = tree_low_cst (DECL_SIZE_UNIT (SSAVAR (var)), 1);
872   byte_align = align_local_variable (SSAVAR (var));
873
874   /* We handle highly aligned variables in expand_stack_vars.  */
875   gcc_assert (byte_align * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT);
876
877   offset = alloc_stack_frame_space (size, byte_align);
878
879   expand_one_stack_var_at (var, virtual_stack_vars_rtx,
880                            crtl->max_used_stack_slot_alignment, offset);
881 }
882
883 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
884    that will reside in a hard register.  */
885
886 static void
887 expand_one_hard_reg_var (tree var)
888 {
889   rest_of_decl_compilation (var, 0, 0);
890 }
891
892 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
893    that will reside in a pseudo register.  */
894
895 static void
896 expand_one_register_var (tree var)
897 {
898   tree decl = SSAVAR (var);
899   tree type = TREE_TYPE (decl);
900   enum machine_mode reg_mode = promote_decl_mode (decl, NULL);
901   rtx x = gen_reg_rtx (reg_mode);
902
903   set_rtl (var, x);
904
905   /* Note if the object is a user variable.  */
906   if (!DECL_ARTIFICIAL (decl))
907     mark_user_reg (x);
908
909   if (POINTER_TYPE_P (type))
910     mark_reg_pointer (x, TYPE_ALIGN (TREE_TYPE (type)));
911 }
912
913 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL that
914    has some associated error, e.g. its type is error-mark.  We just need
915    to pick something that won't crash the rest of the compiler.  */
916
917 static void
918 expand_one_error_var (tree var)
919 {
920   enum machine_mode mode = DECL_MODE (var);
921   rtx x;
922
923   if (mode == BLKmode)
924     x = gen_rtx_MEM (BLKmode, const0_rtx);
925   else if (mode == VOIDmode)
926     x = const0_rtx;
927   else
928     x = gen_reg_rtx (mode);
929
930   SET_DECL_RTL (var, x);
931 }
932
933 /* A subroutine of expand_one_var.  VAR is a variable that will be
934    allocated to the local stack frame.  Return true if we wish to
935    add VAR to STACK_VARS so that it will be coalesced with other
936    variables.  Return false to allocate VAR immediately.
937
938    This function is used to reduce the number of variables considered
939    for coalescing, which reduces the size of the quadratic problem.  */
940
941 static bool
942 defer_stack_allocation (tree var, bool toplevel)
943 {
944   /* If stack protection is enabled, *all* stack variables must be deferred,
945      so that we can re-order the strings to the top of the frame.  */
946   if (flag_stack_protect)
947     return true;
948
949   /* We handle "large" alignment via dynamic allocation.  We want to handle
950      this extra complication in only one place, so defer them.  */
951   if (DECL_ALIGN (var) > MAX_SUPPORTED_STACK_ALIGNMENT)
952     return true;
953
954   /* Variables in the outermost scope automatically conflict with
955      every other variable.  The only reason to want to defer them
956      at all is that, after sorting, we can more efficiently pack
957      small variables in the stack frame.  Continue to defer at -O2.  */
958   if (toplevel && optimize < 2)
959     return false;
960
961   /* Without optimization, *most* variables are allocated from the
962      stack, which makes the quadratic problem large exactly when we
963      want compilation to proceed as quickly as possible.  On the
964      other hand, we don't want the function's stack frame size to
965      get completely out of hand.  So we avoid adding scalars and
966      "small" aggregates to the list at all.  */
967   if (optimize == 0 && tree_low_cst (DECL_SIZE_UNIT (var), 1) < 32)
968     return false;
969
970   return true;
971 }
972
973 /* A subroutine of expand_used_vars.  Expand one variable according to
974    its flavor.  Variables to be placed on the stack are not actually
975    expanded yet, merely recorded.
976    When REALLY_EXPAND is false, only add stack values to be allocated.
977    Return stack usage this variable is supposed to take.
978 */
979
980 static HOST_WIDE_INT
981 expand_one_var (tree var, bool toplevel, bool really_expand)
982 {
983   unsigned int align = BITS_PER_UNIT;
984   tree origvar = var;
985
986   var = SSAVAR (var);
987
988   if (TREE_TYPE (var) != error_mark_node && TREE_CODE (var) == VAR_DECL)
989     {
990       /* Because we don't know if VAR will be in register or on stack,
991          we conservatively assume it will be on stack even if VAR is
992          eventually put into register after RA pass.  For non-automatic
993          variables, which won't be on stack, we collect alignment of
994          type and ignore user specified alignment.  */
995       if (TREE_STATIC (var) || DECL_EXTERNAL (var))
996         align = MINIMUM_ALIGNMENT (TREE_TYPE (var),
997                                    TYPE_MODE (TREE_TYPE (var)),
998                                    TYPE_ALIGN (TREE_TYPE (var)));
999       else if (DECL_HAS_VALUE_EXPR_P (var)
1000                || (DECL_RTL_SET_P (var) && MEM_P (DECL_RTL (var))))
1001         /* Don't consider debug only variables with DECL_HAS_VALUE_EXPR_P set
1002            or variables which were assigned a stack slot already by
1003            expand_one_stack_var_at - in the latter case DECL_ALIGN has been
1004            changed from the offset chosen to it.  */
1005         align = crtl->stack_alignment_estimated;
1006       else
1007         align = MINIMUM_ALIGNMENT (var, DECL_MODE (var), DECL_ALIGN (var));
1008
1009       /* If the variable alignment is very large we'll dynamicaly allocate
1010          it, which means that in-frame portion is just a pointer.  */
1011       if (align > MAX_SUPPORTED_STACK_ALIGNMENT)
1012         align = POINTER_SIZE;
1013     }
1014
1015   if (SUPPORTS_STACK_ALIGNMENT
1016       && crtl->stack_alignment_estimated < align)
1017     {
1018       /* stack_alignment_estimated shouldn't change after stack
1019          realign decision made */
1020       gcc_assert(!crtl->stack_realign_processed);
1021       crtl->stack_alignment_estimated = align;
1022     }
1023
1024   /* stack_alignment_needed > PREFERRED_STACK_BOUNDARY is permitted.
1025      So here we only make sure stack_alignment_needed >= align.  */
1026   if (crtl->stack_alignment_needed < align)
1027     crtl->stack_alignment_needed = align;
1028   if (crtl->max_used_stack_slot_alignment < align)
1029     crtl->max_used_stack_slot_alignment = align;
1030
1031   if (TREE_CODE (origvar) == SSA_NAME)
1032     {
1033       gcc_assert (TREE_CODE (var) != VAR_DECL
1034                   || (!DECL_EXTERNAL (var)
1035                       && !DECL_HAS_VALUE_EXPR_P (var)
1036                       && !TREE_STATIC (var)
1037                       && TREE_TYPE (var) != error_mark_node
1038                       && !DECL_HARD_REGISTER (var)
1039                       && really_expand));
1040     }
1041   if (TREE_CODE (var) != VAR_DECL && TREE_CODE (origvar) != SSA_NAME)
1042     ;
1043   else if (DECL_EXTERNAL (var))
1044     ;
1045   else if (DECL_HAS_VALUE_EXPR_P (var))
1046     ;
1047   else if (TREE_STATIC (var))
1048     ;
1049   else if (TREE_CODE (origvar) != SSA_NAME && DECL_RTL_SET_P (var))
1050     ;
1051   else if (TREE_TYPE (var) == error_mark_node)
1052     {
1053       if (really_expand)
1054         expand_one_error_var (var);
1055     }
1056   else if (TREE_CODE (var) == VAR_DECL && DECL_HARD_REGISTER (var))
1057     {
1058       if (really_expand)
1059         expand_one_hard_reg_var (var);
1060     }
1061   else if (use_register_for_decl (var))
1062     {
1063       if (really_expand)
1064         expand_one_register_var (origvar);
1065     }
1066   else if (!host_integerp (DECL_SIZE_UNIT (var), 1))
1067     {
1068       if (really_expand)
1069         {
1070           error ("size of variable %q+D is too large", var);
1071           expand_one_error_var (var);
1072         }
1073     }
1074   else if (defer_stack_allocation (var, toplevel))
1075     add_stack_var (origvar);
1076   else
1077     {
1078       if (really_expand)
1079         expand_one_stack_var (origvar);
1080       return tree_low_cst (DECL_SIZE_UNIT (var), 1);
1081     }
1082   return 0;
1083 }
1084
1085 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
1086    expanding variables.  Those variables that can be put into registers
1087    are allocated pseudos; those that can't are put on the stack.
1088
1089    TOPLEVEL is true if this is the outermost BLOCK.  */
1090
1091 static void
1092 expand_used_vars_for_block (tree block, bool toplevel)
1093 {
1094   size_t i, j, old_sv_num, this_sv_num, new_sv_num;
1095   tree t;
1096
1097   old_sv_num = toplevel ? 0 : stack_vars_num;
1098
1099   /* Expand all variables at this level.  */
1100   for (t = BLOCK_VARS (block); t ; t = DECL_CHAIN (t))
1101     if (TREE_USED (t))
1102       expand_one_var (t, toplevel, true);
1103
1104   this_sv_num = stack_vars_num;
1105
1106   /* Expand all variables at containing levels.  */
1107   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
1108     expand_used_vars_for_block (t, false);
1109
1110   /* Since we do not track exact variable lifetimes (which is not even
1111      possible for variables whose address escapes), we mirror the block
1112      tree in the interference graph.  Here we cause all variables at this
1113      level, and all sublevels, to conflict.  */
1114   if (old_sv_num < this_sv_num)
1115     {
1116       new_sv_num = stack_vars_num;
1117
1118       for (i = old_sv_num; i < new_sv_num; ++i)
1119         for (j = i < this_sv_num ? i : this_sv_num; j-- > old_sv_num ;)
1120           add_stack_var_conflict (i, j);
1121     }
1122 }
1123
1124 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
1125    and clear TREE_USED on all local variables.  */
1126
1127 static void
1128 clear_tree_used (tree block)
1129 {
1130   tree t;
1131
1132   for (t = BLOCK_VARS (block); t ; t = DECL_CHAIN (t))
1133     /* if (!TREE_STATIC (t) && !DECL_EXTERNAL (t)) */
1134       TREE_USED (t) = 0;
1135
1136   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
1137     clear_tree_used (t);
1138 }
1139
1140 /* Examine TYPE and determine a bit mask of the following features.  */
1141
1142 #define SPCT_HAS_LARGE_CHAR_ARRAY       1
1143 #define SPCT_HAS_SMALL_CHAR_ARRAY       2
1144 #define SPCT_HAS_ARRAY                  4
1145 #define SPCT_HAS_AGGREGATE              8
1146
1147 static unsigned int
1148 stack_protect_classify_type (tree type)
1149 {
1150   unsigned int ret = 0;
1151   tree t;
1152
1153   switch (TREE_CODE (type))
1154     {
1155     case ARRAY_TYPE:
1156       t = TYPE_MAIN_VARIANT (TREE_TYPE (type));
1157       if (t == char_type_node
1158           || t == signed_char_type_node
1159           || t == unsigned_char_type_node)
1160         {
1161           unsigned HOST_WIDE_INT max = PARAM_VALUE (PARAM_SSP_BUFFER_SIZE);
1162           unsigned HOST_WIDE_INT len;
1163
1164           if (!TYPE_SIZE_UNIT (type)
1165               || !host_integerp (TYPE_SIZE_UNIT (type), 1))
1166             len = max;
1167           else
1168             len = tree_low_cst (TYPE_SIZE_UNIT (type), 1);
1169
1170           if (len < max)
1171             ret = SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_ARRAY;
1172           else
1173             ret = SPCT_HAS_LARGE_CHAR_ARRAY | SPCT_HAS_ARRAY;
1174         }
1175       else
1176         ret = SPCT_HAS_ARRAY;
1177       break;
1178
1179     case UNION_TYPE:
1180     case QUAL_UNION_TYPE:
1181     case RECORD_TYPE:
1182       ret = SPCT_HAS_AGGREGATE;
1183       for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
1184         if (TREE_CODE (t) == FIELD_DECL)
1185           ret |= stack_protect_classify_type (TREE_TYPE (t));
1186       break;
1187
1188     default:
1189       break;
1190     }
1191
1192   return ret;
1193 }
1194
1195 /* Return nonzero if DECL should be segregated into the "vulnerable" upper
1196    part of the local stack frame.  Remember if we ever return nonzero for
1197    any variable in this function.  The return value is the phase number in
1198    which the variable should be allocated.  */
1199
1200 static int
1201 stack_protect_decl_phase (tree decl)
1202 {
1203   unsigned int bits = stack_protect_classify_type (TREE_TYPE (decl));
1204   int ret = 0;
1205
1206   if (bits & SPCT_HAS_SMALL_CHAR_ARRAY)
1207     has_short_buffer = true;
1208
1209   if (flag_stack_protect == 2)
1210     {
1211       if ((bits & (SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_LARGE_CHAR_ARRAY))
1212           && !(bits & SPCT_HAS_AGGREGATE))
1213         ret = 1;
1214       else if (bits & SPCT_HAS_ARRAY)
1215         ret = 2;
1216     }
1217   else
1218     ret = (bits & SPCT_HAS_LARGE_CHAR_ARRAY) != 0;
1219
1220   if (ret)
1221     has_protected_decls = true;
1222
1223   return ret;
1224 }
1225
1226 /* Two helper routines that check for phase 1 and phase 2.  These are used
1227    as callbacks for expand_stack_vars.  */
1228
1229 static bool
1230 stack_protect_decl_phase_1 (tree decl)
1231 {
1232   return stack_protect_decl_phase (decl) == 1;
1233 }
1234
1235 static bool
1236 stack_protect_decl_phase_2 (tree decl)
1237 {
1238   return stack_protect_decl_phase (decl) == 2;
1239 }
1240
1241 /* Ensure that variables in different stack protection phases conflict
1242    so that they are not merged and share the same stack slot.  */
1243
1244 static void
1245 add_stack_protection_conflicts (void)
1246 {
1247   size_t i, j, n = stack_vars_num;
1248   unsigned char *phase;
1249
1250   phase = XNEWVEC (unsigned char, n);
1251   for (i = 0; i < n; ++i)
1252     phase[i] = stack_protect_decl_phase (stack_vars[i].decl);
1253
1254   for (i = 0; i < n; ++i)
1255     {
1256       unsigned char ph_i = phase[i];
1257       for (j = 0; j < i; ++j)
1258         if (ph_i != phase[j])
1259           add_stack_var_conflict (i, j);
1260     }
1261
1262   XDELETEVEC (phase);
1263 }
1264
1265 /* Create a decl for the guard at the top of the stack frame.  */
1266
1267 static void
1268 create_stack_guard (void)
1269 {
1270   tree guard = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
1271                            VAR_DECL, NULL, ptr_type_node);
1272   TREE_THIS_VOLATILE (guard) = 1;
1273   TREE_USED (guard) = 1;
1274   expand_one_stack_var (guard);
1275   crtl->stack_protect_guard = guard;
1276 }
1277
1278 /* Prepare for expanding variables.  */
1279 static void
1280 init_vars_expansion (void)
1281 {
1282   tree t;
1283   unsigned ix;
1284   /* Set TREE_USED on all variables in the local_decls.  */
1285   FOR_EACH_LOCAL_DECL (cfun, ix, t)
1286     TREE_USED (t) = 1;
1287
1288   /* Clear TREE_USED on all variables associated with a block scope.  */
1289   clear_tree_used (DECL_INITIAL (current_function_decl));
1290
1291   /* Initialize local stack smashing state.  */
1292   has_protected_decls = false;
1293   has_short_buffer = false;
1294 }
1295
1296 /* Free up stack variable graph data.  */
1297 static void
1298 fini_vars_expansion (void)
1299 {
1300   size_t i, n = stack_vars_num;
1301   for (i = 0; i < n; i++)
1302     BITMAP_FREE (stack_vars[i].conflicts);
1303   XDELETEVEC (stack_vars);
1304   XDELETEVEC (stack_vars_sorted);
1305   stack_vars = NULL;
1306   stack_vars_alloc = stack_vars_num = 0;
1307 }
1308
1309 /* Make a fair guess for the size of the stack frame of the function
1310    in NODE.  This doesn't have to be exact, the result is only used in
1311    the inline heuristics.  So we don't want to run the full stack var
1312    packing algorithm (which is quadratic in the number of stack vars).
1313    Instead, we calculate the total size of all stack vars.  This turns
1314    out to be a pretty fair estimate -- packing of stack vars doesn't
1315    happen very often.  */
1316
1317 HOST_WIDE_INT
1318 estimated_stack_frame_size (struct cgraph_node *node)
1319 {
1320   HOST_WIDE_INT size = 0;
1321   size_t i;
1322   tree var;
1323   tree old_cur_fun_decl = current_function_decl;
1324   referenced_var_iterator rvi;
1325   struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
1326
1327   current_function_decl = node->decl;
1328   push_cfun (fn);
1329
1330   gcc_checking_assert (gimple_referenced_vars (fn));
1331   FOR_EACH_REFERENCED_VAR (fn, var, rvi)
1332     size += expand_one_var (var, true, false);
1333
1334   if (stack_vars_num > 0)
1335     {
1336       /* Fake sorting the stack vars for account_stack_vars ().  */
1337       stack_vars_sorted = XNEWVEC (size_t, stack_vars_num);
1338       for (i = 0; i < stack_vars_num; ++i)
1339         stack_vars_sorted[i] = i;
1340       size += account_stack_vars ();
1341       fini_vars_expansion ();
1342     }
1343   pop_cfun ();
1344   current_function_decl = old_cur_fun_decl;
1345   return size;
1346 }
1347
1348 /* Expand all variables used in the function.  */
1349
1350 static void
1351 expand_used_vars (void)
1352 {
1353   tree var, outer_block = DECL_INITIAL (current_function_decl);
1354   VEC(tree,heap) *maybe_local_decls = NULL;
1355   unsigned i;
1356   unsigned len;
1357
1358   /* Compute the phase of the stack frame for this function.  */
1359   {
1360     int align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
1361     int off = STARTING_FRAME_OFFSET % align;
1362     frame_phase = off ? align - off : 0;
1363   }
1364
1365   init_vars_expansion ();
1366
1367   for (i = 0; i < SA.map->num_partitions; i++)
1368     {
1369       tree var = partition_to_var (SA.map, i);
1370
1371       gcc_assert (is_gimple_reg (var));
1372       if (TREE_CODE (SSA_NAME_VAR (var)) == VAR_DECL)
1373         expand_one_var (var, true, true);
1374       else
1375         {
1376           /* This is a PARM_DECL or RESULT_DECL.  For those partitions that
1377              contain the default def (representing the parm or result itself)
1378              we don't do anything here.  But those which don't contain the
1379              default def (representing a temporary based on the parm/result)
1380              we need to allocate space just like for normal VAR_DECLs.  */
1381           if (!bitmap_bit_p (SA.partition_has_default_def, i))
1382             {
1383               expand_one_var (var, true, true);
1384               gcc_assert (SA.partition_to_pseudo[i]);
1385             }
1386         }
1387     }
1388
1389   /* At this point all variables on the local_decls with TREE_USED
1390      set are not associated with any block scope.  Lay them out.  */
1391
1392   len = VEC_length (tree, cfun->local_decls);
1393   FOR_EACH_LOCAL_DECL (cfun, i, var)
1394     {
1395       bool expand_now = false;
1396
1397       /* Expanded above already.  */
1398       if (is_gimple_reg (var))
1399         {
1400           TREE_USED (var) = 0;
1401           goto next;
1402         }
1403       /* We didn't set a block for static or extern because it's hard
1404          to tell the difference between a global variable (re)declared
1405          in a local scope, and one that's really declared there to
1406          begin with.  And it doesn't really matter much, since we're
1407          not giving them stack space.  Expand them now.  */
1408       else if (TREE_STATIC (var) || DECL_EXTERNAL (var))
1409         expand_now = true;
1410
1411       /* If the variable is not associated with any block, then it
1412          was created by the optimizers, and could be live anywhere
1413          in the function.  */
1414       else if (TREE_USED (var))
1415         expand_now = true;
1416
1417       /* Finally, mark all variables on the list as used.  We'll use
1418          this in a moment when we expand those associated with scopes.  */
1419       TREE_USED (var) = 1;
1420
1421       if (expand_now)
1422         expand_one_var (var, true, true);
1423
1424     next:
1425       if (DECL_ARTIFICIAL (var) && !DECL_IGNORED_P (var))
1426         {
1427           rtx rtl = DECL_RTL_IF_SET (var);
1428
1429           /* Keep artificial non-ignored vars in cfun->local_decls
1430              chain until instantiate_decls.  */
1431           if (rtl && (MEM_P (rtl) || GET_CODE (rtl) == CONCAT))
1432             add_local_decl (cfun, var);
1433           else if (rtl == NULL_RTX)
1434             /* If rtl isn't set yet, which can happen e.g. with
1435                -fstack-protector, retry before returning from this
1436                function.  */
1437             VEC_safe_push (tree, heap, maybe_local_decls, var);
1438         }
1439     }
1440
1441   /* We duplicated some of the decls in CFUN->LOCAL_DECLS.
1442
1443      +-----------------+-----------------+
1444      | ...processed... | ...duplicates...|
1445      +-----------------+-----------------+
1446                        ^
1447                        +-- LEN points here.
1448
1449      We just want the duplicates, as those are the artificial
1450      non-ignored vars that we want to keep until instantiate_decls.
1451      Move them down and truncate the array.  */
1452   if (!VEC_empty (tree, cfun->local_decls))
1453     VEC_block_remove (tree, cfun->local_decls, 0, len);
1454
1455   /* At this point, all variables within the block tree with TREE_USED
1456      set are actually used by the optimized function.  Lay them out.  */
1457   expand_used_vars_for_block (outer_block, true);
1458
1459   if (stack_vars_num > 0)
1460     {
1461       /* Due to the way alias sets work, no variables with non-conflicting
1462          alias sets may be assigned the same address.  Add conflicts to
1463          reflect this.  */
1464       add_alias_set_conflicts ();
1465
1466       /* If stack protection is enabled, we don't share space between
1467          vulnerable data and non-vulnerable data.  */
1468       if (flag_stack_protect)
1469         add_stack_protection_conflicts ();
1470
1471       /* Now that we have collected all stack variables, and have computed a
1472          minimal interference graph, attempt to save some stack space.  */
1473       partition_stack_vars ();
1474       if (dump_file)
1475         dump_stack_var_partition ();
1476     }
1477
1478   /* There are several conditions under which we should create a
1479      stack guard: protect-all, alloca used, protected decls present.  */
1480   if (flag_stack_protect == 2
1481       || (flag_stack_protect
1482           && (cfun->calls_alloca || has_protected_decls)))
1483     create_stack_guard ();
1484
1485   /* Assign rtl to each variable based on these partitions.  */
1486   if (stack_vars_num > 0)
1487     {
1488       /* Reorder decls to be protected by iterating over the variables
1489          array multiple times, and allocating out of each phase in turn.  */
1490       /* ??? We could probably integrate this into the qsort we did
1491          earlier, such that we naturally see these variables first,
1492          and thus naturally allocate things in the right order.  */
1493       if (has_protected_decls)
1494         {
1495           /* Phase 1 contains only character arrays.  */
1496           expand_stack_vars (stack_protect_decl_phase_1);
1497
1498           /* Phase 2 contains other kinds of arrays.  */
1499           if (flag_stack_protect == 2)
1500             expand_stack_vars (stack_protect_decl_phase_2);
1501         }
1502
1503       expand_stack_vars (NULL);
1504
1505       fini_vars_expansion ();
1506     }
1507
1508   /* If there were any artificial non-ignored vars without rtl
1509      found earlier, see if deferred stack allocation hasn't assigned
1510      rtl to them.  */
1511   FOR_EACH_VEC_ELT_REVERSE (tree, maybe_local_decls, i, var)
1512     {
1513       rtx rtl = DECL_RTL_IF_SET (var);
1514
1515       /* Keep artificial non-ignored vars in cfun->local_decls
1516          chain until instantiate_decls.  */
1517       if (rtl && (MEM_P (rtl) || GET_CODE (rtl) == CONCAT))
1518         add_local_decl (cfun, var);
1519     }
1520   VEC_free (tree, heap, maybe_local_decls);
1521
1522   /* If the target requires that FRAME_OFFSET be aligned, do it.  */
1523   if (STACK_ALIGNMENT_NEEDED)
1524     {
1525       HOST_WIDE_INT align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
1526       if (!FRAME_GROWS_DOWNWARD)
1527         frame_offset += align - 1;
1528       frame_offset &= -align;
1529     }
1530 }
1531
1532
1533 /* If we need to produce a detailed dump, print the tree representation
1534    for STMT to the dump file.  SINCE is the last RTX after which the RTL
1535    generated for STMT should have been appended.  */
1536
1537 static void
1538 maybe_dump_rtl_for_gimple_stmt (gimple stmt, rtx since)
1539 {
1540   if (dump_file && (dump_flags & TDF_DETAILS))
1541     {
1542       fprintf (dump_file, "\n;; ");
1543       print_gimple_stmt (dump_file, stmt, 0,
1544                          TDF_SLIM | (dump_flags & TDF_LINENO));
1545       fprintf (dump_file, "\n");
1546
1547       print_rtl (dump_file, since ? NEXT_INSN (since) : since);
1548     }
1549 }
1550
1551 /* Maps the blocks that do not contain tree labels to rtx labels.  */
1552
1553 static struct pointer_map_t *lab_rtx_for_bb;
1554
1555 /* Returns the label_rtx expression for a label starting basic block BB.  */
1556
1557 static rtx
1558 label_rtx_for_bb (basic_block bb ATTRIBUTE_UNUSED)
1559 {
1560   gimple_stmt_iterator gsi;
1561   tree lab;
1562   gimple lab_stmt;
1563   void **elt;
1564
1565   if (bb->flags & BB_RTL)
1566     return block_label (bb);
1567
1568   elt = pointer_map_contains (lab_rtx_for_bb, bb);
1569   if (elt)
1570     return (rtx) *elt;
1571
1572   /* Find the tree label if it is present.  */
1573
1574   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1575     {
1576       lab_stmt = gsi_stmt (gsi);
1577       if (gimple_code (lab_stmt) != GIMPLE_LABEL)
1578         break;
1579
1580       lab = gimple_label_label (lab_stmt);
1581       if (DECL_NONLOCAL (lab))
1582         break;
1583
1584       return label_rtx (lab);
1585     }
1586
1587   elt = pointer_map_insert (lab_rtx_for_bb, bb);
1588   *elt = gen_label_rtx ();
1589   return (rtx) *elt;
1590 }
1591
1592
1593 /* A subroutine of expand_gimple_cond.  Given E, a fallthrough edge
1594    of a basic block where we just expanded the conditional at the end,
1595    possibly clean up the CFG and instruction sequence.  LAST is the
1596    last instruction before the just emitted jump sequence.  */
1597
1598 static void
1599 maybe_cleanup_end_of_block (edge e, rtx last)
1600 {
1601   /* Special case: when jumpif decides that the condition is
1602      trivial it emits an unconditional jump (and the necessary
1603      barrier).  But we still have two edges, the fallthru one is
1604      wrong.  purge_dead_edges would clean this up later.  Unfortunately
1605      we have to insert insns (and split edges) before
1606      find_many_sub_basic_blocks and hence before purge_dead_edges.
1607      But splitting edges might create new blocks which depend on the
1608      fact that if there are two edges there's no barrier.  So the
1609      barrier would get lost and verify_flow_info would ICE.  Instead
1610      of auditing all edge splitters to care for the barrier (which
1611      normally isn't there in a cleaned CFG), fix it here.  */
1612   if (BARRIER_P (get_last_insn ()))
1613     {
1614       rtx insn;
1615       remove_edge (e);
1616       /* Now, we have a single successor block, if we have insns to
1617          insert on the remaining edge we potentially will insert
1618          it at the end of this block (if the dest block isn't feasible)
1619          in order to avoid splitting the edge.  This insertion will take
1620          place in front of the last jump.  But we might have emitted
1621          multiple jumps (conditional and one unconditional) to the
1622          same destination.  Inserting in front of the last one then
1623          is a problem.  See PR 40021.  We fix this by deleting all
1624          jumps except the last unconditional one.  */
1625       insn = PREV_INSN (get_last_insn ());
1626       /* Make sure we have an unconditional jump.  Otherwise we're
1627          confused.  */
1628       gcc_assert (JUMP_P (insn) && !any_condjump_p (insn));
1629       for (insn = PREV_INSN (insn); insn != last;)
1630         {
1631           insn = PREV_INSN (insn);
1632           if (JUMP_P (NEXT_INSN (insn)))
1633             {
1634               if (!any_condjump_p (NEXT_INSN (insn)))
1635                 {
1636                   gcc_assert (BARRIER_P (NEXT_INSN (NEXT_INSN (insn))));
1637                   delete_insn (NEXT_INSN (NEXT_INSN (insn)));
1638                 }
1639               delete_insn (NEXT_INSN (insn));
1640             }
1641         }
1642     }
1643 }
1644
1645 /* A subroutine of expand_gimple_basic_block.  Expand one GIMPLE_COND.
1646    Returns a new basic block if we've terminated the current basic
1647    block and created a new one.  */
1648
1649 static basic_block
1650 expand_gimple_cond (basic_block bb, gimple stmt)
1651 {
1652   basic_block new_bb, dest;
1653   edge new_edge;
1654   edge true_edge;
1655   edge false_edge;
1656   rtx last2, last;
1657   enum tree_code code;
1658   tree op0, op1;
1659
1660   code = gimple_cond_code (stmt);
1661   op0 = gimple_cond_lhs (stmt);
1662   op1 = gimple_cond_rhs (stmt);
1663   /* We're sometimes presented with such code:
1664        D.123_1 = x < y;
1665        if (D.123_1 != 0)
1666          ...
1667      This would expand to two comparisons which then later might
1668      be cleaned up by combine.  But some pattern matchers like if-conversion
1669      work better when there's only one compare, so make up for this
1670      here as special exception if TER would have made the same change.  */
1671   if (gimple_cond_single_var_p (stmt)
1672       && SA.values
1673       && TREE_CODE (op0) == SSA_NAME
1674       && bitmap_bit_p (SA.values, SSA_NAME_VERSION (op0)))
1675     {
1676       gimple second = SSA_NAME_DEF_STMT (op0);
1677       if (gimple_code (second) == GIMPLE_ASSIGN)
1678         {
1679           enum tree_code code2 = gimple_assign_rhs_code (second);
1680           if (TREE_CODE_CLASS (code2) == tcc_comparison)
1681             {
1682               code = code2;
1683               op0 = gimple_assign_rhs1 (second);
1684               op1 = gimple_assign_rhs2 (second);
1685             }
1686           /* If jumps are cheap turn some more codes into
1687              jumpy sequences.  */
1688           else if (BRANCH_COST (optimize_insn_for_speed_p (), false) < 4)
1689             {
1690               if ((code2 == BIT_AND_EXPR
1691                    && TYPE_PRECISION (TREE_TYPE (op0)) == 1
1692                    && TREE_CODE (gimple_assign_rhs2 (second)) != INTEGER_CST)
1693                   || code2 == TRUTH_AND_EXPR)
1694                 {
1695                   code = TRUTH_ANDIF_EXPR;
1696                   op0 = gimple_assign_rhs1 (second);
1697                   op1 = gimple_assign_rhs2 (second);
1698                 }
1699               else if (code2 == BIT_IOR_EXPR || code2 == TRUTH_OR_EXPR)
1700                 {
1701                   code = TRUTH_ORIF_EXPR;
1702                   op0 = gimple_assign_rhs1 (second);
1703                   op1 = gimple_assign_rhs2 (second);
1704                 }
1705             }
1706         }
1707     }
1708
1709   last2 = last = get_last_insn ();
1710
1711   extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1712   set_curr_insn_source_location (gimple_location (stmt));
1713   set_curr_insn_block (gimple_block (stmt));
1714
1715   /* These flags have no purpose in RTL land.  */
1716   true_edge->flags &= ~EDGE_TRUE_VALUE;
1717   false_edge->flags &= ~EDGE_FALSE_VALUE;
1718
1719   /* We can either have a pure conditional jump with one fallthru edge or
1720      two-way jump that needs to be decomposed into two basic blocks.  */
1721   if (false_edge->dest == bb->next_bb)
1722     {
1723       jumpif_1 (code, op0, op1, label_rtx_for_bb (true_edge->dest),
1724                 true_edge->probability);
1725       maybe_dump_rtl_for_gimple_stmt (stmt, last);
1726       if (true_edge->goto_locus)
1727         {
1728           set_curr_insn_source_location (true_edge->goto_locus);
1729           set_curr_insn_block (true_edge->goto_block);
1730           true_edge->goto_locus = curr_insn_locator ();
1731         }
1732       true_edge->goto_block = NULL;
1733       false_edge->flags |= EDGE_FALLTHRU;
1734       maybe_cleanup_end_of_block (false_edge, last);
1735       return NULL;
1736     }
1737   if (true_edge->dest == bb->next_bb)
1738     {
1739       jumpifnot_1 (code, op0, op1, label_rtx_for_bb (false_edge->dest),
1740                    false_edge->probability);
1741       maybe_dump_rtl_for_gimple_stmt (stmt, last);
1742       if (false_edge->goto_locus)
1743         {
1744           set_curr_insn_source_location (false_edge->goto_locus);
1745           set_curr_insn_block (false_edge->goto_block);
1746           false_edge->goto_locus = curr_insn_locator ();
1747         }
1748       false_edge->goto_block = NULL;
1749       true_edge->flags |= EDGE_FALLTHRU;
1750       maybe_cleanup_end_of_block (true_edge, last);
1751       return NULL;
1752     }
1753
1754   jumpif_1 (code, op0, op1, label_rtx_for_bb (true_edge->dest),
1755             true_edge->probability);
1756   last = get_last_insn ();
1757   if (false_edge->goto_locus)
1758     {
1759       set_curr_insn_source_location (false_edge->goto_locus);
1760       set_curr_insn_block (false_edge->goto_block);
1761       false_edge->goto_locus = curr_insn_locator ();
1762     }
1763   false_edge->goto_block = NULL;
1764   emit_jump (label_rtx_for_bb (false_edge->dest));
1765
1766   BB_END (bb) = last;
1767   if (BARRIER_P (BB_END (bb)))
1768     BB_END (bb) = PREV_INSN (BB_END (bb));
1769   update_bb_for_insn (bb);
1770
1771   new_bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
1772   dest = false_edge->dest;
1773   redirect_edge_succ (false_edge, new_bb);
1774   false_edge->flags |= EDGE_FALLTHRU;
1775   new_bb->count = false_edge->count;
1776   new_bb->frequency = EDGE_FREQUENCY (false_edge);
1777   new_edge = make_edge (new_bb, dest, 0);
1778   new_edge->probability = REG_BR_PROB_BASE;
1779   new_edge->count = new_bb->count;
1780   if (BARRIER_P (BB_END (new_bb)))
1781     BB_END (new_bb) = PREV_INSN (BB_END (new_bb));
1782   update_bb_for_insn (new_bb);
1783
1784   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
1785
1786   if (true_edge->goto_locus)
1787     {
1788       set_curr_insn_source_location (true_edge->goto_locus);
1789       set_curr_insn_block (true_edge->goto_block);
1790       true_edge->goto_locus = curr_insn_locator ();
1791     }
1792   true_edge->goto_block = NULL;
1793
1794   return new_bb;
1795 }
1796
1797 /* A subroutine of expand_gimple_stmt_1, expanding one GIMPLE_CALL
1798    statement STMT.  */
1799
1800 static void
1801 expand_call_stmt (gimple stmt)
1802 {
1803   tree exp, decl, lhs;
1804   bool builtin_p;
1805   size_t i;
1806
1807   if (gimple_call_internal_p (stmt))
1808     {
1809       expand_internal_call (stmt);
1810       return;
1811     }
1812
1813   exp = build_vl_exp (CALL_EXPR, gimple_call_num_args (stmt) + 3);
1814
1815   CALL_EXPR_FN (exp) = gimple_call_fn (stmt);
1816   decl = gimple_call_fndecl (stmt);
1817   builtin_p = decl && DECL_BUILT_IN (decl);
1818
1819   /* If this is not a builtin function, the function type through which the
1820      call is made may be different from the type of the function.  */
1821   if (!builtin_p)
1822     CALL_EXPR_FN (exp)
1823       = fold_convert (build_pointer_type (gimple_call_fntype (stmt)),
1824                       CALL_EXPR_FN (exp));
1825
1826   TREE_TYPE (exp) = gimple_call_return_type (stmt);
1827   CALL_EXPR_STATIC_CHAIN (exp) = gimple_call_chain (stmt);
1828
1829   for (i = 0; i < gimple_call_num_args (stmt); i++)
1830     {
1831       tree arg = gimple_call_arg (stmt, i);
1832       gimple def;
1833       /* TER addresses into arguments of builtin functions so we have a
1834          chance to infer more correct alignment information.  See PR39954.  */
1835       if (builtin_p
1836           && TREE_CODE (arg) == SSA_NAME
1837           && (def = get_gimple_for_ssa_name (arg))
1838           && gimple_assign_rhs_code (def) == ADDR_EXPR)
1839         arg = gimple_assign_rhs1 (def);
1840       CALL_EXPR_ARG (exp, i) = arg;
1841     }
1842
1843   if (gimple_has_side_effects (stmt))
1844     TREE_SIDE_EFFECTS (exp) = 1;
1845
1846   if (gimple_call_nothrow_p (stmt))
1847     TREE_NOTHROW (exp) = 1;
1848
1849   CALL_EXPR_TAILCALL (exp) = gimple_call_tail_p (stmt);
1850   CALL_EXPR_RETURN_SLOT_OPT (exp) = gimple_call_return_slot_opt_p (stmt);
1851   if (decl
1852       && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
1853       && DECL_FUNCTION_CODE (decl) == BUILT_IN_ALLOCA)
1854     CALL_ALLOCA_FOR_VAR_P (exp) = gimple_call_alloca_for_var_p (stmt);
1855   else
1856     CALL_FROM_THUNK_P (exp) = gimple_call_from_thunk_p (stmt);
1857   CALL_CANNOT_INLINE_P (exp) = gimple_call_cannot_inline_p (stmt);
1858   CALL_EXPR_VA_ARG_PACK (exp) = gimple_call_va_arg_pack_p (stmt);
1859   SET_EXPR_LOCATION (exp, gimple_location (stmt));
1860   TREE_BLOCK (exp) = gimple_block (stmt);
1861
1862   lhs = gimple_call_lhs (stmt);
1863   if (lhs)
1864     expand_assignment (lhs, exp, false);
1865   else
1866     expand_expr_real_1 (exp, const0_rtx, VOIDmode, EXPAND_NORMAL, NULL);
1867 }
1868
1869 /* A subroutine of expand_gimple_stmt, expanding one gimple statement
1870    STMT that doesn't require special handling for outgoing edges.  That
1871    is no tailcalls and no GIMPLE_COND.  */
1872
1873 static void
1874 expand_gimple_stmt_1 (gimple stmt)
1875 {
1876   tree op0;
1877
1878   set_curr_insn_source_location (gimple_location (stmt));
1879   set_curr_insn_block (gimple_block (stmt));
1880
1881   switch (gimple_code (stmt))
1882     {
1883     case GIMPLE_GOTO:
1884       op0 = gimple_goto_dest (stmt);
1885       if (TREE_CODE (op0) == LABEL_DECL)
1886         expand_goto (op0);
1887       else
1888         expand_computed_goto (op0);
1889       break;
1890     case GIMPLE_LABEL:
1891       expand_label (gimple_label_label (stmt));
1892       break;
1893     case GIMPLE_NOP:
1894     case GIMPLE_PREDICT:
1895       break;
1896     case GIMPLE_SWITCH:
1897       expand_case (stmt);
1898       break;
1899     case GIMPLE_ASM:
1900       expand_asm_stmt (stmt);
1901       break;
1902     case GIMPLE_CALL:
1903       expand_call_stmt (stmt);
1904       break;
1905
1906     case GIMPLE_RETURN:
1907       op0 = gimple_return_retval (stmt);
1908
1909       if (op0 && op0 != error_mark_node)
1910         {
1911           tree result = DECL_RESULT (current_function_decl);
1912
1913           /* If we are not returning the current function's RESULT_DECL,
1914              build an assignment to it.  */
1915           if (op0 != result)
1916             {
1917               /* I believe that a function's RESULT_DECL is unique.  */
1918               gcc_assert (TREE_CODE (op0) != RESULT_DECL);
1919
1920               /* ??? We'd like to use simply expand_assignment here,
1921                  but this fails if the value is of BLKmode but the return
1922                  decl is a register.  expand_return has special handling
1923                  for this combination, which eventually should move
1924                  to common code.  See comments there.  Until then, let's
1925                  build a modify expression :-/  */
1926               op0 = build2 (MODIFY_EXPR, TREE_TYPE (result),
1927                             result, op0);
1928             }
1929         }
1930       if (!op0)
1931         expand_null_return ();
1932       else
1933         expand_return (op0);
1934       break;
1935
1936     case GIMPLE_ASSIGN:
1937       {
1938         tree lhs = gimple_assign_lhs (stmt);
1939
1940         /* Tree expand used to fiddle with |= and &= of two bitfield
1941            COMPONENT_REFs here.  This can't happen with gimple, the LHS
1942            of binary assigns must be a gimple reg.  */
1943
1944         if (TREE_CODE (lhs) != SSA_NAME
1945             || get_gimple_rhs_class (gimple_expr_code (stmt))
1946                == GIMPLE_SINGLE_RHS)
1947           {
1948             tree rhs = gimple_assign_rhs1 (stmt);
1949             gcc_assert (get_gimple_rhs_class (gimple_expr_code (stmt))
1950                         == GIMPLE_SINGLE_RHS);
1951             if (gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (rhs))
1952               SET_EXPR_LOCATION (rhs, gimple_location (stmt));
1953             expand_assignment (lhs, rhs,
1954                                gimple_assign_nontemporal_move_p (stmt));
1955           }
1956         else
1957           {
1958             rtx target, temp;
1959             bool nontemporal = gimple_assign_nontemporal_move_p (stmt);
1960             struct separate_ops ops;
1961             bool promoted = false;
1962
1963             target = expand_expr (lhs, NULL_RTX, VOIDmode, EXPAND_WRITE);
1964             if (GET_CODE (target) == SUBREG && SUBREG_PROMOTED_VAR_P (target))
1965               promoted = true;
1966
1967             ops.code = gimple_assign_rhs_code (stmt);
1968             ops.type = TREE_TYPE (lhs);
1969             switch (get_gimple_rhs_class (gimple_expr_code (stmt)))
1970               {
1971                 case GIMPLE_TERNARY_RHS:
1972                   ops.op2 = gimple_assign_rhs3 (stmt);
1973                   /* Fallthru */
1974                 case GIMPLE_BINARY_RHS:
1975                   ops.op1 = gimple_assign_rhs2 (stmt);
1976                   /* Fallthru */
1977                 case GIMPLE_UNARY_RHS:
1978                   ops.op0 = gimple_assign_rhs1 (stmt);
1979                   break;
1980                 default:
1981                   gcc_unreachable ();
1982               }
1983             ops.location = gimple_location (stmt);
1984
1985             /* If we want to use a nontemporal store, force the value to
1986                register first.  If we store into a promoted register,
1987                don't directly expand to target.  */
1988             temp = nontemporal || promoted ? NULL_RTX : target;
1989             temp = expand_expr_real_2 (&ops, temp, GET_MODE (target),
1990                                        EXPAND_NORMAL);
1991
1992             if (temp == target)
1993               ;
1994             else if (promoted)
1995               {
1996                 int unsignedp = SUBREG_PROMOTED_UNSIGNED_P (target);
1997                 /* If TEMP is a VOIDmode constant, use convert_modes to make
1998                    sure that we properly convert it.  */
1999                 if (CONSTANT_P (temp) && GET_MODE (temp) == VOIDmode)
2000                   {
2001                     temp = convert_modes (GET_MODE (target),
2002                                           TYPE_MODE (ops.type),
2003                                           temp, unsignedp);
2004                     temp = convert_modes (GET_MODE (SUBREG_REG (target)),
2005                                           GET_MODE (target), temp, unsignedp);
2006                   }
2007
2008                 convert_move (SUBREG_REG (target), temp, unsignedp);
2009               }
2010             else if (nontemporal && emit_storent_insn (target, temp))
2011               ;
2012             else
2013               {
2014                 temp = force_operand (temp, target);
2015                 if (temp != target)
2016                   emit_move_insn (target, temp);
2017               }
2018           }
2019       }
2020       break;
2021
2022     default:
2023       gcc_unreachable ();
2024     }
2025 }
2026
2027 /* Expand one gimple statement STMT and return the last RTL instruction
2028    before any of the newly generated ones.
2029
2030    In addition to generating the necessary RTL instructions this also
2031    sets REG_EH_REGION notes if necessary and sets the current source
2032    location for diagnostics.  */
2033
2034 static rtx
2035 expand_gimple_stmt (gimple stmt)
2036 {
2037   location_t saved_location = input_location;
2038   rtx last = get_last_insn ();
2039   int lp_nr;
2040
2041   gcc_assert (cfun);
2042
2043   /* We need to save and restore the current source location so that errors
2044      discovered during expansion are emitted with the right location.  But
2045      it would be better if the diagnostic routines used the source location
2046      embedded in the tree nodes rather than globals.  */
2047   if (gimple_has_location (stmt))
2048     input_location = gimple_location (stmt);
2049
2050   expand_gimple_stmt_1 (stmt);
2051
2052   /* Free any temporaries used to evaluate this statement.  */
2053   free_temp_slots ();
2054
2055   input_location = saved_location;
2056
2057   /* Mark all insns that may trap.  */
2058   lp_nr = lookup_stmt_eh_lp (stmt);
2059   if (lp_nr)
2060     {
2061       rtx insn;
2062       for (insn = next_real_insn (last); insn;
2063            insn = next_real_insn (insn))
2064         {
2065           if (! find_reg_note (insn, REG_EH_REGION, NULL_RTX)
2066               /* If we want exceptions for non-call insns, any
2067                  may_trap_p instruction may throw.  */
2068               && GET_CODE (PATTERN (insn)) != CLOBBER
2069               && GET_CODE (PATTERN (insn)) != USE
2070               && insn_could_throw_p (insn))
2071             make_reg_eh_region_note (insn, 0, lp_nr);
2072         }
2073     }
2074
2075   return last;
2076 }
2077
2078 /* A subroutine of expand_gimple_basic_block.  Expand one GIMPLE_CALL
2079    that has CALL_EXPR_TAILCALL set.  Returns non-null if we actually
2080    generated a tail call (something that might be denied by the ABI
2081    rules governing the call; see calls.c).
2082
2083    Sets CAN_FALLTHRU if we generated a *conditional* tail call, and
2084    can still reach the rest of BB.  The case here is __builtin_sqrt,
2085    where the NaN result goes through the external function (with a
2086    tailcall) and the normal result happens via a sqrt instruction.  */
2087
2088 static basic_block
2089 expand_gimple_tailcall (basic_block bb, gimple stmt, bool *can_fallthru)
2090 {
2091   rtx last2, last;
2092   edge e;
2093   edge_iterator ei;
2094   int probability;
2095   gcov_type count;
2096
2097   last2 = last = expand_gimple_stmt (stmt);
2098
2099   for (last = NEXT_INSN (last); last; last = NEXT_INSN (last))
2100     if (CALL_P (last) && SIBLING_CALL_P (last))
2101       goto found;
2102
2103   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
2104
2105   *can_fallthru = true;
2106   return NULL;
2107
2108  found:
2109   /* ??? Wouldn't it be better to just reset any pending stack adjust?
2110      Any instructions emitted here are about to be deleted.  */
2111   do_pending_stack_adjust ();
2112
2113   /* Remove any non-eh, non-abnormal edges that don't go to exit.  */
2114   /* ??? I.e. the fallthrough edge.  HOWEVER!  If there were to be
2115      EH or abnormal edges, we shouldn't have created a tail call in
2116      the first place.  So it seems to me we should just be removing
2117      all edges here, or redirecting the existing fallthru edge to
2118      the exit block.  */
2119
2120   probability = 0;
2121   count = 0;
2122
2123   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
2124     {
2125       if (!(e->flags & (EDGE_ABNORMAL | EDGE_EH)))
2126         {
2127           if (e->dest != EXIT_BLOCK_PTR)
2128             {
2129               e->dest->count -= e->count;
2130               e->dest->frequency -= EDGE_FREQUENCY (e);
2131               if (e->dest->count < 0)
2132                 e->dest->count = 0;
2133               if (e->dest->frequency < 0)
2134                 e->dest->frequency = 0;
2135             }
2136           count += e->count;
2137           probability += e->probability;
2138           remove_edge (e);
2139         }
2140       else
2141         ei_next (&ei);
2142     }
2143
2144   /* This is somewhat ugly: the call_expr expander often emits instructions
2145      after the sibcall (to perform the function return).  These confuse the
2146      find_many_sub_basic_blocks code, so we need to get rid of these.  */
2147   last = NEXT_INSN (last);
2148   gcc_assert (BARRIER_P (last));
2149
2150   *can_fallthru = false;
2151   while (NEXT_INSN (last))
2152     {
2153       /* For instance an sqrt builtin expander expands if with
2154          sibcall in the then and label for `else`.  */
2155       if (LABEL_P (NEXT_INSN (last)))
2156         {
2157           *can_fallthru = true;
2158           break;
2159         }
2160       delete_insn (NEXT_INSN (last));
2161     }
2162
2163   e = make_edge (bb, EXIT_BLOCK_PTR, EDGE_ABNORMAL | EDGE_SIBCALL);
2164   e->probability += probability;
2165   e->count += count;
2166   BB_END (bb) = last;
2167   update_bb_for_insn (bb);
2168
2169   if (NEXT_INSN (last))
2170     {
2171       bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
2172
2173       last = BB_END (bb);
2174       if (BARRIER_P (last))
2175         BB_END (bb) = PREV_INSN (last);
2176     }
2177
2178   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
2179
2180   return bb;
2181 }
2182
2183 /* Return the difference between the floor and the truncated result of
2184    a signed division by OP1 with remainder MOD.  */
2185 static rtx
2186 floor_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2187 {
2188   /* (mod != 0 ? (op1 / mod < 0 ? -1 : 0) : 0) */
2189   return gen_rtx_IF_THEN_ELSE
2190     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2191      gen_rtx_IF_THEN_ELSE
2192      (mode, gen_rtx_LT (BImode,
2193                         gen_rtx_DIV (mode, op1, mod),
2194                         const0_rtx),
2195       constm1_rtx, const0_rtx),
2196      const0_rtx);
2197 }
2198
2199 /* Return the difference between the ceil and the truncated result of
2200    a signed division by OP1 with remainder MOD.  */
2201 static rtx
2202 ceil_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2203 {
2204   /* (mod != 0 ? (op1 / mod > 0 ? 1 : 0) : 0) */
2205   return gen_rtx_IF_THEN_ELSE
2206     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2207      gen_rtx_IF_THEN_ELSE
2208      (mode, gen_rtx_GT (BImode,
2209                         gen_rtx_DIV (mode, op1, mod),
2210                         const0_rtx),
2211       const1_rtx, const0_rtx),
2212      const0_rtx);
2213 }
2214
2215 /* Return the difference between the ceil and the truncated result of
2216    an unsigned division by OP1 with remainder MOD.  */
2217 static rtx
2218 ceil_udiv_adjust (enum machine_mode mode, rtx mod, rtx op1 ATTRIBUTE_UNUSED)
2219 {
2220   /* (mod != 0 ? 1 : 0) */
2221   return gen_rtx_IF_THEN_ELSE
2222     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2223      const1_rtx, const0_rtx);
2224 }
2225
2226 /* Return the difference between the rounded and the truncated result
2227    of a signed division by OP1 with remainder MOD.  Halfway cases are
2228    rounded away from zero, rather than to the nearest even number.  */
2229 static rtx
2230 round_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2231 {
2232   /* (abs (mod) >= abs (op1) - abs (mod)
2233       ? (op1 / mod > 0 ? 1 : -1)
2234       : 0) */
2235   return gen_rtx_IF_THEN_ELSE
2236     (mode, gen_rtx_GE (BImode, gen_rtx_ABS (mode, mod),
2237                        gen_rtx_MINUS (mode,
2238                                       gen_rtx_ABS (mode, op1),
2239                                       gen_rtx_ABS (mode, mod))),
2240      gen_rtx_IF_THEN_ELSE
2241      (mode, gen_rtx_GT (BImode,
2242                         gen_rtx_DIV (mode, op1, mod),
2243                         const0_rtx),
2244       const1_rtx, constm1_rtx),
2245      const0_rtx);
2246 }
2247
2248 /* Return the difference between the rounded and the truncated result
2249    of a unsigned division by OP1 with remainder MOD.  Halfway cases
2250    are rounded away from zero, rather than to the nearest even
2251    number.  */
2252 static rtx
2253 round_udiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2254 {
2255   /* (mod >= op1 - mod ? 1 : 0) */
2256   return gen_rtx_IF_THEN_ELSE
2257     (mode, gen_rtx_GE (BImode, mod,
2258                        gen_rtx_MINUS (mode, op1, mod)),
2259      const1_rtx, const0_rtx);
2260 }
2261
2262 /* Convert X to MODE, that must be Pmode or ptr_mode, without emitting
2263    any rtl.  */
2264
2265 static rtx
2266 convert_debug_memory_address (enum machine_mode mode, rtx x,
2267                               addr_space_t as)
2268 {
2269   enum machine_mode xmode = GET_MODE (x);
2270
2271 #ifndef POINTERS_EXTEND_UNSIGNED
2272   gcc_assert (mode == Pmode
2273               || mode == targetm.addr_space.address_mode (as));
2274   gcc_assert (xmode == mode || xmode == VOIDmode);
2275 #else
2276   rtx temp;
2277   enum machine_mode address_mode = targetm.addr_space.address_mode (as);
2278   enum machine_mode pointer_mode = targetm.addr_space.pointer_mode (as);
2279
2280   gcc_assert (mode == address_mode || mode == pointer_mode);
2281
2282   if (GET_MODE (x) == mode || GET_MODE (x) == VOIDmode)
2283     return x;
2284
2285   if (GET_MODE_BITSIZE (mode) < GET_MODE_BITSIZE (xmode))
2286     x = simplify_gen_subreg (mode, x, xmode,
2287                              subreg_lowpart_offset
2288                              (mode, xmode));
2289   else if (POINTERS_EXTEND_UNSIGNED > 0)
2290     x = gen_rtx_ZERO_EXTEND (mode, x);
2291   else if (!POINTERS_EXTEND_UNSIGNED)
2292     x = gen_rtx_SIGN_EXTEND (mode, x);
2293   else
2294     {
2295       switch (GET_CODE (x))
2296         {
2297         case SUBREG:
2298           if ((SUBREG_PROMOTED_VAR_P (x)
2299                || (REG_P (SUBREG_REG (x)) && REG_POINTER (SUBREG_REG (x)))
2300                || (GET_CODE (SUBREG_REG (x)) == PLUS
2301                    && REG_P (XEXP (SUBREG_REG (x), 0))
2302                    && REG_POINTER (XEXP (SUBREG_REG (x), 0))
2303                    && CONST_INT_P (XEXP (SUBREG_REG (x), 1))))
2304               && GET_MODE (SUBREG_REG (x)) == mode)
2305             return SUBREG_REG (x);
2306           break;
2307         case LABEL_REF:
2308           temp = gen_rtx_LABEL_REF (mode, XEXP (x, 0));
2309           LABEL_REF_NONLOCAL_P (temp) = LABEL_REF_NONLOCAL_P (x);
2310           return temp;
2311         case SYMBOL_REF:
2312           temp = shallow_copy_rtx (x);
2313           PUT_MODE (temp, mode);
2314           return temp;
2315         case CONST:
2316           temp = convert_debug_memory_address (mode, XEXP (x, 0), as);
2317           if (temp)
2318             temp = gen_rtx_CONST (mode, temp);
2319           return temp;
2320         case PLUS:
2321         case MINUS:
2322           if (CONST_INT_P (XEXP (x, 1)))
2323             {
2324               temp = convert_debug_memory_address (mode, XEXP (x, 0), as);
2325               if (temp)
2326                 return gen_rtx_fmt_ee (GET_CODE (x), mode, temp, XEXP (x, 1));
2327             }
2328           break;
2329         default:
2330           break;
2331         }
2332       /* Don't know how to express ptr_extend as operation in debug info.  */
2333       return NULL;
2334     }
2335 #endif /* POINTERS_EXTEND_UNSIGNED */
2336
2337   return x;
2338 }
2339
2340 /* Return an RTX equivalent to the value of the tree expression
2341    EXP.  */
2342
2343 static rtx
2344 expand_debug_expr (tree exp)
2345 {
2346   rtx op0 = NULL_RTX, op1 = NULL_RTX, op2 = NULL_RTX;
2347   enum machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
2348   enum machine_mode inner_mode = VOIDmode;
2349   int unsignedp = TYPE_UNSIGNED (TREE_TYPE (exp));
2350   addr_space_t as;
2351
2352   switch (TREE_CODE_CLASS (TREE_CODE (exp)))
2353     {
2354     case tcc_expression:
2355       switch (TREE_CODE (exp))
2356         {
2357         case COND_EXPR:
2358         case DOT_PROD_EXPR:
2359         case WIDEN_MULT_PLUS_EXPR:
2360         case WIDEN_MULT_MINUS_EXPR:
2361         case FMA_EXPR:
2362           goto ternary;
2363
2364         case TRUTH_ANDIF_EXPR:
2365         case TRUTH_ORIF_EXPR:
2366         case TRUTH_AND_EXPR:
2367         case TRUTH_OR_EXPR:
2368         case TRUTH_XOR_EXPR:
2369           goto binary;
2370
2371         case TRUTH_NOT_EXPR:
2372           goto unary;
2373
2374         default:
2375           break;
2376         }
2377       break;
2378
2379     ternary:
2380       op2 = expand_debug_expr (TREE_OPERAND (exp, 2));
2381       if (!op2)
2382         return NULL_RTX;
2383       /* Fall through.  */
2384
2385     binary:
2386     case tcc_binary:
2387     case tcc_comparison:
2388       op1 = expand_debug_expr (TREE_OPERAND (exp, 1));
2389       if (!op1)
2390         return NULL_RTX;
2391       /* Fall through.  */
2392
2393     unary:
2394     case tcc_unary:
2395       inner_mode = TYPE_MODE (TREE_TYPE (TREE_OPERAND (exp, 0)));
2396       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
2397       if (!op0)
2398         return NULL_RTX;
2399       break;
2400
2401     case tcc_type:
2402     case tcc_statement:
2403       gcc_unreachable ();
2404
2405     case tcc_constant:
2406     case tcc_exceptional:
2407     case tcc_declaration:
2408     case tcc_reference:
2409     case tcc_vl_exp:
2410       break;
2411     }
2412
2413   switch (TREE_CODE (exp))
2414     {
2415     case STRING_CST:
2416       if (!lookup_constant_def (exp))
2417         {
2418           if (strlen (TREE_STRING_POINTER (exp)) + 1
2419               != (size_t) TREE_STRING_LENGTH (exp))
2420             return NULL_RTX;
2421           op0 = gen_rtx_CONST_STRING (Pmode, TREE_STRING_POINTER (exp));
2422           op0 = gen_rtx_MEM (BLKmode, op0);
2423           set_mem_attributes (op0, exp, 0);
2424           return op0;
2425         }
2426       /* Fall through...  */
2427
2428     case INTEGER_CST:
2429     case REAL_CST:
2430     case FIXED_CST:
2431       op0 = expand_expr (exp, NULL_RTX, mode, EXPAND_INITIALIZER);
2432       return op0;
2433
2434     case COMPLEX_CST:
2435       gcc_assert (COMPLEX_MODE_P (mode));
2436       op0 = expand_debug_expr (TREE_REALPART (exp));
2437       op1 = expand_debug_expr (TREE_IMAGPART (exp));
2438       return gen_rtx_CONCAT (mode, op0, op1);
2439
2440     case DEBUG_EXPR_DECL:
2441       op0 = DECL_RTL_IF_SET (exp);
2442
2443       if (op0)
2444         return op0;
2445
2446       op0 = gen_rtx_DEBUG_EXPR (mode);
2447       DEBUG_EXPR_TREE_DECL (op0) = exp;
2448       SET_DECL_RTL (exp, op0);
2449
2450       return op0;
2451
2452     case VAR_DECL:
2453     case PARM_DECL:
2454     case FUNCTION_DECL:
2455     case LABEL_DECL:
2456     case CONST_DECL:
2457     case RESULT_DECL:
2458       op0 = DECL_RTL_IF_SET (exp);
2459
2460       /* This decl was probably optimized away.  */
2461       if (!op0)
2462         {
2463           if (TREE_CODE (exp) != VAR_DECL
2464               || DECL_EXTERNAL (exp)
2465               || !TREE_STATIC (exp)
2466               || !DECL_NAME (exp)
2467               || DECL_HARD_REGISTER (exp)
2468               || DECL_IN_CONSTANT_POOL (exp)
2469               || mode == VOIDmode)
2470             return NULL;
2471
2472           op0 = make_decl_rtl_for_debug (exp);
2473           if (!MEM_P (op0)
2474               || GET_CODE (XEXP (op0, 0)) != SYMBOL_REF
2475               || SYMBOL_REF_DECL (XEXP (op0, 0)) != exp)
2476             return NULL;
2477         }
2478       else
2479         op0 = copy_rtx (op0);
2480
2481       if (GET_MODE (op0) == BLKmode
2482           /* If op0 is not BLKmode, but BLKmode is, adjust_mode
2483              below would ICE.  While it is likely a FE bug,
2484              try to be robust here.  See PR43166.  */
2485           || mode == BLKmode
2486           || (mode == VOIDmode && GET_MODE (op0) != VOIDmode))
2487         {
2488           gcc_assert (MEM_P (op0));
2489           op0 = adjust_address_nv (op0, mode, 0);
2490           return op0;
2491         }
2492
2493       /* Fall through.  */
2494
2495     adjust_mode:
2496     case PAREN_EXPR:
2497     case NOP_EXPR:
2498     case CONVERT_EXPR:
2499       {
2500         inner_mode = GET_MODE (op0);
2501
2502         if (mode == inner_mode)
2503           return op0;
2504
2505         if (inner_mode == VOIDmode)
2506           {
2507             if (TREE_CODE (exp) == SSA_NAME)
2508               inner_mode = TYPE_MODE (TREE_TYPE (exp));
2509             else
2510               inner_mode = TYPE_MODE (TREE_TYPE (TREE_OPERAND (exp, 0)));
2511             if (mode == inner_mode)
2512               return op0;
2513           }
2514
2515         if (FLOAT_MODE_P (mode) && FLOAT_MODE_P (inner_mode))
2516           {
2517             if (GET_MODE_BITSIZE (mode) == GET_MODE_BITSIZE (inner_mode))
2518               op0 = simplify_gen_subreg (mode, op0, inner_mode, 0);
2519             else if (GET_MODE_BITSIZE (mode) < GET_MODE_BITSIZE (inner_mode))
2520               op0 = simplify_gen_unary (FLOAT_TRUNCATE, mode, op0, inner_mode);
2521             else
2522               op0 = simplify_gen_unary (FLOAT_EXTEND, mode, op0, inner_mode);
2523           }
2524         else if (FLOAT_MODE_P (mode))
2525           {
2526             gcc_assert (TREE_CODE (exp) != SSA_NAME);
2527             if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0))))
2528               op0 = simplify_gen_unary (UNSIGNED_FLOAT, mode, op0, inner_mode);
2529             else
2530               op0 = simplify_gen_unary (FLOAT, mode, op0, inner_mode);
2531           }
2532         else if (FLOAT_MODE_P (inner_mode))
2533           {
2534             if (unsignedp)
2535               op0 = simplify_gen_unary (UNSIGNED_FIX, mode, op0, inner_mode);
2536             else
2537               op0 = simplify_gen_unary (FIX, mode, op0, inner_mode);
2538           }
2539         else if (CONSTANT_P (op0)
2540                  || GET_MODE_BITSIZE (mode) <= GET_MODE_BITSIZE (inner_mode))
2541           op0 = simplify_gen_subreg (mode, op0, inner_mode,
2542                                      subreg_lowpart_offset (mode,
2543                                                             inner_mode));
2544         else if (TREE_CODE_CLASS (TREE_CODE (exp)) == tcc_unary
2545                  ? TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0)))
2546                  : unsignedp)
2547           op0 = simplify_gen_unary (ZERO_EXTEND, mode, op0, inner_mode);
2548         else
2549           op0 = simplify_gen_unary (SIGN_EXTEND, mode, op0, inner_mode);
2550
2551         return op0;
2552       }
2553
2554     case MEM_REF:
2555       if (!is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
2556         {
2557           tree newexp = fold_binary (MEM_REF, TREE_TYPE (exp),
2558                                      TREE_OPERAND (exp, 0),
2559                                      TREE_OPERAND (exp, 1));
2560           if (newexp)
2561             return expand_debug_expr (newexp);
2562         }
2563       /* FALLTHROUGH */
2564     case INDIRECT_REF:
2565       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
2566       if (!op0)
2567         return NULL;
2568
2569       if (TREE_CODE (exp) == MEM_REF)
2570         {
2571           if (GET_CODE (op0) == DEBUG_IMPLICIT_PTR
2572               || (GET_CODE (op0) == PLUS
2573                   && GET_CODE (XEXP (op0, 0)) == DEBUG_IMPLICIT_PTR))
2574             /* (mem (debug_implicit_ptr)) might confuse aliasing.
2575                Instead just use get_inner_reference.  */
2576             goto component_ref;
2577
2578           op1 = expand_debug_expr (TREE_OPERAND (exp, 1));
2579           if (!op1 || !CONST_INT_P (op1))
2580             return NULL;
2581
2582           op0 = plus_constant (op0, INTVAL (op1));
2583         }
2584
2585       if (POINTER_TYPE_P (TREE_TYPE (exp)))
2586         as = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (exp)));
2587       else
2588         as = ADDR_SPACE_GENERIC;
2589
2590       op0 = convert_debug_memory_address (targetm.addr_space.address_mode (as),
2591                                           op0, as);
2592       if (op0 == NULL_RTX)
2593         return NULL;
2594
2595       op0 = gen_rtx_MEM (mode, op0);
2596       set_mem_attributes (op0, exp, 0);
2597       if (TREE_CODE (exp) == MEM_REF
2598           && !is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
2599         set_mem_expr (op0, NULL_TREE);
2600       set_mem_addr_space (op0, as);
2601
2602       return op0;
2603
2604     case TARGET_MEM_REF:
2605       if (TREE_CODE (TMR_BASE (exp)) == ADDR_EXPR
2606           && !DECL_RTL_SET_P (TREE_OPERAND (TMR_BASE (exp), 0)))
2607         return NULL;
2608
2609       op0 = expand_debug_expr
2610             (tree_mem_ref_addr (build_pointer_type (TREE_TYPE (exp)), exp));
2611       if (!op0)
2612         return NULL;
2613
2614       if (POINTER_TYPE_P (TREE_TYPE (exp)))
2615         as = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (exp)));
2616       else
2617         as = ADDR_SPACE_GENERIC;
2618
2619       op0 = convert_debug_memory_address (targetm.addr_space.address_mode (as),
2620                                           op0, as);
2621       if (op0 == NULL_RTX)
2622         return NULL;
2623
2624       op0 = gen_rtx_MEM (mode, op0);
2625
2626       set_mem_attributes (op0, exp, 0);
2627       set_mem_addr_space (op0, as);
2628
2629       return op0;
2630
2631     component_ref:
2632     case ARRAY_REF:
2633     case ARRAY_RANGE_REF:
2634     case COMPONENT_REF:
2635     case BIT_FIELD_REF:
2636     case REALPART_EXPR:
2637     case IMAGPART_EXPR:
2638     case VIEW_CONVERT_EXPR:
2639       {
2640         enum machine_mode mode1;
2641         HOST_WIDE_INT bitsize, bitpos;
2642         tree offset;
2643         int volatilep = 0;
2644         tree tem = get_inner_reference (exp, &bitsize, &bitpos, &offset,
2645                                         &mode1, &unsignedp, &volatilep, false);
2646         rtx orig_op0;
2647
2648         if (bitsize == 0)
2649           return NULL;
2650
2651         orig_op0 = op0 = expand_debug_expr (tem);
2652
2653         if (!op0)
2654           return NULL;
2655
2656         if (offset)
2657           {
2658             enum machine_mode addrmode, offmode;
2659
2660             if (!MEM_P (op0))
2661               return NULL;
2662
2663             op0 = XEXP (op0, 0);
2664             addrmode = GET_MODE (op0);
2665             if (addrmode == VOIDmode)
2666               addrmode = Pmode;
2667
2668             op1 = expand_debug_expr (offset);
2669             if (!op1)
2670               return NULL;
2671
2672             offmode = GET_MODE (op1);
2673             if (offmode == VOIDmode)
2674               offmode = TYPE_MODE (TREE_TYPE (offset));
2675
2676             if (addrmode != offmode)
2677               op1 = simplify_gen_subreg (addrmode, op1, offmode,
2678                                          subreg_lowpart_offset (addrmode,
2679                                                                 offmode));
2680
2681             /* Don't use offset_address here, we don't need a
2682                recognizable address, and we don't want to generate
2683                code.  */
2684             op0 = gen_rtx_MEM (mode, simplify_gen_binary (PLUS, addrmode,
2685                                                           op0, op1));
2686           }
2687
2688         if (MEM_P (op0))
2689           {
2690             if (mode1 == VOIDmode)
2691               /* Bitfield.  */
2692               mode1 = smallest_mode_for_size (bitsize, MODE_INT);
2693             if (bitpos >= BITS_PER_UNIT)
2694               {
2695                 op0 = adjust_address_nv (op0, mode1, bitpos / BITS_PER_UNIT);
2696                 bitpos %= BITS_PER_UNIT;
2697               }
2698             else if (bitpos < 0)
2699               {
2700                 HOST_WIDE_INT units
2701                   = (-bitpos + BITS_PER_UNIT - 1) / BITS_PER_UNIT;
2702                 op0 = adjust_address_nv (op0, mode1, units);
2703                 bitpos += units * BITS_PER_UNIT;
2704               }
2705             else if (bitpos == 0 && bitsize == GET_MODE_BITSIZE (mode))
2706               op0 = adjust_address_nv (op0, mode, 0);
2707             else if (GET_MODE (op0) != mode1)
2708               op0 = adjust_address_nv (op0, mode1, 0);
2709             else
2710               op0 = copy_rtx (op0);
2711             if (op0 == orig_op0)
2712               op0 = shallow_copy_rtx (op0);
2713             set_mem_attributes (op0, exp, 0);
2714           }
2715
2716         if (bitpos == 0 && mode == GET_MODE (op0))
2717           return op0;
2718
2719         if (bitpos < 0)
2720           return NULL;
2721
2722         if (GET_MODE (op0) == BLKmode)
2723           return NULL;
2724
2725         if ((bitpos % BITS_PER_UNIT) == 0
2726             && bitsize == GET_MODE_BITSIZE (mode1))
2727           {
2728             enum machine_mode opmode = GET_MODE (op0);
2729
2730             if (opmode == VOIDmode)
2731               opmode = TYPE_MODE (TREE_TYPE (tem));
2732
2733             /* This condition may hold if we're expanding the address
2734                right past the end of an array that turned out not to
2735                be addressable (i.e., the address was only computed in
2736                debug stmts).  The gen_subreg below would rightfully
2737                crash, and the address doesn't really exist, so just
2738                drop it.  */
2739             if (bitpos >= GET_MODE_BITSIZE (opmode))
2740               return NULL;
2741
2742             if ((bitpos % GET_MODE_BITSIZE (mode)) == 0)
2743               return simplify_gen_subreg (mode, op0, opmode,
2744                                           bitpos / BITS_PER_UNIT);
2745           }
2746
2747         return simplify_gen_ternary (SCALAR_INT_MODE_P (GET_MODE (op0))
2748                                      && TYPE_UNSIGNED (TREE_TYPE (exp))
2749                                      ? SIGN_EXTRACT
2750                                      : ZERO_EXTRACT, mode,
2751                                      GET_MODE (op0) != VOIDmode
2752                                      ? GET_MODE (op0)
2753                                      : TYPE_MODE (TREE_TYPE (tem)),
2754                                      op0, GEN_INT (bitsize), GEN_INT (bitpos));
2755       }
2756
2757     case ABS_EXPR:
2758       return simplify_gen_unary (ABS, mode, op0, mode);
2759
2760     case NEGATE_EXPR:
2761       return simplify_gen_unary (NEG, mode, op0, mode);
2762
2763     case BIT_NOT_EXPR:
2764       return simplify_gen_unary (NOT, mode, op0, mode);
2765
2766     case FLOAT_EXPR:
2767       return simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
2768                                                                          0)))
2769                                  ? UNSIGNED_FLOAT : FLOAT, mode, op0,
2770                                  inner_mode);
2771
2772     case FIX_TRUNC_EXPR:
2773       return simplify_gen_unary (unsignedp ? UNSIGNED_FIX : FIX, mode, op0,
2774                                  inner_mode);
2775
2776     case POINTER_PLUS_EXPR:
2777       /* For the rare target where pointers are not the same size as
2778          size_t, we need to check for mis-matched modes and correct
2779          the addend.  */
2780       if (op0 && op1
2781           && GET_MODE (op0) != VOIDmode && GET_MODE (op1) != VOIDmode
2782           && GET_MODE (op0) != GET_MODE (op1))
2783         {
2784           if (GET_MODE_BITSIZE (GET_MODE (op0)) < GET_MODE_BITSIZE (GET_MODE (op1)))
2785             op1 = simplify_gen_unary (TRUNCATE, GET_MODE (op0), op1,
2786                                       GET_MODE (op1));
2787           else
2788             /* We always sign-extend, regardless of the signedness of
2789                the operand, because the operand is always unsigned
2790                here even if the original C expression is signed.  */
2791             op1 = simplify_gen_unary (SIGN_EXTEND, GET_MODE (op0), op1,
2792                                       GET_MODE (op1));
2793         }
2794       /* Fall through.  */
2795     case PLUS_EXPR:
2796       return simplify_gen_binary (PLUS, mode, op0, op1);
2797
2798     case MINUS_EXPR:
2799       return simplify_gen_binary (MINUS, mode, op0, op1);
2800
2801     case MULT_EXPR:
2802       return simplify_gen_binary (MULT, mode, op0, op1);
2803
2804     case RDIV_EXPR:
2805     case TRUNC_DIV_EXPR:
2806     case EXACT_DIV_EXPR:
2807       if (unsignedp)
2808         return simplify_gen_binary (UDIV, mode, op0, op1);
2809       else
2810         return simplify_gen_binary (DIV, mode, op0, op1);
2811
2812     case TRUNC_MOD_EXPR:
2813       return simplify_gen_binary (unsignedp ? UMOD : MOD, mode, op0, op1);
2814
2815     case FLOOR_DIV_EXPR:
2816       if (unsignedp)
2817         return simplify_gen_binary (UDIV, mode, op0, op1);
2818       else
2819         {
2820           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
2821           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2822           rtx adj = floor_sdiv_adjust (mode, mod, op1);
2823           return simplify_gen_binary (PLUS, mode, div, adj);
2824         }
2825
2826     case FLOOR_MOD_EXPR:
2827       if (unsignedp)
2828         return simplify_gen_binary (UMOD, mode, op0, op1);
2829       else
2830         {
2831           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2832           rtx adj = floor_sdiv_adjust (mode, mod, op1);
2833           adj = simplify_gen_unary (NEG, mode,
2834                                     simplify_gen_binary (MULT, mode, adj, op1),
2835                                     mode);
2836           return simplify_gen_binary (PLUS, mode, mod, adj);
2837         }
2838
2839     case CEIL_DIV_EXPR:
2840       if (unsignedp)
2841         {
2842           rtx div = simplify_gen_binary (UDIV, mode, op0, op1);
2843           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
2844           rtx adj = ceil_udiv_adjust (mode, mod, op1);
2845           return simplify_gen_binary (PLUS, mode, div, adj);
2846         }
2847       else
2848         {
2849           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
2850           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2851           rtx adj = ceil_sdiv_adjust (mode, mod, op1);
2852           return simplify_gen_binary (PLUS, mode, div, adj);
2853         }
2854
2855     case CEIL_MOD_EXPR:
2856       if (unsignedp)
2857         {
2858           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
2859           rtx adj = ceil_udiv_adjust (mode, mod, op1);
2860           adj = simplify_gen_unary (NEG, mode,
2861                                     simplify_gen_binary (MULT, mode, adj, op1),
2862                                     mode);
2863           return simplify_gen_binary (PLUS, mode, mod, adj);
2864         }
2865       else
2866         {
2867           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2868           rtx adj = ceil_sdiv_adjust (mode, mod, op1);
2869           adj = simplify_gen_unary (NEG, mode,
2870                                     simplify_gen_binary (MULT, mode, adj, op1),
2871                                     mode);
2872           return simplify_gen_binary (PLUS, mode, mod, adj);
2873         }
2874
2875     case ROUND_DIV_EXPR:
2876       if (unsignedp)
2877         {
2878           rtx div = simplify_gen_binary (UDIV, mode, op0, op1);
2879           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
2880           rtx adj = round_udiv_adjust (mode, mod, op1);
2881           return simplify_gen_binary (PLUS, mode, div, adj);
2882         }
2883       else
2884         {
2885           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
2886           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2887           rtx adj = round_sdiv_adjust (mode, mod, op1);
2888           return simplify_gen_binary (PLUS, mode, div, adj);
2889         }
2890
2891     case ROUND_MOD_EXPR:
2892       if (unsignedp)
2893         {
2894           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
2895           rtx adj = round_udiv_adjust (mode, mod, op1);
2896           adj = simplify_gen_unary (NEG, mode,
2897                                     simplify_gen_binary (MULT, mode, adj, op1),
2898                                     mode);
2899           return simplify_gen_binary (PLUS, mode, mod, adj);
2900         }
2901       else
2902         {
2903           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
2904           rtx adj = round_sdiv_adjust (mode, mod, op1);
2905           adj = simplify_gen_unary (NEG, mode,
2906                                     simplify_gen_binary (MULT, mode, adj, op1),
2907                                     mode);
2908           return simplify_gen_binary (PLUS, mode, mod, adj);
2909         }
2910
2911     case LSHIFT_EXPR:
2912       return simplify_gen_binary (ASHIFT, mode, op0, op1);
2913
2914     case RSHIFT_EXPR:
2915       if (unsignedp)
2916         return simplify_gen_binary (LSHIFTRT, mode, op0, op1);
2917       else
2918         return simplify_gen_binary (ASHIFTRT, mode, op0, op1);
2919
2920     case LROTATE_EXPR:
2921       return simplify_gen_binary (ROTATE, mode, op0, op1);
2922
2923     case RROTATE_EXPR:
2924       return simplify_gen_binary (ROTATERT, mode, op0, op1);
2925
2926     case MIN_EXPR:
2927       return simplify_gen_binary (unsignedp ? UMIN : SMIN, mode, op0, op1);
2928
2929     case MAX_EXPR:
2930       return simplify_gen_binary (unsignedp ? UMAX : SMAX, mode, op0, op1);
2931
2932     case BIT_AND_EXPR:
2933     case TRUTH_AND_EXPR:
2934       return simplify_gen_binary (AND, mode, op0, op1);
2935
2936     case BIT_IOR_EXPR:
2937     case TRUTH_OR_EXPR:
2938       return simplify_gen_binary (IOR, mode, op0, op1);
2939
2940     case BIT_XOR_EXPR:
2941     case TRUTH_XOR_EXPR:
2942       return simplify_gen_binary (XOR, mode, op0, op1);
2943
2944     case TRUTH_ANDIF_EXPR:
2945       return gen_rtx_IF_THEN_ELSE (mode, op0, op1, const0_rtx);
2946
2947     case TRUTH_ORIF_EXPR:
2948       return gen_rtx_IF_THEN_ELSE (mode, op0, const_true_rtx, op1);
2949
2950     case TRUTH_NOT_EXPR:
2951       return simplify_gen_relational (EQ, mode, inner_mode, op0, const0_rtx);
2952
2953     case LT_EXPR:
2954       return simplify_gen_relational (unsignedp ? LTU : LT, mode, inner_mode,
2955                                       op0, op1);
2956
2957     case LE_EXPR:
2958       return simplify_gen_relational (unsignedp ? LEU : LE, mode, inner_mode,
2959                                       op0, op1);
2960
2961     case GT_EXPR:
2962       return simplify_gen_relational (unsignedp ? GTU : GT, mode, inner_mode,
2963                                       op0, op1);
2964
2965     case GE_EXPR:
2966       return simplify_gen_relational (unsignedp ? GEU : GE, mode, inner_mode,
2967                                       op0, op1);
2968
2969     case EQ_EXPR:
2970       return simplify_gen_relational (EQ, mode, inner_mode, op0, op1);
2971
2972     case NE_EXPR:
2973       return simplify_gen_relational (NE, mode, inner_mode, op0, op1);
2974
2975     case UNORDERED_EXPR:
2976       return simplify_gen_relational (UNORDERED, mode, inner_mode, op0, op1);
2977
2978     case ORDERED_EXPR:
2979       return simplify_gen_relational (ORDERED, mode, inner_mode, op0, op1);
2980
2981     case UNLT_EXPR:
2982       return simplify_gen_relational (UNLT, mode, inner_mode, op0, op1);
2983
2984     case UNLE_EXPR:
2985       return simplify_gen_relational (UNLE, mode, inner_mode, op0, op1);
2986
2987     case UNGT_EXPR:
2988       return simplify_gen_relational (UNGT, mode, inner_mode, op0, op1);
2989
2990     case UNGE_EXPR:
2991       return simplify_gen_relational (UNGE, mode, inner_mode, op0, op1);
2992
2993     case UNEQ_EXPR:
2994       return simplify_gen_relational (UNEQ, mode, inner_mode, op0, op1);
2995
2996     case LTGT_EXPR:
2997       return simplify_gen_relational (LTGT, mode, inner_mode, op0, op1);
2998
2999     case COND_EXPR:
3000       return gen_rtx_IF_THEN_ELSE (mode, op0, op1, op2);
3001
3002     case COMPLEX_EXPR:
3003       gcc_assert (COMPLEX_MODE_P (mode));
3004       if (GET_MODE (op0) == VOIDmode)
3005         op0 = gen_rtx_CONST (GET_MODE_INNER (mode), op0);
3006       if (GET_MODE (op1) == VOIDmode)
3007         op1 = gen_rtx_CONST (GET_MODE_INNER (mode), op1);
3008       return gen_rtx_CONCAT (mode, op0, op1);
3009
3010     case CONJ_EXPR:
3011       if (GET_CODE (op0) == CONCAT)
3012         return gen_rtx_CONCAT (mode, XEXP (op0, 0),
3013                                simplify_gen_unary (NEG, GET_MODE_INNER (mode),
3014                                                    XEXP (op0, 1),
3015                                                    GET_MODE_INNER (mode)));
3016       else
3017         {
3018           enum machine_mode imode = GET_MODE_INNER (mode);
3019           rtx re, im;
3020
3021           if (MEM_P (op0))
3022             {
3023               re = adjust_address_nv (op0, imode, 0);
3024               im = adjust_address_nv (op0, imode, GET_MODE_SIZE (imode));
3025             }
3026           else
3027             {
3028               enum machine_mode ifmode = int_mode_for_mode (mode);
3029               enum machine_mode ihmode = int_mode_for_mode (imode);
3030               rtx halfsize;
3031               if (ifmode == BLKmode || ihmode == BLKmode)
3032                 return NULL;
3033               halfsize = GEN_INT (GET_MODE_BITSIZE (ihmode));
3034               re = op0;
3035               if (mode != ifmode)
3036                 re = gen_rtx_SUBREG (ifmode, re, 0);
3037               re = gen_rtx_ZERO_EXTRACT (ihmode, re, halfsize, const0_rtx);
3038               if (imode != ihmode)
3039                 re = gen_rtx_SUBREG (imode, re, 0);
3040               im = copy_rtx (op0);
3041               if (mode != ifmode)
3042                 im = gen_rtx_SUBREG (ifmode, im, 0);
3043               im = gen_rtx_ZERO_EXTRACT (ihmode, im, halfsize, halfsize);
3044               if (imode != ihmode)
3045                 im = gen_rtx_SUBREG (imode, im, 0);
3046             }
3047           im = gen_rtx_NEG (imode, im);
3048           return gen_rtx_CONCAT (mode, re, im);
3049         }
3050
3051     case ADDR_EXPR:
3052       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
3053       if (!op0 || !MEM_P (op0))
3054         {
3055           if ((TREE_CODE (TREE_OPERAND (exp, 0)) == VAR_DECL
3056                || TREE_CODE (TREE_OPERAND (exp, 0)) == PARM_DECL
3057                || TREE_CODE (TREE_OPERAND (exp, 0)) == RESULT_DECL)
3058               && !TREE_ADDRESSABLE (TREE_OPERAND (exp, 0)))
3059             return gen_rtx_DEBUG_IMPLICIT_PTR (mode, TREE_OPERAND (exp, 0));
3060
3061           if (handled_component_p (TREE_OPERAND (exp, 0)))
3062             {
3063               HOST_WIDE_INT bitoffset, bitsize, maxsize;
3064               tree decl
3065                 = get_ref_base_and_extent (TREE_OPERAND (exp, 0),
3066                                            &bitoffset, &bitsize, &maxsize);
3067               if ((TREE_CODE (decl) == VAR_DECL
3068                    || TREE_CODE (decl) == PARM_DECL
3069                    || TREE_CODE (decl) == RESULT_DECL)
3070                   && !TREE_ADDRESSABLE (decl)
3071                   && (bitoffset % BITS_PER_UNIT) == 0
3072                   && bitsize > 0
3073                   && bitsize == maxsize)
3074                 return plus_constant (gen_rtx_DEBUG_IMPLICIT_PTR (mode, decl),
3075                                       bitoffset / BITS_PER_UNIT);
3076             }
3077
3078           return NULL;
3079         }
3080
3081       as = TYPE_ADDR_SPACE (TREE_TYPE (exp));
3082       op0 = convert_debug_memory_address (mode, XEXP (op0, 0), as);
3083
3084       return op0;
3085
3086     case VECTOR_CST:
3087       exp = build_constructor_from_list (TREE_TYPE (exp),
3088                                          TREE_VECTOR_CST_ELTS (exp));
3089       /* Fall through.  */
3090
3091     case CONSTRUCTOR:
3092       if (TREE_CODE (TREE_TYPE (exp)) == VECTOR_TYPE)
3093         {
3094           unsigned i;
3095           tree val;
3096
3097           op0 = gen_rtx_CONCATN
3098             (mode, rtvec_alloc (TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp))));
3099
3100           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (exp), i, val)
3101             {
3102               op1 = expand_debug_expr (val);
3103               if (!op1)
3104                 return NULL;
3105               XVECEXP (op0, 0, i) = op1;
3106             }
3107
3108           if (i < TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp)))
3109             {
3110               op1 = expand_debug_expr
3111                 (build_zero_cst (TREE_TYPE (TREE_TYPE (exp))));
3112
3113               if (!op1)
3114                 return NULL;
3115
3116               for (; i < TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp)); i++)
3117                 XVECEXP (op0, 0, i) = op1;
3118             }
3119
3120           return op0;
3121         }
3122       else
3123         goto flag_unsupported;
3124
3125     case CALL_EXPR:
3126       /* ??? Maybe handle some builtins?  */
3127       return NULL;
3128
3129     case SSA_NAME:
3130       {
3131         gimple g = get_gimple_for_ssa_name (exp);
3132         if (g)
3133           {
3134             op0 = expand_debug_expr (gimple_assign_rhs_to_tree (g));
3135             if (!op0)
3136               return NULL;
3137           }
3138         else
3139           {
3140             int part = var_to_partition (SA.map, exp);
3141
3142             if (part == NO_PARTITION)
3143               {
3144                 /* If this is a reference to an incoming value of parameter
3145                    that is never used in the code or where the incoming
3146                    value is never used in the code, use PARM_DECL's
3147                    DECL_RTL if set.  */
3148                 if (SSA_NAME_IS_DEFAULT_DEF (exp)
3149                     && TREE_CODE (SSA_NAME_VAR (exp)) == PARM_DECL)
3150                   {
3151                     rtx incoming = DECL_INCOMING_RTL (SSA_NAME_VAR (exp));
3152                     if (incoming
3153                         && GET_MODE (incoming) != BLKmode
3154                         && ((REG_P (incoming) && HARD_REGISTER_P (incoming))
3155                             || (MEM_P (incoming)
3156                                 && REG_P (XEXP (incoming, 0))
3157                                 && HARD_REGISTER_P (XEXP (incoming, 0)))))
3158                       {
3159                         op0 = gen_rtx_ENTRY_VALUE (GET_MODE (incoming));
3160                         ENTRY_VALUE_EXP (op0) = incoming;
3161                         goto adjust_mode;
3162                       }
3163                     op0 = expand_debug_expr (SSA_NAME_VAR (exp));
3164                     if (!op0)
3165                       return NULL;
3166                     goto adjust_mode;
3167                   }
3168                 return NULL;
3169               }
3170
3171             gcc_assert (part >= 0 && (unsigned)part < SA.map->num_partitions);
3172
3173             op0 = copy_rtx (SA.partition_to_pseudo[part]);
3174           }
3175         goto adjust_mode;
3176       }
3177
3178     case ERROR_MARK:
3179       return NULL;
3180
3181     /* Vector stuff.  For most of the codes we don't have rtl codes.  */
3182     case REALIGN_LOAD_EXPR:
3183     case REDUC_MAX_EXPR:
3184     case REDUC_MIN_EXPR:
3185     case REDUC_PLUS_EXPR:
3186     case VEC_COND_EXPR:
3187     case VEC_EXTRACT_EVEN_EXPR:
3188     case VEC_EXTRACT_ODD_EXPR:
3189     case VEC_INTERLEAVE_HIGH_EXPR:
3190     case VEC_INTERLEAVE_LOW_EXPR:
3191     case VEC_LSHIFT_EXPR:
3192     case VEC_PACK_FIX_TRUNC_EXPR:
3193     case VEC_PACK_SAT_EXPR:
3194     case VEC_PACK_TRUNC_EXPR:
3195     case VEC_RSHIFT_EXPR:
3196     case VEC_UNPACK_FLOAT_HI_EXPR:
3197     case VEC_UNPACK_FLOAT_LO_EXPR:
3198     case VEC_UNPACK_HI_EXPR:
3199     case VEC_UNPACK_LO_EXPR:
3200     case VEC_WIDEN_MULT_HI_EXPR:
3201     case VEC_WIDEN_MULT_LO_EXPR:
3202       return NULL;
3203
3204    /* Misc codes.  */
3205     case ADDR_SPACE_CONVERT_EXPR:
3206     case FIXED_CONVERT_EXPR:
3207     case OBJ_TYPE_REF:
3208     case WITH_SIZE_EXPR:
3209       return NULL;
3210
3211     case DOT_PROD_EXPR:
3212       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3213           && SCALAR_INT_MODE_P (mode))
3214         {
3215           op0
3216             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3217                                                                           0)))
3218                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op0,
3219                                   inner_mode);
3220           op1
3221             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3222                                                                           1)))
3223                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op1,
3224                                   inner_mode);
3225           op0 = simplify_gen_binary (MULT, mode, op0, op1);
3226           return simplify_gen_binary (PLUS, mode, op0, op2);
3227         }
3228       return NULL;
3229
3230     case WIDEN_MULT_EXPR:
3231     case WIDEN_MULT_PLUS_EXPR:
3232     case WIDEN_MULT_MINUS_EXPR:
3233       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3234           && SCALAR_INT_MODE_P (mode))
3235         {
3236           inner_mode = GET_MODE (op0);
3237           if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0))))
3238             op0 = simplify_gen_unary (ZERO_EXTEND, mode, op0, inner_mode);
3239           else
3240             op0 = simplify_gen_unary (SIGN_EXTEND, mode, op0, inner_mode);
3241           if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 1))))
3242             op1 = simplify_gen_unary (ZERO_EXTEND, mode, op1, inner_mode);
3243           else
3244             op1 = simplify_gen_unary (SIGN_EXTEND, mode, op1, inner_mode);
3245           op0 = simplify_gen_binary (MULT, mode, op0, op1);
3246           if (TREE_CODE (exp) == WIDEN_MULT_EXPR)
3247             return op0;
3248           else if (TREE_CODE (exp) == WIDEN_MULT_PLUS_EXPR)
3249             return simplify_gen_binary (PLUS, mode, op0, op2);
3250           else
3251             return simplify_gen_binary (MINUS, mode, op2, op0);
3252         }
3253       return NULL;
3254
3255     case WIDEN_SUM_EXPR:
3256       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3257           && SCALAR_INT_MODE_P (mode))
3258         {
3259           op0
3260             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3261                                                                           0)))
3262                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op0,
3263                                   inner_mode);
3264           return simplify_gen_binary (PLUS, mode, op0, op1);
3265         }
3266       return NULL;
3267
3268     case FMA_EXPR:
3269       return simplify_gen_ternary (FMA, mode, inner_mode, op0, op1, op2);
3270
3271     default:
3272     flag_unsupported:
3273 #ifdef ENABLE_CHECKING
3274       debug_tree (exp);
3275       gcc_unreachable ();
3276 #else
3277       return NULL;
3278 #endif
3279     }
3280 }
3281
3282 /* Expand the _LOCs in debug insns.  We run this after expanding all
3283    regular insns, so that any variables referenced in the function
3284    will have their DECL_RTLs set.  */
3285
3286 static void
3287 expand_debug_locations (void)
3288 {
3289   rtx insn;
3290   rtx last = get_last_insn ();
3291   int save_strict_alias = flag_strict_aliasing;
3292
3293   /* New alias sets while setting up memory attributes cause
3294      -fcompare-debug failures, even though it doesn't bring about any
3295      codegen changes.  */
3296   flag_strict_aliasing = 0;
3297
3298   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
3299     if (DEBUG_INSN_P (insn))
3300       {
3301         tree value = (tree)INSN_VAR_LOCATION_LOC (insn);
3302         rtx val;
3303         enum machine_mode mode;
3304
3305         if (value == NULL_TREE)
3306           val = NULL_RTX;
3307         else
3308           {
3309             val = expand_debug_expr (value);
3310             gcc_assert (last == get_last_insn ());
3311           }
3312
3313         if (!val)
3314           val = gen_rtx_UNKNOWN_VAR_LOC ();
3315         else
3316           {
3317             mode = GET_MODE (INSN_VAR_LOCATION (insn));
3318
3319             gcc_assert (mode == GET_MODE (val)
3320                         || (GET_MODE (val) == VOIDmode
3321                             && (CONST_INT_P (val)
3322                                 || GET_CODE (val) == CONST_FIXED
3323                                 || GET_CODE (val) == CONST_DOUBLE
3324                                 || GET_CODE (val) == LABEL_REF)));
3325           }
3326
3327         INSN_VAR_LOCATION_LOC (insn) = val;
3328       }
3329
3330   flag_strict_aliasing = save_strict_alias;
3331 }
3332
3333 /* Expand basic block BB from GIMPLE trees to RTL.  */
3334
3335 static basic_block
3336 expand_gimple_basic_block (basic_block bb)
3337 {
3338   gimple_stmt_iterator gsi;
3339   gimple_seq stmts;
3340   gimple stmt = NULL;
3341   rtx note, last;
3342   edge e;
3343   edge_iterator ei;
3344   void **elt;
3345
3346   if (dump_file)
3347     fprintf (dump_file, "\n;; Generating RTL for gimple basic block %d\n",
3348              bb->index);
3349
3350   /* Note that since we are now transitioning from GIMPLE to RTL, we
3351      cannot use the gsi_*_bb() routines because they expect the basic
3352      block to be in GIMPLE, instead of RTL.  Therefore, we need to
3353      access the BB sequence directly.  */
3354   stmts = bb_seq (bb);
3355   bb->il.gimple = NULL;
3356   rtl_profile_for_bb (bb);
3357   init_rtl_bb_info (bb);
3358   bb->flags |= BB_RTL;
3359
3360   /* Remove the RETURN_EXPR if we may fall though to the exit
3361      instead.  */
3362   gsi = gsi_last (stmts);
3363   if (!gsi_end_p (gsi)
3364       && gimple_code (gsi_stmt (gsi)) == GIMPLE_RETURN)
3365     {
3366       gimple ret_stmt = gsi_stmt (gsi);
3367
3368       gcc_assert (single_succ_p (bb));
3369       gcc_assert (single_succ (bb) == EXIT_BLOCK_PTR);
3370
3371       if (bb->next_bb == EXIT_BLOCK_PTR
3372           && !gimple_return_retval (ret_stmt))
3373         {
3374           gsi_remove (&gsi, false);
3375           single_succ_edge (bb)->flags |= EDGE_FALLTHRU;
3376         }
3377     }
3378
3379   gsi = gsi_start (stmts);
3380   if (!gsi_end_p (gsi))
3381     {
3382       stmt = gsi_stmt (gsi);
3383       if (gimple_code (stmt) != GIMPLE_LABEL)
3384         stmt = NULL;
3385     }
3386
3387   elt = pointer_map_contains (lab_rtx_for_bb, bb);
3388
3389   if (stmt || elt)
3390     {
3391       last = get_last_insn ();
3392
3393       if (stmt)
3394         {
3395           expand_gimple_stmt (stmt);
3396           gsi_next (&gsi);
3397         }
3398
3399       if (elt)
3400         emit_label ((rtx) *elt);
3401
3402       /* Java emits line number notes in the top of labels.
3403          ??? Make this go away once line number notes are obsoleted.  */
3404       BB_HEAD (bb) = NEXT_INSN (last);
3405       if (NOTE_P (BB_HEAD (bb)))
3406         BB_HEAD (bb) = NEXT_INSN (BB_HEAD (bb));
3407       note = emit_note_after (NOTE_INSN_BASIC_BLOCK, BB_HEAD (bb));
3408
3409       maybe_dump_rtl_for_gimple_stmt (stmt, last);
3410     }
3411   else
3412     note = BB_HEAD (bb) = emit_note (NOTE_INSN_BASIC_BLOCK);
3413
3414   NOTE_BASIC_BLOCK (note) = bb;
3415
3416   for (; !gsi_end_p (gsi); gsi_next (&gsi))
3417     {
3418       basic_block new_bb;
3419
3420       stmt = gsi_stmt (gsi);
3421
3422       /* If this statement is a non-debug one, and we generate debug
3423          insns, then this one might be the last real use of a TERed
3424          SSA_NAME, but where there are still some debug uses further
3425          down.  Expanding the current SSA name in such further debug
3426          uses by their RHS might lead to wrong debug info, as coalescing
3427          might make the operands of such RHS be placed into the same
3428          pseudo as something else.  Like so:
3429            a_1 = a_0 + 1;   // Assume a_1 is TERed and a_0 is dead
3430            use(a_1);
3431            a_2 = ...
3432            #DEBUG ... => a_1
3433          As a_0 and a_2 don't overlap in lifetime, assume they are coalesced.
3434          If we now would expand a_1 by it's RHS (a_0 + 1) in the debug use,
3435          the write to a_2 would actually have clobbered the place which
3436          formerly held a_0.
3437
3438          So, instead of that, we recognize the situation, and generate
3439          debug temporaries at the last real use of TERed SSA names:
3440            a_1 = a_0 + 1;
3441            #DEBUG #D1 => a_1
3442            use(a_1);
3443            a_2 = ...
3444            #DEBUG ... => #D1
3445          */
3446       if (MAY_HAVE_DEBUG_INSNS
3447           && SA.values
3448           && !is_gimple_debug (stmt))
3449         {
3450           ssa_op_iter iter;
3451           tree op;
3452           gimple def;
3453
3454           location_t sloc = get_curr_insn_source_location ();
3455           tree sblock = get_curr_insn_block ();
3456
3457           /* Look for SSA names that have their last use here (TERed
3458              names always have only one real use).  */
3459           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3460             if ((def = get_gimple_for_ssa_name (op)))
3461               {
3462                 imm_use_iterator imm_iter;
3463                 use_operand_p use_p;
3464                 bool have_debug_uses = false;
3465
3466                 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
3467                   {
3468                     if (gimple_debug_bind_p (USE_STMT (use_p)))
3469                       {
3470                         have_debug_uses = true;
3471                         break;
3472                       }
3473                   }
3474
3475                 if (have_debug_uses)
3476                   {
3477                     /* OP is a TERed SSA name, with DEF it's defining
3478                        statement, and where OP is used in further debug
3479                        instructions.  Generate a debug temporary, and
3480                        replace all uses of OP in debug insns with that
3481                        temporary.  */
3482                     gimple debugstmt;
3483                     tree value = gimple_assign_rhs_to_tree (def);
3484                     tree vexpr = make_node (DEBUG_EXPR_DECL);
3485                     rtx val;
3486                     enum machine_mode mode;
3487
3488                     set_curr_insn_source_location (gimple_location (def));
3489                     set_curr_insn_block (gimple_block (def));
3490
3491                     DECL_ARTIFICIAL (vexpr) = 1;
3492                     TREE_TYPE (vexpr) = TREE_TYPE (value);
3493                     if (DECL_P (value))
3494                       mode = DECL_MODE (value);
3495                     else
3496                       mode = TYPE_MODE (TREE_TYPE (value));
3497                     DECL_MODE (vexpr) = mode;
3498
3499                     val = gen_rtx_VAR_LOCATION
3500                         (mode, vexpr, (rtx)value, VAR_INIT_STATUS_INITIALIZED);
3501
3502                     emit_debug_insn (val);
3503
3504                     FOR_EACH_IMM_USE_STMT (debugstmt, imm_iter, op)
3505                       {
3506                         if (!gimple_debug_bind_p (debugstmt))
3507                           continue;
3508
3509                         FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
3510                           SET_USE (use_p, vexpr);
3511
3512                         update_stmt (debugstmt);
3513                       }
3514                   }
3515               }
3516           set_curr_insn_source_location (sloc);
3517           set_curr_insn_block (sblock);
3518         }
3519
3520       currently_expanding_gimple_stmt = stmt;
3521
3522       /* Expand this statement, then evaluate the resulting RTL and
3523          fixup the CFG accordingly.  */
3524       if (gimple_code (stmt) == GIMPLE_COND)
3525         {
3526           new_bb = expand_gimple_cond (bb, stmt);
3527           if (new_bb)
3528             return new_bb;
3529         }
3530       else if (gimple_debug_bind_p (stmt))
3531         {
3532           location_t sloc = get_curr_insn_source_location ();
3533           tree sblock = get_curr_insn_block ();
3534           gimple_stmt_iterator nsi = gsi;
3535
3536           for (;;)
3537             {
3538               tree var = gimple_debug_bind_get_var (stmt);
3539               tree value;
3540               rtx val;
3541               enum machine_mode mode;
3542
3543               if (gimple_debug_bind_has_value_p (stmt))
3544                 value = gimple_debug_bind_get_value (stmt);
3545               else
3546                 value = NULL_TREE;
3547
3548               last = get_last_insn ();
3549
3550               set_curr_insn_source_location (gimple_location (stmt));
3551               set_curr_insn_block (gimple_block (stmt));
3552
3553               if (DECL_P (var))
3554                 mode = DECL_MODE (var);
3555               else
3556                 mode = TYPE_MODE (TREE_TYPE (var));
3557
3558               val = gen_rtx_VAR_LOCATION
3559                 (mode, var, (rtx)value, VAR_INIT_STATUS_INITIALIZED);
3560
3561               emit_debug_insn (val);
3562
3563               if (dump_file && (dump_flags & TDF_DETAILS))
3564                 {
3565                   /* We can't dump the insn with a TREE where an RTX
3566                      is expected.  */
3567                   PAT_VAR_LOCATION_LOC (val) = const0_rtx;
3568                   maybe_dump_rtl_for_gimple_stmt (stmt, last);
3569                   PAT_VAR_LOCATION_LOC (val) = (rtx)value;
3570                 }
3571
3572               /* In order not to generate too many debug temporaries,
3573                  we delink all uses of debug statements we already expanded.
3574                  Therefore debug statements between definition and real
3575                  use of TERed SSA names will continue to use the SSA name,
3576                  and not be replaced with debug temps.  */
3577               delink_stmt_imm_use (stmt);
3578
3579               gsi = nsi;
3580               gsi_next (&nsi);
3581               if (gsi_end_p (nsi))
3582                 break;
3583               stmt = gsi_stmt (nsi);
3584               if (!gimple_debug_bind_p (stmt))
3585                 break;
3586             }
3587
3588           set_curr_insn_source_location (sloc);
3589           set_curr_insn_block (sblock);
3590         }
3591       else
3592         {
3593           if (is_gimple_call (stmt) && gimple_call_tail_p (stmt))
3594             {
3595               bool can_fallthru;
3596               new_bb = expand_gimple_tailcall (bb, stmt, &can_fallthru);
3597               if (new_bb)
3598                 {
3599                   if (can_fallthru)
3600                     bb = new_bb;
3601                   else
3602                     return new_bb;
3603                 }
3604             }
3605           else
3606             {
3607               def_operand_p def_p;
3608               def_p = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF);
3609
3610               if (def_p != NULL)
3611                 {
3612                   /* Ignore this stmt if it is in the list of
3613                      replaceable expressions.  */
3614                   if (SA.values
3615                       && bitmap_bit_p (SA.values,
3616                                        SSA_NAME_VERSION (DEF_FROM_PTR (def_p))))
3617                     continue;
3618                 }
3619               last = expand_gimple_stmt (stmt);
3620               maybe_dump_rtl_for_gimple_stmt (stmt, last);
3621             }
3622         }
3623     }
3624
3625   currently_expanding_gimple_stmt = NULL;
3626
3627   /* Expand implicit goto and convert goto_locus.  */
3628   FOR_EACH_EDGE (e, ei, bb->succs)
3629     {
3630       if (e->goto_locus && e->goto_block)
3631         {
3632           set_curr_insn_source_location (e->goto_locus);
3633           set_curr_insn_block (e->goto_block);
3634           e->goto_locus = curr_insn_locator ();
3635         }
3636       e->goto_block = NULL;
3637       if ((e->flags & EDGE_FALLTHRU) && e->dest != bb->next_bb)
3638         {
3639           emit_jump (label_rtx_for_bb (e->dest));
3640           e->flags &= ~EDGE_FALLTHRU;
3641         }
3642     }
3643
3644   /* Expanded RTL can create a jump in the last instruction of block.
3645      This later might be assumed to be a jump to successor and break edge insertion.
3646      We need to insert dummy move to prevent this. PR41440. */
3647   if (single_succ_p (bb)
3648       && (single_succ_edge (bb)->flags & EDGE_FALLTHRU)
3649       && (last = get_last_insn ())
3650       && JUMP_P (last))
3651     {
3652       rtx dummy = gen_reg_rtx (SImode);
3653       emit_insn_after_noloc (gen_move_insn (dummy, dummy), last, NULL);
3654     }
3655
3656   do_pending_stack_adjust ();
3657
3658   /* Find the block tail.  The last insn in the block is the insn
3659      before a barrier and/or table jump insn.  */
3660   last = get_last_insn ();
3661   if (BARRIER_P (last))
3662     last = PREV_INSN (last);
3663   if (JUMP_TABLE_DATA_P (last))
3664     last = PREV_INSN (PREV_INSN (last));
3665   BB_END (bb) = last;
3666
3667   update_bb_for_insn (bb);
3668
3669   return bb;
3670 }
3671
3672
3673 /* Create a basic block for initialization code.  */
3674
3675 static basic_block
3676 construct_init_block (void)
3677 {
3678   basic_block init_block, first_block;
3679   edge e = NULL;
3680   int flags;
3681
3682   /* Multiple entry points not supported yet.  */
3683   gcc_assert (EDGE_COUNT (ENTRY_BLOCK_PTR->succs) == 1);
3684   init_rtl_bb_info (ENTRY_BLOCK_PTR);
3685   init_rtl_bb_info (EXIT_BLOCK_PTR);
3686   ENTRY_BLOCK_PTR->flags |= BB_RTL;
3687   EXIT_BLOCK_PTR->flags |= BB_RTL;
3688
3689   e = EDGE_SUCC (ENTRY_BLOCK_PTR, 0);
3690
3691   /* When entry edge points to first basic block, we don't need jump,
3692      otherwise we have to jump into proper target.  */
3693   if (e && e->dest != ENTRY_BLOCK_PTR->next_bb)
3694     {
3695       tree label = gimple_block_label (e->dest);
3696
3697       emit_jump (label_rtx (label));
3698       flags = 0;
3699     }
3700   else
3701     flags = EDGE_FALLTHRU;
3702
3703   init_block = create_basic_block (NEXT_INSN (get_insns ()),
3704                                    get_last_insn (),
3705                                    ENTRY_BLOCK_PTR);
3706   init_block->frequency = ENTRY_BLOCK_PTR->frequency;
3707   init_block->count = ENTRY_BLOCK_PTR->count;
3708   if (e)
3709     {
3710       first_block = e->dest;
3711       redirect_edge_succ (e, init_block);
3712       e = make_edge (init_block, first_block, flags);
3713     }
3714   else
3715     e = make_edge (init_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
3716   e->probability = REG_BR_PROB_BASE;
3717   e->count = ENTRY_BLOCK_PTR->count;
3718
3719   update_bb_for_insn (init_block);
3720   return init_block;
3721 }
3722
3723 /* For each lexical block, set BLOCK_NUMBER to the depth at which it is
3724    found in the block tree.  */
3725
3726 static void
3727 set_block_levels (tree block, int level)
3728 {
3729   while (block)
3730     {
3731       BLOCK_NUMBER (block) = level;
3732       set_block_levels (BLOCK_SUBBLOCKS (block), level + 1);
3733       block = BLOCK_CHAIN (block);
3734     }
3735 }
3736
3737 /* Create a block containing landing pads and similar stuff.  */
3738
3739 static void
3740 construct_exit_block (void)
3741 {
3742   rtx head = get_last_insn ();
3743   rtx end;
3744   basic_block exit_block;
3745   edge e, e2;
3746   unsigned ix;
3747   edge_iterator ei;
3748   rtx orig_end = BB_END (EXIT_BLOCK_PTR->prev_bb);
3749
3750   rtl_profile_for_bb (EXIT_BLOCK_PTR);
3751
3752   /* Make sure the locus is set to the end of the function, so that
3753      epilogue line numbers and warnings are set properly.  */
3754   if (cfun->function_end_locus != UNKNOWN_LOCATION)
3755     input_location = cfun->function_end_locus;
3756
3757   /* The following insns belong to the top scope.  */
3758   set_curr_insn_block (DECL_INITIAL (current_function_decl));
3759
3760   /* Generate rtl for function exit.  */
3761   expand_function_end ();
3762
3763   end = get_last_insn ();
3764   if (head == end)
3765     return;
3766   /* While emitting the function end we could move end of the last basic block.
3767    */
3768   BB_END (EXIT_BLOCK_PTR->prev_bb) = orig_end;
3769   while (NEXT_INSN (head) && NOTE_P (NEXT_INSN (head)))
3770     head = NEXT_INSN (head);
3771   exit_block = create_basic_block (NEXT_INSN (head), end,
3772                                    EXIT_BLOCK_PTR->prev_bb);
3773   exit_block->frequency = EXIT_BLOCK_PTR->frequency;
3774   exit_block->count = EXIT_BLOCK_PTR->count;
3775
3776   ix = 0;
3777   while (ix < EDGE_COUNT (EXIT_BLOCK_PTR->preds))
3778     {
3779       e = EDGE_PRED (EXIT_BLOCK_PTR, ix);
3780       if (!(e->flags & EDGE_ABNORMAL))
3781         redirect_edge_succ (e, exit_block);
3782       else
3783         ix++;
3784     }
3785
3786   e = make_edge (exit_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
3787   e->probability = REG_BR_PROB_BASE;
3788   e->count = EXIT_BLOCK_PTR->count;
3789   FOR_EACH_EDGE (e2, ei, EXIT_BLOCK_PTR->preds)
3790     if (e2 != e)
3791       {
3792         e->count -= e2->count;
3793         exit_block->count -= e2->count;
3794         exit_block->frequency -= EDGE_FREQUENCY (e2);
3795       }
3796   if (e->count < 0)
3797     e->count = 0;
3798   if (exit_block->count < 0)
3799     exit_block->count = 0;
3800   if (exit_block->frequency < 0)
3801     exit_block->frequency = 0;
3802   update_bb_for_insn (exit_block);
3803 }
3804
3805 /* Helper function for discover_nonconstant_array_refs.
3806    Look for ARRAY_REF nodes with non-constant indexes and mark them
3807    addressable.  */
3808
3809 static tree
3810 discover_nonconstant_array_refs_r (tree * tp, int *walk_subtrees,
3811                                    void *data ATTRIBUTE_UNUSED)
3812 {
3813   tree t = *tp;
3814
3815   if (IS_TYPE_OR_DECL_P (t))
3816     *walk_subtrees = 0;
3817   else if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
3818     {
3819       while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
3820               && is_gimple_min_invariant (TREE_OPERAND (t, 1))
3821               && (!TREE_OPERAND (t, 2)
3822                   || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
3823              || (TREE_CODE (t) == COMPONENT_REF
3824                  && (!TREE_OPERAND (t,2)
3825                      || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
3826              || TREE_CODE (t) == BIT_FIELD_REF
3827              || TREE_CODE (t) == REALPART_EXPR
3828              || TREE_CODE (t) == IMAGPART_EXPR
3829              || TREE_CODE (t) == VIEW_CONVERT_EXPR
3830              || CONVERT_EXPR_P (t))
3831         t = TREE_OPERAND (t, 0);
3832
3833       if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
3834         {
3835           t = get_base_address (t);
3836           if (t && DECL_P (t)
3837               && DECL_MODE (t) != BLKmode)
3838             TREE_ADDRESSABLE (t) = 1;
3839         }
3840
3841       *walk_subtrees = 0;
3842     }
3843
3844   return NULL_TREE;
3845 }
3846
3847 /* RTL expansion is not able to compile array references with variable
3848    offsets for arrays stored in single register.  Discover such
3849    expressions and mark variables as addressable to avoid this
3850    scenario.  */
3851
3852 static void
3853 discover_nonconstant_array_refs (void)
3854 {
3855   basic_block bb;
3856   gimple_stmt_iterator gsi;
3857
3858   FOR_EACH_BB (bb)
3859     for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3860       {
3861         gimple stmt = gsi_stmt (gsi);
3862         if (!is_gimple_debug (stmt))
3863           walk_gimple_op (stmt, discover_nonconstant_array_refs_r, NULL);
3864       }
3865 }
3866
3867 /* This function sets crtl->args.internal_arg_pointer to a virtual
3868    register if DRAP is needed.  Local register allocator will replace
3869    virtual_incoming_args_rtx with the virtual register.  */
3870
3871 static void
3872 expand_stack_alignment (void)
3873 {
3874   rtx drap_rtx;
3875   unsigned int preferred_stack_boundary;
3876
3877   if (! SUPPORTS_STACK_ALIGNMENT)
3878     return;
3879
3880   if (cfun->calls_alloca
3881       || cfun->has_nonlocal_label
3882       || crtl->has_nonlocal_goto)
3883     crtl->need_drap = true;
3884
3885   /* Call update_stack_boundary here again to update incoming stack
3886      boundary.  It may set incoming stack alignment to a different
3887      value after RTL expansion.  TARGET_FUNCTION_OK_FOR_SIBCALL may
3888      use the minimum incoming stack alignment to check if it is OK
3889      to perform sibcall optimization since sibcall optimization will
3890      only align the outgoing stack to incoming stack boundary.  */
3891   if (targetm.calls.update_stack_boundary)
3892     targetm.calls.update_stack_boundary ();
3893
3894   /* The incoming stack frame has to be aligned at least at
3895      parm_stack_boundary.  */
3896   gcc_assert (crtl->parm_stack_boundary <= INCOMING_STACK_BOUNDARY);
3897
3898   /* Update crtl->stack_alignment_estimated and use it later to align
3899      stack.  We check PREFERRED_STACK_BOUNDARY if there may be non-call
3900      exceptions since callgraph doesn't collect incoming stack alignment
3901      in this case.  */
3902   if (cfun->can_throw_non_call_exceptions
3903       && PREFERRED_STACK_BOUNDARY > crtl->preferred_stack_boundary)
3904     preferred_stack_boundary = PREFERRED_STACK_BOUNDARY;
3905   else
3906     preferred_stack_boundary = crtl->preferred_stack_boundary;
3907   if (preferred_stack_boundary > crtl->stack_alignment_estimated)
3908     crtl->stack_alignment_estimated = preferred_stack_boundary;
3909   if (preferred_stack_boundary > crtl->stack_alignment_needed)
3910     crtl->stack_alignment_needed = preferred_stack_boundary;
3911
3912   gcc_assert (crtl->stack_alignment_needed
3913               <= crtl->stack_alignment_estimated);
3914
3915   crtl->stack_realign_needed
3916     = INCOMING_STACK_BOUNDARY < crtl->stack_alignment_estimated;
3917   crtl->stack_realign_tried = crtl->stack_realign_needed;
3918
3919   crtl->stack_realign_processed = true;
3920
3921   /* Target has to redefine TARGET_GET_DRAP_RTX to support stack
3922      alignment.  */
3923   gcc_assert (targetm.calls.get_drap_rtx != NULL);
3924   drap_rtx = targetm.calls.get_drap_rtx ();
3925
3926   /* stack_realign_drap and drap_rtx must match.  */
3927   gcc_assert ((stack_realign_drap != 0) == (drap_rtx != NULL));
3928
3929   /* Do nothing if NULL is returned, which means DRAP is not needed.  */
3930   if (NULL != drap_rtx)
3931     {
3932       crtl->args.internal_arg_pointer = drap_rtx;
3933
3934       /* Call fixup_tail_calls to clean up REG_EQUIV note if DRAP is
3935          needed. */
3936       fixup_tail_calls ();
3937     }
3938 }
3939
3940 /* Translate the intermediate representation contained in the CFG
3941    from GIMPLE trees to RTL.
3942
3943    We do conversion per basic block and preserve/update the tree CFG.
3944    This implies we have to do some magic as the CFG can simultaneously
3945    consist of basic blocks containing RTL and GIMPLE trees.  This can
3946    confuse the CFG hooks, so be careful to not manipulate CFG during
3947    the expansion.  */
3948
3949 static unsigned int
3950 gimple_expand_cfg (void)
3951 {
3952   basic_block bb, init_block;
3953   sbitmap blocks;
3954   edge_iterator ei;
3955   edge e;
3956   rtx var_seq;
3957   unsigned i;
3958
3959   timevar_push (TV_OUT_OF_SSA);
3960   rewrite_out_of_ssa (&SA);
3961   timevar_pop (TV_OUT_OF_SSA);
3962   SA.partition_to_pseudo = (rtx *)xcalloc (SA.map->num_partitions,
3963                                            sizeof (rtx));
3964
3965   /* Some backends want to know that we are expanding to RTL.  */
3966   currently_expanding_to_rtl = 1;
3967
3968   rtl_profile_for_bb (ENTRY_BLOCK_PTR);
3969
3970   insn_locators_alloc ();
3971   if (!DECL_IS_BUILTIN (current_function_decl))
3972     {
3973       /* Eventually, all FEs should explicitly set function_start_locus.  */
3974       if (cfun->function_start_locus == UNKNOWN_LOCATION)
3975        set_curr_insn_source_location
3976          (DECL_SOURCE_LOCATION (current_function_decl));
3977       else
3978        set_curr_insn_source_location (cfun->function_start_locus);
3979     }
3980   else
3981     set_curr_insn_source_location (UNKNOWN_LOCATION);
3982   set_curr_insn_block (DECL_INITIAL (current_function_decl));
3983   prologue_locator = curr_insn_locator ();
3984
3985 #ifdef INSN_SCHEDULING
3986   init_sched_attrs ();
3987 #endif
3988
3989   /* Make sure first insn is a note even if we don't want linenums.
3990      This makes sure the first insn will never be deleted.
3991      Also, final expects a note to appear there.  */
3992   emit_note (NOTE_INSN_DELETED);
3993
3994   /* Mark arrays indexed with non-constant indices with TREE_ADDRESSABLE.  */
3995   discover_nonconstant_array_refs ();
3996
3997   targetm.expand_to_rtl_hook ();
3998   crtl->stack_alignment_needed = STACK_BOUNDARY;
3999   crtl->max_used_stack_slot_alignment = STACK_BOUNDARY;
4000   crtl->stack_alignment_estimated = 0;
4001   crtl->preferred_stack_boundary = STACK_BOUNDARY;
4002   cfun->cfg->max_jumptable_ents = 0;
4003
4004   /* Resovle the function section.  Some targets, like ARM EABI rely on knowledge
4005      of the function section at exapnsion time to predict distance of calls.  */
4006   resolve_unique_section (current_function_decl, 0, flag_function_sections);
4007
4008   /* Expand the variables recorded during gimple lowering.  */
4009   timevar_push (TV_VAR_EXPAND);
4010   start_sequence ();
4011
4012   expand_used_vars ();
4013
4014   var_seq = get_insns ();
4015   end_sequence ();
4016   timevar_pop (TV_VAR_EXPAND);
4017
4018   /* Honor stack protection warnings.  */
4019   if (warn_stack_protect)
4020     {
4021       if (cfun->calls_alloca)
4022         warning (OPT_Wstack_protector,
4023                  "stack protector not protecting local variables: "
4024                  "variable length buffer");
4025       if (has_short_buffer && !crtl->stack_protect_guard)
4026         warning (OPT_Wstack_protector,
4027                  "stack protector not protecting function: "
4028                  "all local arrays are less than %d bytes long",
4029                  (int) PARAM_VALUE (PARAM_SSP_BUFFER_SIZE));
4030     }
4031
4032   /* Set up parameters and prepare for return, for the function.  */
4033   expand_function_start (current_function_decl);
4034
4035   /* If we emitted any instructions for setting up the variables,
4036      emit them before the FUNCTION_START note.  */
4037   if (var_seq)
4038     {
4039       emit_insn_before (var_seq, parm_birth_insn);
4040
4041       /* In expand_function_end we'll insert the alloca save/restore
4042          before parm_birth_insn.  We've just insertted an alloca call.
4043          Adjust the pointer to match.  */
4044       parm_birth_insn = var_seq;
4045     }
4046
4047   /* Now that we also have the parameter RTXs, copy them over to our
4048      partitions.  */
4049   for (i = 0; i < SA.map->num_partitions; i++)
4050     {
4051       tree var = SSA_NAME_VAR (partition_to_var (SA.map, i));
4052
4053       if (TREE_CODE (var) != VAR_DECL
4054           && !SA.partition_to_pseudo[i])
4055         SA.partition_to_pseudo[i] = DECL_RTL_IF_SET (var);
4056       gcc_assert (SA.partition_to_pseudo[i]);
4057
4058       /* If this decl was marked as living in multiple places, reset
4059          this now to NULL.  */
4060       if (DECL_RTL_IF_SET (var) == pc_rtx)
4061         SET_DECL_RTL (var, NULL);
4062
4063       /* Some RTL parts really want to look at DECL_RTL(x) when x
4064          was a decl marked in REG_ATTR or MEM_ATTR.  We could use
4065          SET_DECL_RTL here making this available, but that would mean
4066          to select one of the potentially many RTLs for one DECL.  Instead
4067          of doing that we simply reset the MEM_EXPR of the RTL in question,
4068          then nobody can get at it and hence nobody can call DECL_RTL on it.  */
4069       if (!DECL_RTL_SET_P (var))
4070         {
4071           if (MEM_P (SA.partition_to_pseudo[i]))
4072             set_mem_expr (SA.partition_to_pseudo[i], NULL);
4073         }
4074     }
4075
4076   /* If this function is `main', emit a call to `__main'
4077      to run global initializers, etc.  */
4078   if (DECL_NAME (current_function_decl)
4079       && MAIN_NAME_P (DECL_NAME (current_function_decl))
4080       && DECL_FILE_SCOPE_P (current_function_decl))
4081     expand_main_function ();
4082
4083   /* Initialize the stack_protect_guard field.  This must happen after the
4084      call to __main (if any) so that the external decl is initialized.  */
4085   if (crtl->stack_protect_guard)
4086     stack_protect_prologue ();
4087
4088   expand_phi_nodes (&SA);
4089
4090   /* Register rtl specific functions for cfg.  */
4091   rtl_register_cfg_hooks ();
4092
4093   init_block = construct_init_block ();
4094
4095   /* Clear EDGE_EXECUTABLE on the entry edge(s).  It is cleaned from the
4096      remaining edges later.  */
4097   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
4098     e->flags &= ~EDGE_EXECUTABLE;
4099
4100   lab_rtx_for_bb = pointer_map_create ();
4101   FOR_BB_BETWEEN (bb, init_block->next_bb, EXIT_BLOCK_PTR, next_bb)
4102     bb = expand_gimple_basic_block (bb);
4103
4104   if (MAY_HAVE_DEBUG_INSNS)
4105     expand_debug_locations ();
4106
4107   execute_free_datastructures ();
4108   timevar_push (TV_OUT_OF_SSA);
4109   finish_out_of_ssa (&SA);
4110   timevar_pop (TV_OUT_OF_SSA);
4111
4112   timevar_push (TV_POST_EXPAND);
4113   /* We are no longer in SSA form.  */
4114   cfun->gimple_df->in_ssa_p = false;
4115
4116   /* Expansion is used by optimization passes too, set maybe_hot_insn_p
4117      conservatively to true until they are all profile aware.  */
4118   pointer_map_destroy (lab_rtx_for_bb);
4119   free_histograms ();
4120
4121   construct_exit_block ();
4122   set_curr_insn_block (DECL_INITIAL (current_function_decl));
4123   insn_locators_finalize ();
4124
4125   /* Zap the tree EH table.  */
4126   set_eh_throw_stmt_table (cfun, NULL);
4127
4128   /* We need JUMP_LABEL be set in order to redirect jumps, and hence
4129      split edges which edge insertions might do.  */
4130   rebuild_jump_labels (get_insns ());
4131
4132   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
4133     {
4134       edge e;
4135       edge_iterator ei;
4136       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
4137         {
4138           if (e->insns.r)
4139             {
4140               rebuild_jump_labels_chain (e->insns.r);
4141               /* Avoid putting insns before parm_birth_insn.  */
4142               if (e->src == ENTRY_BLOCK_PTR
4143                   && single_succ_p (ENTRY_BLOCK_PTR)
4144                   && parm_birth_insn)
4145                 {
4146                   rtx insns = e->insns.r;
4147                   e->insns.r = NULL_RTX;
4148                   emit_insn_after_noloc (insns, parm_birth_insn, e->dest);
4149                 }
4150               else
4151                 commit_one_edge_insertion (e);
4152             }
4153           else
4154             ei_next (&ei);
4155         }
4156     }
4157
4158   /* We're done expanding trees to RTL.  */
4159   currently_expanding_to_rtl = 0;
4160
4161   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb, EXIT_BLOCK_PTR, next_bb)
4162     {
4163       edge e;
4164       edge_iterator ei;
4165       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
4166         {
4167           /* Clear EDGE_EXECUTABLE.  This flag is never used in the backend.  */
4168           e->flags &= ~EDGE_EXECUTABLE;
4169
4170           /* At the moment not all abnormal edges match the RTL
4171              representation.  It is safe to remove them here as
4172              find_many_sub_basic_blocks will rediscover them.
4173              In the future we should get this fixed properly.  */
4174           if ((e->flags & EDGE_ABNORMAL)
4175               && !(e->flags & EDGE_SIBCALL))
4176             remove_edge (e);
4177           else
4178             ei_next (&ei);
4179         }
4180     }
4181
4182   blocks = sbitmap_alloc (last_basic_block);
4183   sbitmap_ones (blocks);
4184   find_many_sub_basic_blocks (blocks);
4185   sbitmap_free (blocks);
4186   purge_all_dead_edges ();
4187
4188   compact_blocks ();
4189
4190   expand_stack_alignment ();
4191
4192 #ifdef ENABLE_CHECKING
4193   verify_flow_info ();
4194 #endif
4195
4196   /* There's no need to defer outputting this function any more; we
4197      know we want to output it.  */
4198   DECL_DEFER_OUTPUT (current_function_decl) = 0;
4199
4200   /* Now that we're done expanding trees to RTL, we shouldn't have any
4201      more CONCATs anywhere.  */
4202   generating_concat_p = 0;
4203
4204   if (dump_file)
4205     {
4206       fprintf (dump_file,
4207                "\n\n;;\n;; Full RTL generated for this function:\n;;\n");
4208       /* And the pass manager will dump RTL for us.  */
4209     }
4210
4211   /* If we're emitting a nested function, make sure its parent gets
4212      emitted as well.  Doing otherwise confuses debug info.  */
4213   {
4214     tree parent;
4215     for (parent = DECL_CONTEXT (current_function_decl);
4216          parent != NULL_TREE;
4217          parent = get_containing_scope (parent))
4218       if (TREE_CODE (parent) == FUNCTION_DECL)
4219         TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (parent)) = 1;
4220   }
4221
4222   /* We are now committed to emitting code for this function.  Do any
4223      preparation, such as emitting abstract debug info for the inline
4224      before it gets mangled by optimization.  */
4225   if (cgraph_function_possibly_inlined_p (current_function_decl))
4226     (*debug_hooks->outlining_inline_function) (current_function_decl);
4227
4228   TREE_ASM_WRITTEN (current_function_decl) = 1;
4229
4230   /* After expanding, the return labels are no longer needed. */
4231   return_label = NULL;
4232   naked_return_label = NULL;
4233   /* Tag the blocks with a depth number so that change_scope can find
4234      the common parent easily.  */
4235   set_block_levels (DECL_INITIAL (cfun->decl), 0);
4236   default_rtl_profile ();
4237   timevar_pop (TV_POST_EXPAND);
4238   return 0;
4239 }
4240
4241 struct rtl_opt_pass pass_expand =
4242 {
4243  {
4244   RTL_PASS,
4245   "expand",                             /* name */
4246   NULL,                                 /* gate */
4247   gimple_expand_cfg,                    /* execute */
4248   NULL,                                 /* sub */
4249   NULL,                                 /* next */
4250   0,                                    /* static_pass_number */
4251   TV_EXPAND,                            /* tv_id */
4252   PROP_ssa | PROP_gimple_leh | PROP_cfg
4253     | PROP_gimple_lcx,                  /* properties_required */
4254   PROP_rtl,                             /* properties_provided */
4255   PROP_ssa | PROP_trees,                /* properties_destroyed */
4256   TODO_verify_ssa | TODO_verify_flow
4257     | TODO_verify_stmts,                /* todo_flags_start */
4258   TODO_dump_func
4259   | TODO_ggc_collect                    /* todo_flags_finish */
4260  }
4261 };