Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / contrib / gcc-4.1 / gcc / cfgexpand.c
1 /* A pass for lowering trees to RTL.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.  */
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 "toplev.h"
40 #include "debug.h"
41 #include "params.h"
42
43 /* Verify that there is exactly single jump instruction since last and attach
44    REG_BR_PROB note specifying probability.
45    ??? We really ought to pass the probability down to RTL expanders and let it
46    re-distribute it when the conditional expands into multiple conditionals.
47    This is however difficult to do.  */
48 static void
49 add_reg_br_prob_note (FILE *dump_file, rtx last, int probability)
50 {
51   if (profile_status == PROFILE_ABSENT)
52     return;
53   for (last = NEXT_INSN (last); last && NEXT_INSN (last); last = NEXT_INSN (last))
54     if (JUMP_P (last))
55       {
56         /* It is common to emit condjump-around-jump sequence when we don't know
57            how to reverse the conditional.  Special case this.  */
58         if (!any_condjump_p (last)
59             || !JUMP_P (NEXT_INSN (last))
60             || !simplejump_p (NEXT_INSN (last))
61             || !NEXT_INSN (NEXT_INSN (last))
62             || !BARRIER_P (NEXT_INSN (NEXT_INSN (last)))
63             || !NEXT_INSN (NEXT_INSN (NEXT_INSN (last)))
64             || !LABEL_P (NEXT_INSN (NEXT_INSN (NEXT_INSN (last))))
65             || NEXT_INSN (NEXT_INSN (NEXT_INSN (NEXT_INSN (last)))))
66           goto failed;
67         gcc_assert (!find_reg_note (last, REG_BR_PROB, 0));
68         REG_NOTES (last)
69           = gen_rtx_EXPR_LIST (REG_BR_PROB,
70                                GEN_INT (REG_BR_PROB_BASE - probability),
71                                REG_NOTES (last));
72         return;
73       }
74   if (!last || !JUMP_P (last) || !any_condjump_p (last))
75     goto failed;
76   gcc_assert (!find_reg_note (last, REG_BR_PROB, 0));
77   REG_NOTES (last)
78     = gen_rtx_EXPR_LIST (REG_BR_PROB,
79                          GEN_INT (probability), REG_NOTES (last));
80   return;
81 failed:
82   if (dump_file)
83     fprintf (dump_file, "Failed to add probability note\n");
84 }
85
86
87 #ifndef LOCAL_ALIGNMENT
88 #define LOCAL_ALIGNMENT(TYPE, ALIGNMENT) ALIGNMENT
89 #endif
90
91 #ifndef STACK_ALIGNMENT_NEEDED
92 #define STACK_ALIGNMENT_NEEDED 1
93 #endif
94
95
96 /* This structure holds data relevant to one variable that will be
97    placed in a stack slot.  */
98 struct stack_var
99 {
100   /* The Variable.  */
101   tree decl;
102
103   /* The offset of the variable.  During partitioning, this is the
104      offset relative to the partition.  After partitioning, this
105      is relative to the stack frame.  */
106   HOST_WIDE_INT offset;
107
108   /* Initially, the size of the variable.  Later, the size of the partition,
109      if this variable becomes it's partition's representative.  */
110   HOST_WIDE_INT size;
111
112   /* The *byte* alignment required for this variable.  Or as, with the
113      size, the alignment for this partition.  */
114   unsigned int alignb;
115
116   /* The partition representative.  */
117   size_t representative;
118
119   /* The next stack variable in the partition, or EOC.  */
120   size_t next;
121 };
122
123 #define EOC  ((size_t)-1)
124
125 /* We have an array of such objects while deciding allocation.  */
126 static struct stack_var *stack_vars;
127 static size_t stack_vars_alloc;
128 static size_t stack_vars_num;
129
130 /* An array of indicies such that stack_vars[stack_vars_sorted[i]].size
131    is non-decreasing.  */
132 static size_t *stack_vars_sorted;
133
134 /* We have an interference graph between such objects.  This graph
135    is lower triangular.  */
136 static bool *stack_vars_conflict;
137 static size_t stack_vars_conflict_alloc;
138
139 /* The phase of the stack frame.  This is the known misalignment of
140    virtual_stack_vars_rtx from PREFERRED_STACK_BOUNDARY.  That is,
141    (frame_offset+frame_phase) % PREFERRED_STACK_BOUNDARY == 0.  */
142 static int frame_phase;
143
144 /* Used during expand_used_vars to remember if we saw any decls for
145    which we'd like to enable stack smashing protection.  */
146 static bool has_protected_decls;
147
148 /* Used during expand_used_vars.  Remember if we say a character buffer
149    smaller than our cutoff threshold.  Used for -Wstack-protector.  */
150 static bool has_short_buffer;
151
152 /* Discover the byte alignment to use for DECL.  Ignore alignment
153    we can't do with expected alignment of the stack boundary.  */
154
155 static unsigned int
156 get_decl_align_unit (tree decl)
157 {
158   unsigned int align;
159
160   align = DECL_ALIGN (decl);
161   align = LOCAL_ALIGNMENT (TREE_TYPE (decl), align);
162   if (align > PREFERRED_STACK_BOUNDARY)
163     align = PREFERRED_STACK_BOUNDARY;
164   if (cfun->stack_alignment_needed < align)
165     cfun->stack_alignment_needed = align;
166
167   return align / BITS_PER_UNIT;
168 }
169
170 /* Allocate SIZE bytes at byte alignment ALIGN from the stack frame.
171    Return the frame offset.  */
172
173 static HOST_WIDE_INT
174 alloc_stack_frame_space (HOST_WIDE_INT size, HOST_WIDE_INT align)
175 {
176   HOST_WIDE_INT offset, new_frame_offset;
177
178   new_frame_offset = frame_offset;
179   if (FRAME_GROWS_DOWNWARD)
180     {
181       new_frame_offset -= size + frame_phase;
182       new_frame_offset &= -align;
183       new_frame_offset += frame_phase;
184       offset = new_frame_offset;
185     }
186   else
187     {
188       new_frame_offset -= frame_phase;
189       new_frame_offset += align - 1;
190       new_frame_offset &= -align;
191       new_frame_offset += frame_phase;
192       offset = new_frame_offset;
193       new_frame_offset += size;
194     }
195   frame_offset = new_frame_offset;
196
197   return offset;
198 }
199
200 /* Accumulate DECL into STACK_VARS.  */
201
202 static void
203 add_stack_var (tree decl)
204 {
205   if (stack_vars_num >= stack_vars_alloc)
206     {
207       if (stack_vars_alloc)
208         stack_vars_alloc = stack_vars_alloc * 3 / 2;
209       else
210         stack_vars_alloc = 32;
211       stack_vars
212         = XRESIZEVEC (struct stack_var, stack_vars, stack_vars_alloc);
213     }
214   stack_vars[stack_vars_num].decl = decl;
215   stack_vars[stack_vars_num].offset = 0;
216   stack_vars[stack_vars_num].size = tree_low_cst (DECL_SIZE_UNIT (decl), 1);
217   stack_vars[stack_vars_num].alignb = get_decl_align_unit (decl);
218
219   /* All variables are initially in their own partition.  */
220   stack_vars[stack_vars_num].representative = stack_vars_num;
221   stack_vars[stack_vars_num].next = EOC;
222
223   /* Ensure that this decl doesn't get put onto the list twice.  */
224   SET_DECL_RTL (decl, pc_rtx);
225
226   stack_vars_num++;
227 }
228
229 /* Compute the linear index of a lower-triangular coordinate (I, J).  */
230
231 static size_t
232 triangular_index (size_t i, size_t j)
233 {
234   if (i < j)
235     {
236       size_t t;
237       t = i, i = j, j = t;
238     }
239   return (i * (i + 1)) / 2 + j;
240 }
241
242 /* Ensure that STACK_VARS_CONFLICT is large enough for N objects.  */
243
244 static void
245 resize_stack_vars_conflict (size_t n)
246 {
247   size_t size = triangular_index (n-1, n-1) + 1;
248
249   if (size <= stack_vars_conflict_alloc)
250     return;
251
252   stack_vars_conflict = XRESIZEVEC (bool, stack_vars_conflict, size);
253   memset (stack_vars_conflict + stack_vars_conflict_alloc, 0,
254           (size - stack_vars_conflict_alloc) * sizeof (bool));
255   stack_vars_conflict_alloc = size;
256 }
257
258 /* Make the decls associated with luid's X and Y conflict.  */
259
260 static void
261 add_stack_var_conflict (size_t x, size_t y)
262 {
263   size_t index = triangular_index (x, y);
264   gcc_assert (index < stack_vars_conflict_alloc);
265   stack_vars_conflict[index] = true;
266 }
267
268 /* Check whether the decls associated with luid's X and Y conflict.  */
269
270 static bool
271 stack_var_conflict_p (size_t x, size_t y)
272 {
273   size_t index = triangular_index (x, y);
274   gcc_assert (index < stack_vars_conflict_alloc);
275   return stack_vars_conflict[index];
276 }
277  
278 /* Returns true if TYPE is or contains a union type.  */
279
280 static bool
281 aggregate_contains_union_type (tree type)
282 {
283   tree field;
284
285   if (TREE_CODE (type) == UNION_TYPE
286       || TREE_CODE (type) == QUAL_UNION_TYPE)
287     return true;
288   if (TREE_CODE (type) == ARRAY_TYPE)
289     return aggregate_contains_union_type (TREE_TYPE (type));
290   if (TREE_CODE (type) != RECORD_TYPE)
291     return false;
292
293   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
294     if (TREE_CODE (field) == FIELD_DECL)
295       if (aggregate_contains_union_type (TREE_TYPE (field)))
296         return true;
297
298   return false;
299 }
300
301 /* A subroutine of expand_used_vars.  If two variables X and Y have alias
302    sets that do not conflict, then do add a conflict for these variables
303    in the interference graph.  We also need to make sure to add conflicts
304    for union containing structures.  Else RTL alias analysis comes along
305    and due to type based aliasing rules decides that for two overlapping
306    union temporaries { short s; int i; } accesses to the same mem through
307    different types may not alias and happily reorders stores across
308    life-time boundaries of the temporaries (See PR25654).
309    We also have to mind MEM_IN_STRUCT_P and MEM_SCALAR_P.  */
310
311 static void
312 add_alias_set_conflicts (void)
313 {
314   size_t i, j, n = stack_vars_num;
315
316   for (i = 0; i < n; ++i)
317     {
318       tree type_i = TREE_TYPE (stack_vars[i].decl);
319       bool aggr_i = AGGREGATE_TYPE_P (type_i);
320       bool contains_union;
321
322       contains_union = aggregate_contains_union_type (type_i);
323       for (j = 0; j < i; ++j)
324         {
325           tree type_j = TREE_TYPE (stack_vars[j].decl);
326           bool aggr_j = AGGREGATE_TYPE_P (type_j);
327           if (aggr_i != aggr_j
328               /* Either the objects conflict by means of type based
329                  aliasing rules, or we need to add a conflict.  */
330               || !objects_must_conflict_p (type_i, type_j)
331               /* In case the types do not conflict ensure that access
332                  to elements will conflict.  In case of unions we have
333                  to be careful as type based aliasing rules may say
334                  access to the same memory does not conflict.  So play
335                  safe and add a conflict in this case.  */
336               || contains_union)
337             add_stack_var_conflict (i, j);
338         }
339     }
340 }
341
342 /* A subroutine of partition_stack_vars.  A comparison function for qsort,
343    sorting an array of indicies by the size of the object.  */
344
345 static int
346 stack_var_size_cmp (const void *a, const void *b)
347 {
348   HOST_WIDE_INT sa = stack_vars[*(const size_t *)a].size;
349   HOST_WIDE_INT sb = stack_vars[*(const size_t *)b].size;
350
351   if (sa < sb)
352     return -1;
353   if (sa > sb)
354     return 1;
355   return 0;
356 }
357
358 /* A subroutine of partition_stack_vars.  The UNION portion of a UNION/FIND
359    partitioning algorithm.  Partitions A and B are known to be non-conflicting.
360    Merge them into a single partition A.
361
362    At the same time, add OFFSET to all variables in partition B.  At the end
363    of the partitioning process we've have a nice block easy to lay out within
364    the stack frame.  */
365
366 static void
367 union_stack_vars (size_t a, size_t b, HOST_WIDE_INT offset)
368 {
369   size_t i, last;
370
371   /* Update each element of partition B with the given offset,
372      and merge them into partition A.  */
373   for (last = i = b; i != EOC; last = i, i = stack_vars[i].next)
374     {
375       stack_vars[i].offset += offset;
376       stack_vars[i].representative = a;
377     }
378   stack_vars[last].next = stack_vars[a].next;
379   stack_vars[a].next = b;
380
381   /* Update the required alignment of partition A to account for B.  */
382   if (stack_vars[a].alignb < stack_vars[b].alignb)
383     stack_vars[a].alignb = stack_vars[b].alignb;
384
385   /* Update the interference graph and merge the conflicts.  */
386   for (last = stack_vars_num, i = 0; i < last; ++i)
387     if (stack_var_conflict_p (b, i))
388       add_stack_var_conflict (a, i);
389 }
390
391 /* A subroutine of expand_used_vars.  Binpack the variables into
392    partitions constrained by the interference graph.  The overall
393    algorithm used is as follows:
394
395         Sort the objects by size.
396         For each object A {
397           S = size(A)
398           O = 0
399           loop {
400             Look for the largest non-conflicting object B with size <= S.
401             UNION (A, B)
402             offset(B) = O
403             O += size(B)
404             S -= size(B)
405           }
406         }
407 */
408
409 static void
410 partition_stack_vars (void)
411 {
412   size_t si, sj, n = stack_vars_num;
413
414   stack_vars_sorted = XNEWVEC (size_t, stack_vars_num);
415   for (si = 0; si < n; ++si)
416     stack_vars_sorted[si] = si;
417
418   if (n == 1)
419     return;
420
421   qsort (stack_vars_sorted, n, sizeof (size_t), stack_var_size_cmp);
422
423   /* Special case: detect when all variables conflict, and thus we can't
424      do anything during the partitioning loop.  It isn't uncommon (with
425      C code at least) to declare all variables at the top of the function,
426      and if we're not inlining, then all variables will be in the same scope.
427      Take advantage of very fast libc routines for this scan.  */
428   gcc_assert (sizeof(bool) == sizeof(char));
429   if (memchr (stack_vars_conflict, false, stack_vars_conflict_alloc) == NULL)
430     return;
431
432   for (si = 0; si < n; ++si)
433     {
434       size_t i = stack_vars_sorted[si];
435       HOST_WIDE_INT isize = stack_vars[i].size;
436       HOST_WIDE_INT offset = 0;
437
438       for (sj = si; sj-- > 0; )
439         {
440           size_t j = stack_vars_sorted[sj];
441           HOST_WIDE_INT jsize = stack_vars[j].size;
442           unsigned int jalign = stack_vars[j].alignb;
443
444           /* Ignore objects that aren't partition representatives.  */
445           if (stack_vars[j].representative != j)
446             continue;
447
448           /* Ignore objects too large for the remaining space.  */
449           if (isize < jsize)
450             continue;
451
452           /* Ignore conflicting objects.  */
453           if (stack_var_conflict_p (i, j))
454             continue;
455
456           /* Refine the remaining space check to include alignment.  */
457           if (offset & (jalign - 1))
458             {
459               HOST_WIDE_INT toff = offset;
460               toff += jalign - 1;
461               toff &= -(HOST_WIDE_INT)jalign;
462               if (isize - (toff - offset) < jsize)
463                 continue;
464
465               isize -= toff - offset;
466               offset = toff;
467             }
468
469           /* UNION the objects, placing J at OFFSET.  */
470           union_stack_vars (i, j, offset);
471
472           isize -= jsize;
473           if (isize == 0)
474             break;
475         }
476     }
477 }
478
479 /* A debugging aid for expand_used_vars.  Dump the generated partitions.  */
480
481 static void
482 dump_stack_var_partition (void)
483 {
484   size_t si, i, j, n = stack_vars_num;
485
486   for (si = 0; si < n; ++si)
487     {
488       i = stack_vars_sorted[si];
489
490       /* Skip variables that aren't partition representatives, for now.  */
491       if (stack_vars[i].representative != i)
492         continue;
493
494       fprintf (dump_file, "Partition %lu: size " HOST_WIDE_INT_PRINT_DEC
495                " align %u\n", (unsigned long) i, stack_vars[i].size,
496                stack_vars[i].alignb);
497
498       for (j = i; j != EOC; j = stack_vars[j].next)
499         {
500           fputc ('\t', dump_file);
501           print_generic_expr (dump_file, stack_vars[j].decl, dump_flags);
502           fprintf (dump_file, ", offset " HOST_WIDE_INT_PRINT_DEC "\n",
503                    stack_vars[i].offset);
504         }
505     }
506 }
507
508 /* Assign rtl to DECL at frame offset OFFSET.  */
509
510 static void
511 expand_one_stack_var_at (tree decl, HOST_WIDE_INT offset)
512 {
513   HOST_WIDE_INT align;
514   rtx x;
515   
516   /* If this fails, we've overflowed the stack frame.  Error nicely?  */
517   gcc_assert (offset == trunc_int_for_mode (offset, Pmode));
518
519   x = plus_constant (virtual_stack_vars_rtx, offset);
520   x = gen_rtx_MEM (DECL_MODE (decl), x);
521
522   /* Set alignment we actually gave this decl.  */
523   offset -= frame_phase;
524   align = offset & -offset;
525   align *= BITS_PER_UNIT;
526   if (align > STACK_BOUNDARY || align == 0)
527     align = STACK_BOUNDARY;
528   DECL_ALIGN (decl) = align;
529   DECL_USER_ALIGN (decl) = 0;
530
531   set_mem_attributes (x, decl, true);
532   SET_DECL_RTL (decl, x);
533 }
534
535 /* A subroutine of expand_used_vars.  Give each partition representative
536    a unique location within the stack frame.  Update each partition member
537    with that location.  */
538
539 static void
540 expand_stack_vars (bool (*pred) (tree))
541 {
542   size_t si, i, j, n = stack_vars_num;
543
544   for (si = 0; si < n; ++si)
545     {
546       HOST_WIDE_INT offset;
547
548       i = stack_vars_sorted[si];
549
550       /* Skip variables that aren't partition representatives, for now.  */
551       if (stack_vars[i].representative != i)
552         continue;
553
554       /* Skip variables that have already had rtl assigned.  See also
555          add_stack_var where we perpetrate this pc_rtx hack.  */
556       if (DECL_RTL (stack_vars[i].decl) != pc_rtx)
557         continue;
558
559       /* Check the predicate to see whether this variable should be 
560          allocated in this pass.  */
561       if (pred && !pred (stack_vars[i].decl))
562         continue;
563
564       offset = alloc_stack_frame_space (stack_vars[i].size,
565                                         stack_vars[i].alignb);
566
567       /* Create rtl for each variable based on their location within the
568          partition.  */
569       for (j = i; j != EOC; j = stack_vars[j].next)
570         expand_one_stack_var_at (stack_vars[j].decl,
571                                  stack_vars[j].offset + offset);
572     }
573 }
574
575 /* A subroutine of expand_one_var.  Called to immediately assign rtl
576    to a variable to be allocated in the stack frame.  */
577
578 static void
579 expand_one_stack_var (tree var)
580 {
581   HOST_WIDE_INT size, offset, align;
582
583   size = tree_low_cst (DECL_SIZE_UNIT (var), 1);
584   align = get_decl_align_unit (var);
585   offset = alloc_stack_frame_space (size, align);
586
587   expand_one_stack_var_at (var, offset);
588 }
589
590 /* A subroutine of expand_one_var.  Called to assign rtl
591    to a TREE_STATIC VAR_DECL.  */
592
593 static void
594 expand_one_static_var (tree var)
595 {
596   /* In unit-at-a-time all the static variables are expanded at the end
597      of compilation process.  */
598   if (flag_unit_at_a_time)
599     return;
600   /* If this is an inlined copy of a static local variable,
601      look up the original.  */
602   var = DECL_ORIGIN (var);
603
604   /* If we've already processed this variable because of that, do nothing.  */
605   if (TREE_ASM_WRITTEN (var))
606     return;
607
608   /* Give the front end a chance to do whatever.  In practice, this is
609      resolving duplicate names for IMA in C.  */
610   if (lang_hooks.expand_decl (var))
611     return;
612
613   /* Otherwise, just emit the variable.  */
614   rest_of_decl_compilation (var, 0, 0);
615 }
616
617 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
618    that will reside in a hard register.  */
619
620 static void
621 expand_one_hard_reg_var (tree var)
622 {
623   rest_of_decl_compilation (var, 0, 0);
624 }
625
626 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
627    that will reside in a pseudo register.  */
628
629 static void
630 expand_one_register_var (tree var)
631 {
632   tree type = TREE_TYPE (var);
633   int unsignedp = TYPE_UNSIGNED (type);
634   enum machine_mode reg_mode
635     = promote_mode (type, DECL_MODE (var), &unsignedp, 0);
636   rtx x = gen_reg_rtx (reg_mode);
637
638   SET_DECL_RTL (var, x);
639
640   /* Note if the object is a user variable.  */
641   if (!DECL_ARTIFICIAL (var))
642     {
643       mark_user_reg (x);
644
645       /* Trust user variables which have a pointer type to really
646          be pointers.  Do not trust compiler generated temporaries
647          as our type system is totally busted as it relates to
648          pointer arithmetic which translates into lots of compiler
649          generated objects with pointer types, but which are not really
650          pointers.  */
651       if (POINTER_TYPE_P (type))
652         mark_reg_pointer (x, TYPE_ALIGN (TREE_TYPE (TREE_TYPE (var))));
653     }
654 }
655
656 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL that
657    has some associated error, e.g. its type is error-mark.  We just need
658    to pick something that won't crash the rest of the compiler.  */
659
660 static void
661 expand_one_error_var (tree var)
662 {
663   enum machine_mode mode = DECL_MODE (var);
664   rtx x;
665
666   if (mode == BLKmode)
667     x = gen_rtx_MEM (BLKmode, const0_rtx);
668   else if (mode == VOIDmode)
669     x = const0_rtx;
670   else
671     x = gen_reg_rtx (mode);
672
673   SET_DECL_RTL (var, x);
674 }
675
676 /* A subroutine of expand_one_var.  VAR is a variable that will be 
677    allocated to the local stack frame.  Return true if we wish to
678    add VAR to STACK_VARS so that it will be coalesced with other
679    variables.  Return false to allocate VAR immediately.
680
681    This function is used to reduce the number of variables considered
682    for coalescing, which reduces the size of the quadratic problem.  */
683
684 static bool
685 defer_stack_allocation (tree var, bool toplevel)
686 {
687   /* If stack protection is enabled, *all* stack variables must be deferred,
688      so that we can re-order the strings to the top of the frame.  */
689   if (flag_stack_protect)
690     return true;
691
692   /* Variables in the outermost scope automatically conflict with
693      every other variable.  The only reason to want to defer them
694      at all is that, after sorting, we can more efficiently pack
695      small variables in the stack frame.  Continue to defer at -O2.  */
696   if (toplevel && optimize < 2)
697     return false;
698
699   /* Without optimization, *most* variables are allocated from the
700      stack, which makes the quadratic problem large exactly when we
701      want compilation to proceed as quickly as possible.  On the 
702      other hand, we don't want the function's stack frame size to
703      get completely out of hand.  So we avoid adding scalars and
704      "small" aggregates to the list at all.  */
705   if (optimize == 0 && tree_low_cst (DECL_SIZE_UNIT (var), 1) < 32)
706     return false;
707
708   return true;
709 }
710
711 /* A subroutine of expand_used_vars.  Expand one variable according to
712    its flavor.  Variables to be placed on the stack are not actually
713    expanded yet, merely recorded.  */
714
715 static void
716 expand_one_var (tree var, bool toplevel)
717 {
718   if (TREE_CODE (var) != VAR_DECL)
719     lang_hooks.expand_decl (var);
720   else if (DECL_EXTERNAL (var))
721     ;
722   else if (DECL_HAS_VALUE_EXPR_P (var))
723     ;
724   else if (TREE_STATIC (var))
725     expand_one_static_var (var);
726   else if (DECL_RTL_SET_P (var))
727     ;
728   else if (TREE_TYPE (var) == error_mark_node)
729     expand_one_error_var (var);
730   else if (DECL_HARD_REGISTER (var))
731     expand_one_hard_reg_var (var);
732   else if (use_register_for_decl (var))
733     expand_one_register_var (var);
734   else if (defer_stack_allocation (var, toplevel))
735     add_stack_var (var);
736   else
737     expand_one_stack_var (var);
738 }
739
740 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
741    expanding variables.  Those variables that can be put into registers
742    are allocated pseudos; those that can't are put on the stack.
743
744    TOPLEVEL is true if this is the outermost BLOCK.  */
745
746 static void
747 expand_used_vars_for_block (tree block, bool toplevel)
748 {
749   size_t i, j, old_sv_num, this_sv_num, new_sv_num;
750   tree t;
751
752   old_sv_num = toplevel ? 0 : stack_vars_num;
753
754   /* Expand all variables at this level.  */
755   for (t = BLOCK_VARS (block); t ; t = TREE_CHAIN (t))
756     if (TREE_USED (t))
757       expand_one_var (t, toplevel);
758
759   this_sv_num = stack_vars_num;
760
761   /* Expand all variables at containing levels.  */
762   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
763     expand_used_vars_for_block (t, false);
764
765   /* Since we do not track exact variable lifetimes (which is not even
766      possible for varibles whose address escapes), we mirror the block
767      tree in the interference graph.  Here we cause all variables at this
768      level, and all sublevels, to conflict.  Do make certain that a
769      variable conflicts with itself.  */
770   if (old_sv_num < this_sv_num)
771     {
772       new_sv_num = stack_vars_num;
773       resize_stack_vars_conflict (new_sv_num);
774
775       for (i = old_sv_num; i < new_sv_num; ++i)
776         for (j = i < this_sv_num ? i+1 : this_sv_num; j-- > old_sv_num ;)
777           add_stack_var_conflict (i, j);
778     }
779 }
780
781 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
782    and clear TREE_USED on all local variables.  */
783
784 static void
785 clear_tree_used (tree block)
786 {
787   tree t;
788
789   for (t = BLOCK_VARS (block); t ; t = TREE_CHAIN (t))
790     /* if (!TREE_STATIC (t) && !DECL_EXTERNAL (t)) */
791       TREE_USED (t) = 0;
792
793   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
794     clear_tree_used (t);
795 }
796
797 /* Examine TYPE and determine a bit mask of the following features.  */
798
799 #define SPCT_HAS_LARGE_CHAR_ARRAY       1
800 #define SPCT_HAS_SMALL_CHAR_ARRAY       2
801 #define SPCT_HAS_ARRAY                  4
802 #define SPCT_HAS_AGGREGATE              8
803
804 static unsigned int
805 stack_protect_classify_type (tree type)
806 {
807   unsigned int ret = 0;
808   tree t;
809
810   switch (TREE_CODE (type))
811     {
812     case ARRAY_TYPE:
813       t = TYPE_MAIN_VARIANT (TREE_TYPE (type));
814       if (t == char_type_node
815           || t == signed_char_type_node
816           || t == unsigned_char_type_node)
817         {
818           unsigned HOST_WIDE_INT max = PARAM_VALUE (PARAM_SSP_BUFFER_SIZE);
819           unsigned HOST_WIDE_INT len;
820
821           if (!TYPE_SIZE_UNIT (type)
822               || !host_integerp (TYPE_SIZE_UNIT (type), 1))
823             len = max;
824           else
825             len = tree_low_cst (TYPE_SIZE_UNIT (type), 1);
826
827           if (len < max)
828             ret = SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_ARRAY;
829           else
830             ret = SPCT_HAS_LARGE_CHAR_ARRAY | SPCT_HAS_ARRAY;
831         }
832       else
833         ret = SPCT_HAS_ARRAY;
834       break;
835
836     case UNION_TYPE:
837     case QUAL_UNION_TYPE:
838     case RECORD_TYPE:
839       ret = SPCT_HAS_AGGREGATE;
840       for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
841         if (TREE_CODE (t) == FIELD_DECL)
842           ret |= stack_protect_classify_type (TREE_TYPE (t));
843       break;
844
845     default:
846       break;
847     }
848
849   return ret;
850 }
851
852 /* Return nonzero if DECL should be segregated into the "vulnerable" upper
853    part of the local stack frame.  Remember if we ever return nonzero for
854    any variable in this function.  The return value is the phase number in
855    which the variable should be allocated.  */
856
857 static int
858 stack_protect_decl_phase (tree decl)
859 {
860   unsigned int bits = stack_protect_classify_type (TREE_TYPE (decl));
861   int ret = 0;
862
863   if (bits & SPCT_HAS_SMALL_CHAR_ARRAY)
864     has_short_buffer = true;
865
866   if (flag_stack_protect == 2)
867     {
868       if ((bits & (SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_LARGE_CHAR_ARRAY))
869           && !(bits & SPCT_HAS_AGGREGATE))
870         ret = 1;
871       else if (bits & SPCT_HAS_ARRAY)
872         ret = 2;
873     }
874   else
875     ret = (bits & SPCT_HAS_LARGE_CHAR_ARRAY) != 0;
876
877   if (ret)
878     has_protected_decls = true;
879
880   return ret;
881 }
882
883 /* Two helper routines that check for phase 1 and phase 2.  These are used
884    as callbacks for expand_stack_vars.  */
885
886 static bool
887 stack_protect_decl_phase_1 (tree decl)
888 {
889   return stack_protect_decl_phase (decl) == 1;
890 }
891
892 static bool
893 stack_protect_decl_phase_2 (tree decl)
894 {
895   return stack_protect_decl_phase (decl) == 2;
896 }
897
898 /* Ensure that variables in different stack protection phases conflict
899    so that they are not merged and share the same stack slot.  */
900
901 static void
902 add_stack_protection_conflicts (void)
903 {
904   size_t i, j, n = stack_vars_num;
905   unsigned char *phase;
906
907   phase = XNEWVEC (unsigned char, n);
908   for (i = 0; i < n; ++i)
909     phase[i] = stack_protect_decl_phase (stack_vars[i].decl);
910
911   for (i = 0; i < n; ++i)
912     {
913       unsigned char ph_i = phase[i];
914       for (j = 0; j < i; ++j)
915         if (ph_i != phase[j])
916           add_stack_var_conflict (i, j);
917     }
918
919   XDELETEVEC (phase);
920 }
921
922 /* Create a decl for the guard at the top of the stack frame.  */
923
924 static void
925 create_stack_guard (void)
926 {
927   tree guard = build_decl (VAR_DECL, NULL, ptr_type_node);
928   TREE_THIS_VOLATILE (guard) = 1;
929   TREE_USED (guard) = 1;
930   expand_one_stack_var (guard);
931   cfun->stack_protect_guard = guard;
932 }
933
934 /* Expand all variables used in the function.  */
935
936 static void
937 expand_used_vars (void)
938 {
939   tree t, outer_block = DECL_INITIAL (current_function_decl);
940
941   /* Compute the phase of the stack frame for this function.  */
942   {
943     int align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
944     int off = STARTING_FRAME_OFFSET % align;
945     frame_phase = off ? align - off : 0;
946   }
947
948   /* Set TREE_USED on all variables in the unexpanded_var_list.  */
949   for (t = cfun->unexpanded_var_list; t; t = TREE_CHAIN (t))
950     TREE_USED (TREE_VALUE (t)) = 1;
951
952   /* Clear TREE_USED on all variables associated with a block scope.  */
953   clear_tree_used (outer_block);
954
955   /* Initialize local stack smashing state.  */
956   has_protected_decls = false;
957   has_short_buffer = false;
958
959   /* At this point all variables on the unexpanded_var_list with TREE_USED
960      set are not associated with any block scope.  Lay them out.  */
961   for (t = cfun->unexpanded_var_list; t; t = TREE_CHAIN (t))
962     {
963       tree var = TREE_VALUE (t);
964       bool expand_now = false;
965
966       /* We didn't set a block for static or extern because it's hard
967          to tell the difference between a global variable (re)declared
968          in a local scope, and one that's really declared there to
969          begin with.  And it doesn't really matter much, since we're
970          not giving them stack space.  Expand them now.  */
971       if (TREE_STATIC (var) || DECL_EXTERNAL (var))
972         expand_now = true;
973
974       /* Any variable that could have been hoisted into an SSA_NAME
975          will have been propagated anywhere the optimizers chose,
976          i.e. not confined to their original block.  Allocate them
977          as if they were defined in the outermost scope.  */
978       else if (is_gimple_reg (var))
979         expand_now = true;
980
981       /* If the variable is not associated with any block, then it
982          was created by the optimizers, and could be live anywhere
983          in the function.  */
984       else if (TREE_USED (var))
985         expand_now = true;
986
987       /* Finally, mark all variables on the list as used.  We'll use
988          this in a moment when we expand those associated with scopes.  */
989       TREE_USED (var) = 1;
990
991       if (expand_now)
992         expand_one_var (var, true);
993     }
994   cfun->unexpanded_var_list = NULL_TREE;
995
996   /* At this point, all variables within the block tree with TREE_USED
997      set are actually used by the optimized function.  Lay them out.  */
998   expand_used_vars_for_block (outer_block, true);
999
1000   if (stack_vars_num > 0)
1001     {
1002       /* Due to the way alias sets work, no variables with non-conflicting
1003          alias sets may be assigned the same address.  Add conflicts to 
1004          reflect this.  */
1005       add_alias_set_conflicts ();
1006
1007       /* If stack protection is enabled, we don't share space between 
1008          vulnerable data and non-vulnerable data.  */
1009       if (flag_stack_protect)
1010         add_stack_protection_conflicts ();
1011
1012       /* Now that we have collected all stack variables, and have computed a 
1013          minimal interference graph, attempt to save some stack space.  */
1014       partition_stack_vars ();
1015       if (dump_file)
1016         dump_stack_var_partition ();
1017     }
1018
1019   /* There are several conditions under which we should create a
1020      stack guard: protect-all, alloca used, protected decls present.  */
1021   if (flag_stack_protect == 2
1022       || (flag_stack_protect
1023           && (current_function_calls_alloca || has_protected_decls)))
1024     create_stack_guard ();
1025
1026   /* Assign rtl to each variable based on these partitions.  */
1027   if (stack_vars_num > 0)
1028     {
1029       /* Reorder decls to be protected by iterating over the variables
1030          array multiple times, and allocating out of each phase in turn.  */
1031       /* ??? We could probably integrate this into the qsort we did 
1032          earlier, such that we naturally see these variables first,
1033          and thus naturally allocate things in the right order.  */
1034       if (has_protected_decls)
1035         {
1036           /* Phase 1 contains only character arrays.  */
1037           expand_stack_vars (stack_protect_decl_phase_1);
1038
1039           /* Phase 2 contains other kinds of arrays.  */
1040           if (flag_stack_protect == 2)
1041             expand_stack_vars (stack_protect_decl_phase_2);
1042         }
1043
1044       expand_stack_vars (NULL);
1045
1046       /* Free up stack variable graph data.  */
1047       XDELETEVEC (stack_vars);
1048       XDELETEVEC (stack_vars_sorted);
1049       XDELETEVEC (stack_vars_conflict);
1050       stack_vars = NULL;
1051       stack_vars_alloc = stack_vars_num = 0;
1052       stack_vars_conflict = NULL;
1053       stack_vars_conflict_alloc = 0;
1054     }
1055
1056   /* If the target requires that FRAME_OFFSET be aligned, do it.  */
1057   if (STACK_ALIGNMENT_NEEDED)
1058     {
1059       HOST_WIDE_INT align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
1060       if (!FRAME_GROWS_DOWNWARD)
1061         frame_offset += align - 1;
1062       frame_offset &= -align;
1063     }
1064 }
1065
1066
1067 /* If we need to produce a detailed dump, print the tree representation
1068    for STMT to the dump file.  SINCE is the last RTX after which the RTL
1069    generated for STMT should have been appended.  */
1070
1071 static void
1072 maybe_dump_rtl_for_tree_stmt (tree stmt, rtx since)
1073 {
1074   if (dump_file && (dump_flags & TDF_DETAILS))
1075     {
1076       fprintf (dump_file, "\n;; ");
1077       print_generic_expr (dump_file, stmt, TDF_SLIM);
1078       fprintf (dump_file, "\n");
1079
1080       print_rtl (dump_file, since ? NEXT_INSN (since) : since);
1081     }
1082 }
1083
1084 /* A subroutine of expand_gimple_basic_block.  Expand one COND_EXPR.
1085    Returns a new basic block if we've terminated the current basic
1086    block and created a new one.  */
1087
1088 static basic_block
1089 expand_gimple_cond_expr (basic_block bb, tree stmt)
1090 {
1091   basic_block new_bb, dest;
1092   edge new_edge;
1093   edge true_edge;
1094   edge false_edge;
1095   tree pred = COND_EXPR_COND (stmt);
1096   tree then_exp = COND_EXPR_THEN (stmt);
1097   tree else_exp = COND_EXPR_ELSE (stmt);
1098   rtx last2, last;
1099
1100   last2 = last = get_last_insn ();
1101
1102   extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1103   if (EXPR_LOCUS (stmt))
1104     {
1105       emit_line_note (*(EXPR_LOCUS (stmt)));
1106       record_block_change (TREE_BLOCK (stmt));
1107     }
1108
1109   /* These flags have no purpose in RTL land.  */
1110   true_edge->flags &= ~EDGE_TRUE_VALUE;
1111   false_edge->flags &= ~EDGE_FALSE_VALUE;
1112
1113   /* We can either have a pure conditional jump with one fallthru edge or
1114      two-way jump that needs to be decomposed into two basic blocks.  */
1115   if (TREE_CODE (then_exp) == GOTO_EXPR && IS_EMPTY_STMT (else_exp))
1116     {
1117       jumpif (pred, label_rtx (GOTO_DESTINATION (then_exp)));
1118       add_reg_br_prob_note (dump_file, last, true_edge->probability);
1119       maybe_dump_rtl_for_tree_stmt (stmt, last);
1120       if (EXPR_LOCUS (then_exp))
1121         emit_line_note (*(EXPR_LOCUS (then_exp)));
1122       return NULL;
1123     }
1124   if (TREE_CODE (else_exp) == GOTO_EXPR && IS_EMPTY_STMT (then_exp))
1125     {
1126       jumpifnot (pred, label_rtx (GOTO_DESTINATION (else_exp)));
1127       add_reg_br_prob_note (dump_file, last, false_edge->probability);
1128       maybe_dump_rtl_for_tree_stmt (stmt, last);
1129       if (EXPR_LOCUS (else_exp))
1130         emit_line_note (*(EXPR_LOCUS (else_exp)));
1131       return NULL;
1132     }
1133   gcc_assert (TREE_CODE (then_exp) == GOTO_EXPR
1134               && TREE_CODE (else_exp) == GOTO_EXPR);
1135
1136   jumpif (pred, label_rtx (GOTO_DESTINATION (then_exp)));
1137   add_reg_br_prob_note (dump_file, last, true_edge->probability);
1138   last = get_last_insn ();
1139   expand_expr (else_exp, const0_rtx, VOIDmode, 0);
1140
1141   BB_END (bb) = last;
1142   if (BARRIER_P (BB_END (bb)))
1143     BB_END (bb) = PREV_INSN (BB_END (bb));
1144   update_bb_for_insn (bb);
1145
1146   new_bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
1147   dest = false_edge->dest;
1148   redirect_edge_succ (false_edge, new_bb);
1149   false_edge->flags |= EDGE_FALLTHRU;
1150   new_bb->count = false_edge->count;
1151   new_bb->frequency = EDGE_FREQUENCY (false_edge);
1152   new_edge = make_edge (new_bb, dest, 0);
1153   new_edge->probability = REG_BR_PROB_BASE;
1154   new_edge->count = new_bb->count;
1155   if (BARRIER_P (BB_END (new_bb)))
1156     BB_END (new_bb) = PREV_INSN (BB_END (new_bb));
1157   update_bb_for_insn (new_bb);
1158
1159   maybe_dump_rtl_for_tree_stmt (stmt, last2);
1160   
1161   if (EXPR_LOCUS (else_exp))
1162     emit_line_note (*(EXPR_LOCUS (else_exp)));
1163
1164   return new_bb;
1165 }
1166
1167 /* A subroutine of expand_gimple_basic_block.  Expand one CALL_EXPR
1168    that has CALL_EXPR_TAILCALL set.  Returns non-null if we actually
1169    generated a tail call (something that might be denied by the ABI
1170    rules governing the call; see calls.c).
1171
1172    Sets CAN_FALLTHRU if we generated a *conditional* tail call, and
1173    can still reach the rest of BB.  The case here is __builtin_sqrt,
1174    where the NaN result goes through the external function (with a
1175    tailcall) and the normal result happens via a sqrt instruction.  */
1176
1177 static basic_block
1178 expand_gimple_tailcall (basic_block bb, tree stmt, bool *can_fallthru)
1179 {
1180   rtx last2, last;
1181   edge e;
1182   edge_iterator ei;
1183   int probability;
1184   gcov_type count;
1185
1186   last2 = last = get_last_insn ();
1187
1188   expand_expr_stmt (stmt);
1189
1190   for (last = NEXT_INSN (last); last; last = NEXT_INSN (last))
1191     if (CALL_P (last) && SIBLING_CALL_P (last))
1192       goto found;
1193
1194   maybe_dump_rtl_for_tree_stmt (stmt, last2);
1195
1196   *can_fallthru = true;
1197   return NULL;
1198
1199  found:
1200   /* ??? Wouldn't it be better to just reset any pending stack adjust?
1201      Any instructions emitted here are about to be deleted.  */
1202   do_pending_stack_adjust ();
1203
1204   /* Remove any non-eh, non-abnormal edges that don't go to exit.  */
1205   /* ??? I.e. the fallthrough edge.  HOWEVER!  If there were to be
1206      EH or abnormal edges, we shouldn't have created a tail call in
1207      the first place.  So it seems to me we should just be removing
1208      all edges here, or redirecting the existing fallthru edge to
1209      the exit block.  */
1210
1211   probability = 0;
1212   count = 0;
1213
1214   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
1215     {
1216       if (!(e->flags & (EDGE_ABNORMAL | EDGE_EH)))
1217         {
1218           if (e->dest != EXIT_BLOCK_PTR)
1219             {
1220               e->dest->count -= e->count;
1221               e->dest->frequency -= EDGE_FREQUENCY (e);
1222               if (e->dest->count < 0)
1223                 e->dest->count = 0;
1224               if (e->dest->frequency < 0)
1225                 e->dest->frequency = 0;
1226             }
1227           count += e->count;
1228           probability += e->probability;
1229           remove_edge (e);
1230         }
1231       else
1232         ei_next (&ei);
1233     }
1234
1235   /* This is somewhat ugly: the call_expr expander often emits instructions
1236      after the sibcall (to perform the function return).  These confuse the
1237      find_many_sub_basic_blocks code, so we need to get rid of these.  */
1238   last = NEXT_INSN (last);
1239   gcc_assert (BARRIER_P (last));
1240
1241   *can_fallthru = false;
1242   while (NEXT_INSN (last))
1243     {
1244       /* For instance an sqrt builtin expander expands if with
1245          sibcall in the then and label for `else`.  */
1246       if (LABEL_P (NEXT_INSN (last)))
1247         {
1248           *can_fallthru = true;
1249           break;
1250         }
1251       delete_insn (NEXT_INSN (last));
1252     }
1253
1254   e = make_edge (bb, EXIT_BLOCK_PTR, EDGE_ABNORMAL | EDGE_SIBCALL);
1255   e->probability += probability;
1256   e->count += count;
1257   BB_END (bb) = last;
1258   update_bb_for_insn (bb);
1259
1260   if (NEXT_INSN (last))
1261     {
1262       bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
1263
1264       last = BB_END (bb);
1265       if (BARRIER_P (last))
1266         BB_END (bb) = PREV_INSN (last);
1267     }
1268
1269   maybe_dump_rtl_for_tree_stmt (stmt, last2);
1270
1271   return bb;
1272 }
1273
1274 /* Expand basic block BB from GIMPLE trees to RTL.  */
1275
1276 static basic_block
1277 expand_gimple_basic_block (basic_block bb, FILE * dump_file)
1278 {
1279   block_stmt_iterator bsi = bsi_start (bb);
1280   tree stmt = NULL;
1281   rtx note, last;
1282   edge e;
1283   edge_iterator ei;
1284
1285   if (dump_file)
1286     {
1287       fprintf (dump_file,
1288                "\n;; Generating RTL for tree basic block %d\n",
1289                bb->index);
1290     }
1291
1292   init_rtl_bb_info (bb);
1293   bb->flags |= BB_RTL;
1294
1295   if (!bsi_end_p (bsi))
1296     stmt = bsi_stmt (bsi);
1297
1298   if (stmt && TREE_CODE (stmt) == LABEL_EXPR)
1299     {
1300       last = get_last_insn ();
1301
1302       expand_expr_stmt (stmt);
1303
1304       /* Java emits line number notes in the top of labels.
1305          ??? Make this go away once line number notes are obsoleted.  */
1306       BB_HEAD (bb) = NEXT_INSN (last);
1307       if (NOTE_P (BB_HEAD (bb)))
1308         BB_HEAD (bb) = NEXT_INSN (BB_HEAD (bb));
1309       bsi_next (&bsi);
1310       note = emit_note_after (NOTE_INSN_BASIC_BLOCK, BB_HEAD (bb));
1311
1312       maybe_dump_rtl_for_tree_stmt (stmt, last);
1313     }
1314   else
1315     note = BB_HEAD (bb) = emit_note (NOTE_INSN_BASIC_BLOCK);
1316
1317   NOTE_BASIC_BLOCK (note) = bb;
1318
1319   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
1320     {
1321       /* Clear EDGE_EXECUTABLE.  This flag is never used in the backend.  */
1322       e->flags &= ~EDGE_EXECUTABLE;
1323
1324       /* At the moment not all abnormal edges match the RTL representation.
1325          It is safe to remove them here as find_many_sub_basic_blocks will
1326          rediscover them.  In the future we should get this fixed properly.  */
1327       if (e->flags & EDGE_ABNORMAL)
1328         remove_edge (e);
1329       else
1330         ei_next (&ei);
1331     }
1332
1333   for (; !bsi_end_p (bsi); bsi_next (&bsi))
1334     {
1335       tree stmt = bsi_stmt (bsi);
1336       basic_block new_bb;
1337
1338       if (!stmt)
1339         continue;
1340
1341       /* Expand this statement, then evaluate the resulting RTL and
1342          fixup the CFG accordingly.  */
1343       if (TREE_CODE (stmt) == COND_EXPR)
1344         {
1345           new_bb = expand_gimple_cond_expr (bb, stmt);
1346           if (new_bb)
1347             return new_bb;
1348         }
1349       else
1350         {
1351           tree call = get_call_expr_in (stmt);
1352           if (call && CALL_EXPR_TAILCALL (call))
1353             {
1354               bool can_fallthru;
1355               new_bb = expand_gimple_tailcall (bb, stmt, &can_fallthru);
1356               if (new_bb)
1357                 {
1358                   if (can_fallthru)
1359                     bb = new_bb;
1360                   else
1361                     return new_bb;
1362                 }
1363             }
1364           else
1365             {
1366               last = get_last_insn ();
1367               expand_expr_stmt (stmt);
1368               maybe_dump_rtl_for_tree_stmt (stmt, last);
1369             }
1370         }
1371     }
1372
1373   do_pending_stack_adjust ();
1374
1375   /* Find the block tail.  The last insn in the block is the insn
1376      before a barrier and/or table jump insn.  */
1377   last = get_last_insn ();
1378   if (BARRIER_P (last))
1379     last = PREV_INSN (last);
1380   if (JUMP_TABLE_DATA_P (last))
1381     last = PREV_INSN (PREV_INSN (last));
1382   BB_END (bb) = last;
1383
1384   update_bb_for_insn (bb);
1385
1386   return bb;
1387 }
1388
1389
1390 /* Create a basic block for initialization code.  */
1391
1392 static basic_block
1393 construct_init_block (void)
1394 {
1395   basic_block init_block, first_block;
1396   edge e = NULL;
1397   int flags;
1398
1399   /* Multiple entry points not supported yet.  */
1400   gcc_assert (EDGE_COUNT (ENTRY_BLOCK_PTR->succs) == 1);
1401   init_rtl_bb_info (ENTRY_BLOCK_PTR);
1402   init_rtl_bb_info (EXIT_BLOCK_PTR);
1403   ENTRY_BLOCK_PTR->flags |= BB_RTL;
1404   EXIT_BLOCK_PTR->flags |= BB_RTL;
1405
1406   e = EDGE_SUCC (ENTRY_BLOCK_PTR, 0);
1407
1408   /* When entry edge points to first basic block, we don't need jump,
1409      otherwise we have to jump into proper target.  */
1410   if (e && e->dest != ENTRY_BLOCK_PTR->next_bb)
1411     {
1412       tree label = tree_block_label (e->dest);
1413
1414       emit_jump (label_rtx (label));
1415       flags = 0;
1416     }
1417   else
1418     flags = EDGE_FALLTHRU;
1419
1420   init_block = create_basic_block (NEXT_INSN (get_insns ()),
1421                                    get_last_insn (),
1422                                    ENTRY_BLOCK_PTR);
1423   init_block->frequency = ENTRY_BLOCK_PTR->frequency;
1424   init_block->count = ENTRY_BLOCK_PTR->count;
1425   if (e)
1426     {
1427       first_block = e->dest;
1428       redirect_edge_succ (e, init_block);
1429       e = make_edge (init_block, first_block, flags);
1430     }
1431   else
1432     e = make_edge (init_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
1433   e->probability = REG_BR_PROB_BASE;
1434   e->count = ENTRY_BLOCK_PTR->count;
1435
1436   update_bb_for_insn (init_block);
1437   return init_block;
1438 }
1439
1440
1441 /* Create a block containing landing pads and similar stuff.  */
1442
1443 static void
1444 construct_exit_block (void)
1445 {
1446   rtx head = get_last_insn ();
1447   rtx end;
1448   basic_block exit_block;
1449   edge e, e2;
1450   unsigned ix;
1451   edge_iterator ei;
1452
1453   /* Make sure the locus is set to the end of the function, so that
1454      epilogue line numbers and warnings are set properly.  */
1455 #ifdef USE_MAPPED_LOCATION
1456   if (cfun->function_end_locus != UNKNOWN_LOCATION)
1457 #else
1458   if (cfun->function_end_locus.file)
1459 #endif
1460     input_location = cfun->function_end_locus;
1461
1462   /* The following insns belong to the top scope.  */
1463   record_block_change (DECL_INITIAL (current_function_decl));
1464
1465   /* Generate rtl for function exit.  */
1466   expand_function_end ();
1467
1468   end = get_last_insn ();
1469   if (head == end)
1470     return;
1471   while (NEXT_INSN (head) && NOTE_P (NEXT_INSN (head)))
1472     head = NEXT_INSN (head);
1473   exit_block = create_basic_block (NEXT_INSN (head), end,
1474                                    EXIT_BLOCK_PTR->prev_bb);
1475   exit_block->frequency = EXIT_BLOCK_PTR->frequency;
1476   exit_block->count = EXIT_BLOCK_PTR->count;
1477
1478   ix = 0;
1479   while (ix < EDGE_COUNT (EXIT_BLOCK_PTR->preds))
1480     {
1481       e = EDGE_PRED (EXIT_BLOCK_PTR, ix);
1482       if (!(e->flags & EDGE_ABNORMAL))
1483         redirect_edge_succ (e, exit_block);
1484       else
1485         ix++;
1486     }
1487
1488   e = make_edge (exit_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
1489   e->probability = REG_BR_PROB_BASE;
1490   e->count = EXIT_BLOCK_PTR->count;
1491   FOR_EACH_EDGE (e2, ei, EXIT_BLOCK_PTR->preds)
1492     if (e2 != e)
1493       {
1494         e->count -= e2->count;
1495         exit_block->count -= e2->count;
1496         exit_block->frequency -= EDGE_FREQUENCY (e2);
1497       }
1498   if (e->count < 0)
1499     e->count = 0;
1500   if (exit_block->count < 0)
1501     exit_block->count = 0;
1502   if (exit_block->frequency < 0)
1503     exit_block->frequency = 0;
1504   update_bb_for_insn (exit_block);
1505 }
1506
1507 /* Helper function for discover_nonconstant_array_refs. 
1508    Look for ARRAY_REF nodes with non-constant indexes and mark them
1509    addressable.  */
1510
1511 static tree
1512 discover_nonconstant_array_refs_r (tree * tp, int *walk_subtrees,
1513                                    void *data ATTRIBUTE_UNUSED)
1514 {
1515   tree t = *tp;
1516
1517   if (IS_TYPE_OR_DECL_P (t))
1518     *walk_subtrees = 0;
1519   else if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1520     {
1521       while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1522               && is_gimple_min_invariant (TREE_OPERAND (t, 1))
1523               && (!TREE_OPERAND (t, 2)
1524                   || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1525              || (TREE_CODE (t) == COMPONENT_REF
1526                  && (!TREE_OPERAND (t,2)
1527                      || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1528              || TREE_CODE (t) == BIT_FIELD_REF
1529              || TREE_CODE (t) == REALPART_EXPR
1530              || TREE_CODE (t) == IMAGPART_EXPR
1531              || TREE_CODE (t) == VIEW_CONVERT_EXPR
1532              || TREE_CODE (t) == NOP_EXPR
1533              || TREE_CODE (t) == CONVERT_EXPR)
1534         t = TREE_OPERAND (t, 0);
1535
1536       if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1537         {
1538           t = get_base_address (t);
1539           if (t && DECL_P (t))
1540             TREE_ADDRESSABLE (t) = 1;
1541         }
1542
1543       *walk_subtrees = 0;
1544     }
1545
1546   return NULL_TREE;
1547 }
1548
1549 /* RTL expansion is not able to compile array references with variable
1550    offsets for arrays stored in single register.  Discover such
1551    expressions and mark variables as addressable to avoid this
1552    scenario.  */
1553
1554 static void
1555 discover_nonconstant_array_refs (void)
1556 {
1557   basic_block bb;
1558   block_stmt_iterator bsi;
1559
1560   FOR_EACH_BB (bb)
1561     {
1562       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1563         walk_tree (bsi_stmt_ptr (bsi), discover_nonconstant_array_refs_r,
1564                    NULL , NULL);
1565     }
1566 }
1567
1568 /* Translate the intermediate representation contained in the CFG
1569    from GIMPLE trees to RTL.
1570
1571    We do conversion per basic block and preserve/update the tree CFG.
1572    This implies we have to do some magic as the CFG can simultaneously
1573    consist of basic blocks containing RTL and GIMPLE trees.  This can
1574    confuse the CFG hooks, so be careful to not manipulate CFG during
1575    the expansion.  */
1576
1577 static void
1578 tree_expand_cfg (void)
1579 {
1580   basic_block bb, init_block;
1581   sbitmap blocks;
1582
1583   /* Some backends want to know that we are expanding to RTL.  */
1584   currently_expanding_to_rtl = 1;
1585
1586   /* Prepare the rtl middle end to start recording block changes.  */
1587   reset_block_changes ();
1588
1589   /* Mark arrays indexed with non-constant indices with TREE_ADDRESSABLE.  */
1590   discover_nonconstant_array_refs ();
1591
1592   /* Expand the variables recorded during gimple lowering.  */
1593   expand_used_vars ();
1594
1595   /* Honor stack protection warnings.  */
1596   if (warn_stack_protect)
1597     {
1598       if (current_function_calls_alloca)
1599         warning (0, "not protecting local variables: variable length buffer");
1600       if (has_short_buffer && !cfun->stack_protect_guard)
1601         warning (0, "not protecting function: no buffer at least %d bytes long",
1602                  (int) PARAM_VALUE (PARAM_SSP_BUFFER_SIZE));
1603     }
1604
1605   /* Set up parameters and prepare for return, for the function.  */
1606   expand_function_start (current_function_decl);
1607
1608   /* If this function is `main', emit a call to `__main'
1609      to run global initializers, etc.  */
1610   if (DECL_NAME (current_function_decl)
1611       && MAIN_NAME_P (DECL_NAME (current_function_decl))
1612       && DECL_FILE_SCOPE_P (current_function_decl))
1613     expand_main_function ();
1614
1615   /* Initialize the stack_protect_guard field.  This must happen after the
1616      call to __main (if any) so that the external decl is initialized.  */
1617   if (cfun->stack_protect_guard)
1618     stack_protect_prologue ();
1619
1620   /* Register rtl specific functions for cfg.  */
1621   rtl_register_cfg_hooks ();
1622
1623   init_block = construct_init_block ();
1624
1625   FOR_BB_BETWEEN (bb, init_block->next_bb, EXIT_BLOCK_PTR, next_bb)
1626     bb = expand_gimple_basic_block (bb, dump_file);
1627
1628   construct_exit_block ();
1629
1630   /* We're done expanding trees to RTL.  */
1631   currently_expanding_to_rtl = 0;
1632
1633   /* Convert tree EH labels to RTL EH labels, and clean out any unreachable
1634      EH regions.  */
1635   convert_from_eh_region_ranges ();
1636
1637   rebuild_jump_labels (get_insns ());
1638   find_exception_handler_labels ();
1639
1640   blocks = sbitmap_alloc (last_basic_block);
1641   sbitmap_ones (blocks);
1642   find_many_sub_basic_blocks (blocks);
1643   purge_all_dead_edges ();
1644   sbitmap_free (blocks);
1645
1646   compact_blocks ();
1647 #ifdef ENABLE_CHECKING
1648   verify_flow_info();
1649 #endif
1650
1651   /* There's no need to defer outputting this function any more; we
1652      know we want to output it.  */
1653   DECL_DEFER_OUTPUT (current_function_decl) = 0;
1654
1655   /* Now that we're done expanding trees to RTL, we shouldn't have any
1656      more CONCATs anywhere.  */
1657   generating_concat_p = 0;
1658
1659   finalize_block_changes ();
1660
1661   if (dump_file)
1662     {
1663       fprintf (dump_file,
1664                "\n\n;;\n;; Full RTL generated for this function:\n;;\n");
1665       /* And the pass manager will dump RTL for us.  */
1666     }
1667
1668   /* If we're emitting a nested function, make sure its parent gets
1669      emitted as well.  Doing otherwise confuses debug info.  */
1670   {   
1671     tree parent;
1672     for (parent = DECL_CONTEXT (current_function_decl);
1673          parent != NULL_TREE;
1674          parent = get_containing_scope (parent))
1675       if (TREE_CODE (parent) == FUNCTION_DECL)
1676         TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (parent)) = 1;
1677   }
1678     
1679   /* We are now committed to emitting code for this function.  Do any
1680      preparation, such as emitting abstract debug info for the inline
1681      before it gets mangled by optimization.  */
1682   if (cgraph_function_possibly_inlined_p (current_function_decl))
1683     (*debug_hooks->outlining_inline_function) (current_function_decl);
1684
1685   TREE_ASM_WRITTEN (current_function_decl) = 1;
1686
1687   /* After expanding, the return labels are no longer needed. */
1688   return_label = NULL;
1689   naked_return_label = NULL;
1690 }
1691
1692 struct tree_opt_pass pass_expand =
1693 {
1694   "expand",                             /* name */
1695   NULL,                                 /* gate */
1696   tree_expand_cfg,                      /* execute */
1697   NULL,                                 /* sub */
1698   NULL,                                 /* next */
1699   0,                                    /* static_pass_number */
1700   TV_EXPAND,                            /* tv_id */
1701   /* ??? If TER is enabled, we actually receive GENERIC.  */
1702   PROP_gimple_leh | PROP_cfg,           /* properties_required */
1703   PROP_rtl,                             /* properties_provided */
1704   PROP_gimple_leh,                      /* properties_destroyed */
1705   0,                                    /* todo_flags_start */
1706   TODO_dump_func,                       /* todo_flags_finish */
1707   'r'                                   /* letter */
1708 };