OSDN Git Service

2005-08-03 Andrew Pinski <pinskia@physics.uc.edu>
[pf3gnuchains/gcc-fork.git] / gcc / tree-outof-ssa.c
1 /* Convert a program in SSA form into Normal form.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Andrew Macleod <amacleod@redhat.com>
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 2, 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 COPYING.  If not, write to
19 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "ggc.h"
31 #include "langhooks.h"
32 #include "hard-reg-set.h"
33 #include "basic-block.h"
34 #include "output.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "bitmap.h"
39 #include "tree-flow.h"
40 #include "tree-gimple.h"
41 #include "tree-inline.h"
42 #include "varray.h"
43 #include "timevar.h"
44 #include "hashtab.h"
45 #include "tree-dump.h"
46 #include "tree-ssa-live.h"
47 #include "tree-pass.h"
48 #include "toplev.h"
49
50 /* Flags to pass to remove_ssa_form.  */
51
52 #define SSANORM_PERFORM_TER             0x1
53 #define SSANORM_COMBINE_TEMPS           0x2
54 #define SSANORM_COALESCE_PARTITIONS     0x4
55
56 DEF_VEC_I(int);
57 DEF_VEC_ALLOC_I(int,heap);
58
59 /* Used to hold all the components required to do SSA PHI elimination.
60    The node and pred/succ list is a simple linear list of nodes and
61    edges represented as pairs of nodes.
62
63    The predecessor and successor list:  Nodes are entered in pairs, where
64    [0] ->PRED, [1]->SUCC.  All the even indexes in the array represent 
65    predecessors, all the odd elements are successors. 
66    
67    Rationale:
68    When implemented as bitmaps, very large programs SSA->Normal times were 
69    being dominated by clearing the interference graph.
70
71    Typically this list of edges is extremely small since it only includes 
72    PHI results and uses from a single edge which have not coalesced with 
73    each other.  This means that no virtual PHI nodes are included, and
74    empirical evidence suggests that the number of edges rarely exceed
75    3, and in a bootstrap of GCC, the maximum size encountered was 7.
76    This also limits the number of possible nodes that are involved to
77    rarely more than 6, and in the bootstrap of gcc, the maximum number
78    of nodes encountered was 12.  */
79  
80 typedef struct _elim_graph {
81   /* Size of the elimination vectors.  */
82   int size;
83
84   /* List of nodes in the elimination graph.  */
85   VEC(tree,heap) *nodes;
86
87   /*  The predecessor and successor edge list.  */
88   VEC(int,heap) *edge_list;
89
90   /* Visited vector.  */
91   sbitmap visited;
92
93   /* Stack for visited nodes.  */
94   varray_type stack;
95   
96   /* The variable partition map.  */
97   var_map map;
98
99   /* Edge being eliminated by this graph.  */
100   edge e;
101
102   /* List of constant copies to emit.  These are pushed on in pairs.  */
103   VEC(tree,heap) *const_copies;
104 } *elim_graph;
105
106
107 /* Local functions.  */
108 static tree create_temp (tree);
109 static void insert_copy_on_edge (edge, tree, tree);
110 static elim_graph new_elim_graph (int);
111 static inline void delete_elim_graph (elim_graph);
112 static inline void clear_elim_graph (elim_graph);
113 static inline int elim_graph_size (elim_graph);
114 static inline void elim_graph_add_node (elim_graph, tree);
115 static inline void elim_graph_add_edge (elim_graph, int, int);
116 static inline int elim_graph_remove_succ_edge (elim_graph, int);
117
118 static inline void eliminate_name (elim_graph, tree);
119 static void eliminate_build (elim_graph, basic_block);
120 static void elim_forward (elim_graph, int);
121 static int elim_unvisited_predecessor (elim_graph, int);
122 static void elim_backward (elim_graph, int);
123 static void elim_create (elim_graph, int);
124 static void eliminate_phi (edge, elim_graph);
125 static tree_live_info_p coalesce_ssa_name (var_map, int);
126 static void assign_vars (var_map);
127 static bool replace_use_variable (var_map, use_operand_p, tree *);
128 static bool replace_def_variable (var_map, def_operand_p, tree *);
129 static void eliminate_virtual_phis (void);
130 static void coalesce_abnormal_edges (var_map, conflict_graph, root_var_p);
131 static void print_exprs (FILE *, const char *, tree, const char *, tree,
132                          const char *);
133 static void print_exprs_edge (FILE *, edge, const char *, tree, const char *,
134                               tree);
135
136
137 /* Create a temporary variable based on the type of variable T.  Use T's name
138    as the prefix.  */
139
140 static tree
141 create_temp (tree t)
142 {
143   tree tmp;
144   const char *name = NULL;
145   tree type;
146
147   if (TREE_CODE (t) == SSA_NAME)
148     t = SSA_NAME_VAR (t);
149
150   gcc_assert (TREE_CODE (t) == VAR_DECL || TREE_CODE (t) == PARM_DECL);
151
152   type = TREE_TYPE (t);
153   tmp = DECL_NAME (t);
154   if (tmp)
155     name = IDENTIFIER_POINTER (tmp);
156
157   if (name == NULL)
158     name = "temp";
159   tmp = create_tmp_var (type, name);
160
161   if (DECL_DEBUG_EXPR_IS_FROM (t) && DECL_DEBUG_EXPR (t))
162     {
163       SET_DECL_DEBUG_EXPR (tmp, DECL_DEBUG_EXPR (t));  
164       DECL_DEBUG_EXPR_IS_FROM (tmp) = 1;
165     }
166   else if (!DECL_IGNORED_P (t))
167     {
168       SET_DECL_DEBUG_EXPR (tmp, t);
169       DECL_DEBUG_EXPR_IS_FROM (tmp) = 1;
170     }
171   DECL_ARTIFICIAL (tmp) = DECL_ARTIFICIAL (t);
172   DECL_IGNORED_P (tmp) = DECL_IGNORED_P (t);
173   add_referenced_tmp_var (tmp);
174
175   /* add_referenced_tmp_var will create the annotation and set up some
176      of the flags in the annotation.  However, some flags we need to
177      inherit from our original variable.  */
178   var_ann (tmp)->type_mem_tag = var_ann (t)->type_mem_tag;
179   if (is_call_clobbered (t))
180     mark_call_clobbered (tmp);
181
182   return tmp;
183 }
184
185
186 /* This helper function fill insert a copy from a constant or variable SRC to 
187    variable DEST on edge E.  */
188
189 static void
190 insert_copy_on_edge (edge e, tree dest, tree src)
191 {
192   tree copy;
193
194   copy = build (MODIFY_EXPR, TREE_TYPE (dest), dest, src);
195   set_is_used (dest);
196
197   if (TREE_CODE (src) == ADDR_EXPR)
198     src = TREE_OPERAND (src, 0);
199   if (TREE_CODE (src) == VAR_DECL || TREE_CODE (src) == PARM_DECL)
200     set_is_used (src);
201
202   if (dump_file && (dump_flags & TDF_DETAILS))
203     {
204       fprintf (dump_file,
205                "Inserting a copy on edge BB%d->BB%d :",
206                e->src->index,
207                e->dest->index);
208       print_generic_expr (dump_file, copy, dump_flags);
209       fprintf (dump_file, "\n");
210     }
211
212   bsi_insert_on_edge (e, copy);
213 }
214
215
216 /* Create an elimination graph with SIZE nodes and associated data
217    structures.  */
218
219 static elim_graph
220 new_elim_graph (int size)
221 {
222   elim_graph g = (elim_graph) xmalloc (sizeof (struct _elim_graph));
223
224   g->nodes = VEC_alloc (tree, heap, 30);
225   g->const_copies = VEC_alloc (tree, heap, 20);
226   g->edge_list = VEC_alloc (int, heap, 20);
227   VARRAY_INT_INIT (g->stack, 30, " Elimination Stack");
228   
229   g->visited = sbitmap_alloc (size);
230
231   return g;
232 }
233
234
235 /* Empty elimination graph G.  */
236
237 static inline void
238 clear_elim_graph (elim_graph g)
239 {
240   VEC_truncate (tree, g->nodes, 0);
241   VEC_truncate (int, g->edge_list, 0);
242 }
243
244
245 /* Delete elimination graph G.  */
246
247 static inline void
248 delete_elim_graph (elim_graph g)
249 {
250   sbitmap_free (g->visited);
251   VEC_free (int, heap, g->edge_list);
252   VEC_free (tree, heap, g->const_copies);
253   VEC_free (tree, heap, g->nodes);
254   free (g);
255 }
256
257
258 /* Return the number of nodes in graph G.  */
259
260 static inline int
261 elim_graph_size (elim_graph g)
262 {
263   return VEC_length (tree, g->nodes);
264 }
265
266
267 /* Add NODE to graph G, if it doesn't exist already.  */
268
269 static inline void 
270 elim_graph_add_node (elim_graph g, tree node)
271 {
272   int x;
273   tree t;
274
275   for (x = 0; VEC_iterate (tree, g->nodes, x, t); x++)
276     if (t == node)
277       return;
278   VEC_safe_push (tree, heap, g->nodes, node);
279 }
280
281
282 /* Add the edge PRED->SUCC to graph G.  */
283
284 static inline void
285 elim_graph_add_edge (elim_graph g, int pred, int succ)
286 {
287   VEC_safe_push (int, heap, g->edge_list, pred);
288   VEC_safe_push (int, heap, g->edge_list, succ);
289 }
290
291
292 /* Remove an edge from graph G for which NODE is the predecessor, and
293    return the successor node.  -1 is returned if there is no such edge.  */
294
295 static inline int
296 elim_graph_remove_succ_edge (elim_graph g, int node)
297 {
298   int y;
299   unsigned x;
300   for (x = 0; x < VEC_length (int, g->edge_list); x += 2)
301     if (VEC_index (int, g->edge_list, x) == node)
302       {
303         VEC_replace (int, g->edge_list, x, -1);
304         y = VEC_index (int, g->edge_list, x + 1);
305         VEC_replace (int, g->edge_list, x + 1, -1);
306         return y;
307       }
308   return -1;
309 }
310
311
312 /* Find all the nodes in GRAPH which are successors to NODE in the
313    edge list.  VAR will hold the partition number found.  CODE is the
314    code fragment executed for every node found.  */
315
316 #define FOR_EACH_ELIM_GRAPH_SUCC(GRAPH, NODE, VAR, CODE)                \
317 do {                                                                    \
318   unsigned x_;                                                          \
319   int y_;                                                               \
320   for (x_ = 0; x_ < VEC_length (int, (GRAPH)->edge_list); x_ += 2)      \
321     {                                                                   \
322       y_ = VEC_index (int, (GRAPH)->edge_list, x_);                     \
323       if (y_ != (NODE))                                                 \
324         continue;                                                       \
325       (VAR) = VEC_index (int, (GRAPH)->edge_list, x_ + 1);              \
326       CODE;                                                             \
327     }                                                                   \
328 } while (0)
329
330
331 /* Find all the nodes which are predecessors of NODE in the edge list for
332    GRAPH.  VAR will hold the partition number found.  CODE is the
333    code fragment executed for every node found.  */
334
335 #define FOR_EACH_ELIM_GRAPH_PRED(GRAPH, NODE, VAR, CODE)                \
336 do {                                                                    \
337   unsigned x_;                                                          \
338   int y_;                                                               \
339   for (x_ = 0; x_ < VEC_length (int, (GRAPH)->edge_list); x_ += 2)      \
340     {                                                                   \
341       y_ = VEC_index (int, (GRAPH)->edge_list, x_ + 1);                 \
342       if (y_ != (NODE))                                                 \
343         continue;                                                       \
344       (VAR) = VEC_index (int, (GRAPH)->edge_list, x_);                  \
345       CODE;                                                             \
346     }                                                                   \
347 } while (0)
348
349
350 /* Add T to elimination graph G.  */
351
352 static inline void
353 eliminate_name (elim_graph g, tree T)
354 {
355   elim_graph_add_node (g, T);
356 }
357
358
359 /* Build elimination graph G for basic block BB on incoming PHI edge
360    G->e.  */
361
362 static void
363 eliminate_build (elim_graph g, basic_block B)
364 {
365   tree phi;
366   tree T0, Ti;
367   int p0, pi;
368
369   clear_elim_graph (g);
370   
371   for (phi = phi_nodes (B); phi; phi = PHI_CHAIN (phi))
372     {
373       T0 = var_to_partition_to_var (g->map, PHI_RESULT (phi));
374       
375       /* Ignore results which are not in partitions.  */
376       if (T0 == NULL_TREE)
377         continue;
378
379       Ti = PHI_ARG_DEF (phi, g->e->dest_idx);
380
381       /* If this argument is a constant, or a SSA_NAME which is being
382          left in SSA form, just queue a copy to be emitted on this
383          edge.  */
384       if (!phi_ssa_name_p (Ti)
385           || (TREE_CODE (Ti) == SSA_NAME
386               && var_to_partition (g->map, Ti) == NO_PARTITION))
387         {
388           /* Save constant copies until all other copies have been emitted
389              on this edge.  */
390           VEC_safe_push (tree, heap, g->const_copies, T0);
391           VEC_safe_push (tree, heap, g->const_copies, Ti);
392         }
393       else
394         {
395           Ti = var_to_partition_to_var (g->map, Ti);
396           if (T0 != Ti)
397             {
398               eliminate_name (g, T0);
399               eliminate_name (g, Ti);
400               p0 = var_to_partition (g->map, T0);
401               pi = var_to_partition (g->map, Ti);
402               elim_graph_add_edge (g, p0, pi);
403             }
404         }
405     }
406 }
407
408
409 /* Push successors of T onto the elimination stack for G.  */
410
411 static void 
412 elim_forward (elim_graph g, int T)
413 {
414   int S;
415   SET_BIT (g->visited, T);
416   FOR_EACH_ELIM_GRAPH_SUCC (g, T, S,
417     {
418       if (!TEST_BIT (g->visited, S))
419         elim_forward (g, S);
420     });
421   VARRAY_PUSH_INT (g->stack, T);
422 }
423
424
425 /* Return 1 if there unvisited predecessors of T in graph G.  */
426
427 static int
428 elim_unvisited_predecessor (elim_graph g, int T)
429 {
430   int P;
431   FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
432     {
433       if (!TEST_BIT (g->visited, P))
434         return 1;
435     });
436   return 0;
437 }
438
439 /* Process predecessors first, and insert a copy.  */
440
441 static void
442 elim_backward (elim_graph g, int T)
443 {
444   int P;
445   SET_BIT (g->visited, T);
446   FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
447     {
448       if (!TEST_BIT (g->visited, P))
449         {
450           elim_backward (g, P);
451           insert_copy_on_edge (g->e, 
452                                partition_to_var (g->map, P), 
453                                partition_to_var (g->map, T));
454         }
455     });
456 }
457
458 /* Insert required copies for T in graph G.  Check for a strongly connected 
459    region, and create a temporary to break the cycle if one is found.  */
460
461 static void 
462 elim_create (elim_graph g, int T)
463 {
464   tree U;
465   int P, S;
466
467   if (elim_unvisited_predecessor (g, T))
468     {
469       U = create_temp (partition_to_var (g->map, T));
470       insert_copy_on_edge (g->e, U, partition_to_var (g->map, T));
471       FOR_EACH_ELIM_GRAPH_PRED (g, T, P, 
472         {
473           if (!TEST_BIT (g->visited, P))
474             {
475               elim_backward (g, P);
476               insert_copy_on_edge (g->e, partition_to_var (g->map, P), U);
477             }
478         });
479     }
480   else
481     {
482       S = elim_graph_remove_succ_edge (g, T);
483       if (S != -1)
484         {
485           SET_BIT (g->visited, T);
486           insert_copy_on_edge (g->e, 
487                                partition_to_var (g->map, T), 
488                                partition_to_var (g->map, S));
489         }
490     }
491   
492 }
493
494 /* Eliminate all the phi nodes on edge E in graph G.  */
495
496 static void
497 eliminate_phi (edge e, elim_graph g)
498 {
499   int x;
500   basic_block B = e->dest;
501
502   gcc_assert (VEC_length (tree, g->const_copies) == 0);
503
504   /* Abnormal edges already have everything coalesced.  */
505   if (e->flags & EDGE_ABNORMAL)
506     return;
507
508   g->e = e;
509
510   eliminate_build (g, B);
511
512   if (elim_graph_size (g) != 0)
513     {
514       tree var;
515
516       sbitmap_zero (g->visited);
517       VARRAY_POP_ALL (g->stack);
518
519       for (x = 0; VEC_iterate (tree, g->nodes, x, var); x++)
520         {
521           int p = var_to_partition (g->map, var);
522           if (!TEST_BIT (g->visited, p))
523             elim_forward (g, p);
524         }
525        
526       sbitmap_zero (g->visited);
527       while (VARRAY_ACTIVE_SIZE (g->stack) > 0)
528         {
529           x = VARRAY_TOP_INT (g->stack);
530           VARRAY_POP (g->stack);
531           if (!TEST_BIT (g->visited, x))
532             elim_create (g, x);
533         }
534     }
535
536   /* If there are any pending constant copies, issue them now.  */
537   while (VEC_length (tree, g->const_copies) > 0)
538     {
539       tree src, dest;
540       src = VEC_pop (tree, g->const_copies);
541       dest = VEC_pop (tree, g->const_copies);
542       insert_copy_on_edge (e, dest, src);
543     }
544 }
545
546
547 /* Shortcut routine to print messages to file F of the form:
548    "STR1 EXPR1 STR2 EXPR2 STR3."  */
549
550 static void
551 print_exprs (FILE *f, const char *str1, tree expr1, const char *str2,
552              tree expr2, const char *str3)
553 {
554   fprintf (f, "%s", str1);
555   print_generic_expr (f, expr1, TDF_SLIM);
556   fprintf (f, "%s", str2);
557   print_generic_expr (f, expr2, TDF_SLIM);
558   fprintf (f, "%s", str3);
559 }
560
561
562 /* Shortcut routine to print abnormal edge messages to file F of the form:
563    "STR1 EXPR1 STR2 EXPR2 across edge E.  */
564
565 static void
566 print_exprs_edge (FILE *f, edge e, const char *str1, tree expr1, 
567                   const char *str2, tree expr2)
568 {
569   print_exprs (f, str1, expr1, str2, expr2, " across an abnormal edge");
570   fprintf (f, " from BB%d->BB%d\n", e->src->index,
571                e->dest->index);
572 }
573
574
575 /* Coalesce partitions in MAP which are live across abnormal edges in GRAPH.
576    RV is the root variable groupings of the partitions in MAP.  Since code 
577    cannot be inserted on these edges, failure to coalesce something across
578    an abnormal edge is an error.  */
579
580 static void
581 coalesce_abnormal_edges (var_map map, conflict_graph graph, root_var_p rv)
582 {
583   basic_block bb;
584   edge e;
585   tree phi, var, tmp;
586   int x, y, z;
587   edge_iterator ei;
588
589   /* Code cannot be inserted on abnormal edges. Look for all abnormal 
590      edges, and coalesce any PHI results with their arguments across 
591      that edge.  */
592
593   FOR_EACH_BB (bb)
594     FOR_EACH_EDGE (e, ei, bb->succs)
595       if (e->dest != EXIT_BLOCK_PTR && e->flags & EDGE_ABNORMAL)
596         for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
597           {
598             /* Visit each PHI on the destination side of this abnormal
599                edge, and attempt to coalesce the argument with the result.  */
600             var = PHI_RESULT (phi);
601             x = var_to_partition (map, var);
602
603             /* Ignore results which are not relevant.  */
604             if (x == NO_PARTITION)
605               continue;
606
607             tmp = PHI_ARG_DEF (phi, e->dest_idx);
608 #ifdef ENABLE_CHECKING
609             if (!phi_ssa_name_p (tmp))
610               {
611                 print_exprs_edge (stderr, e,
612                                   "\nConstant argument in PHI. Can't insert :",
613                                   var, " = ", tmp);
614                 internal_error ("SSA corruption");
615               }
616 #else
617             gcc_assert (phi_ssa_name_p (tmp));
618 #endif
619             y = var_to_partition (map, tmp);
620             gcc_assert (x != NO_PARTITION);
621             gcc_assert (y != NO_PARTITION);
622 #ifdef ENABLE_CHECKING
623             if (root_var_find (rv, x) != root_var_find (rv, y))
624               {
625                 print_exprs_edge (stderr, e, "\nDifferent root vars: ",
626                                   root_var (rv, root_var_find (rv, x)), 
627                                   " and ", 
628                                   root_var (rv, root_var_find (rv, y)));
629                 internal_error ("SSA corruption");
630               }
631 #else
632             gcc_assert (root_var_find (rv, x) == root_var_find (rv, y));
633 #endif
634
635             if (x != y)
636               {
637 #ifdef ENABLE_CHECKING
638                 if (conflict_graph_conflict_p (graph, x, y))
639                   {
640                     print_exprs_edge (stderr, e, "\n Conflict ", 
641                                       partition_to_var (map, x),
642                                       " and ", partition_to_var (map, y));
643                     internal_error ("SSA corruption");
644                   }
645 #else
646                 gcc_assert (!conflict_graph_conflict_p (graph, x, y));
647 #endif
648                 
649                 /* Now map the partitions back to their real variables.  */
650                 var = partition_to_var (map, x);
651                 tmp = partition_to_var (map, y);
652                 if (dump_file && (dump_flags & TDF_DETAILS))
653                   {
654                     print_exprs_edge (dump_file, e, 
655                                       "ABNORMAL: Coalescing ",
656                                       var, " and ", tmp);
657                   }
658                 z = var_union (map, var, tmp);
659 #ifdef ENABLE_CHECKING
660                 if (z == NO_PARTITION)
661                   {
662                     print_exprs_edge (stderr, e, "\nUnable to coalesce", 
663                                       partition_to_var (map, x), " and ", 
664                                       partition_to_var (map, y));
665                     internal_error ("SSA corruption");
666                   }
667 #else
668                 gcc_assert (z != NO_PARTITION);
669 #endif
670                 gcc_assert (z == x || z == y);
671                 if (z == x)
672                   conflict_graph_merge_regs (graph, x, y);
673                 else
674                   conflict_graph_merge_regs (graph, y, x);
675               }
676           }
677 }
678
679
680 /* Reduce the number of live ranges in MAP.  Live range information is 
681    returned if FLAGS indicates that we are combining temporaries, otherwise 
682    NULL is returned.  The only partitions which are associated with actual 
683    variables at this point are those which are forced to be coalesced for 
684    various reason. (live on entry, live across abnormal edges, etc.).  */
685
686 static tree_live_info_p
687 coalesce_ssa_name (var_map map, int flags)
688 {
689   unsigned num, x, i;
690   sbitmap live;
691   tree var, phi;
692   root_var_p rv;
693   tree_live_info_p liveinfo;
694   var_ann_t ann;
695   conflict_graph graph;
696   basic_block bb;
697   coalesce_list_p cl = NULL;
698   sbitmap_iterator sbi;
699
700   if (num_var_partitions (map) <= 1)
701     return NULL;
702
703   liveinfo = calculate_live_on_entry (map);
704   calculate_live_on_exit (liveinfo);
705   rv = root_var_init (map);
706
707   /* Remove single element variable from the list.  */
708   root_var_compact (rv);
709
710   cl = create_coalesce_list (map);
711
712   /* Add all potential copies via PHI arguments to the list.  */
713   FOR_EACH_BB (bb)
714     {
715       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
716         {
717           tree res = PHI_RESULT (phi);
718           int p = var_to_partition (map, res);
719           if (p == NO_PARTITION)
720             continue;
721           for (x = 0; x < (unsigned)PHI_NUM_ARGS (phi); x++)
722             {
723               tree arg = PHI_ARG_DEF (phi, x);
724               int p2;
725
726               if (TREE_CODE (arg) != SSA_NAME)
727                 continue;
728               if (SSA_NAME_VAR (res) != SSA_NAME_VAR (arg))
729                 continue;
730               p2 = var_to_partition (map, PHI_ARG_DEF (phi, x));
731               if (p2 != NO_PARTITION)
732                 {
733                   edge e = PHI_ARG_EDGE (phi, x);
734                   add_coalesce (cl, p, p2,
735                                 coalesce_cost (EDGE_FREQUENCY (e),
736                                                maybe_hot_bb_p (bb),
737                                                EDGE_CRITICAL_P (e)));
738                 }
739             }
740         }
741     }
742
743   /* Coalesce all the result decls together.  */
744   var = NULL_TREE;
745   i = 0;
746   for (x = 0; x < num_var_partitions (map); x++)
747     {
748       tree p = partition_to_var (map, x);
749       if (TREE_CODE (SSA_NAME_VAR(p)) == RESULT_DECL)
750         {
751           if (var == NULL_TREE)
752             {
753               var = p;
754               i = x;
755             }
756           else
757             add_coalesce (cl, i, x,
758                           coalesce_cost (EXIT_BLOCK_PTR->frequency,
759                                          maybe_hot_bb_p (EXIT_BLOCK_PTR),
760                                          false));
761         }
762     }
763
764   /* Build a conflict graph.  */
765   graph = build_tree_conflict_graph (liveinfo, rv, cl);
766
767   if (cl)
768     {
769       if (dump_file && (dump_flags & TDF_DETAILS))
770         {
771           fprintf (dump_file, "Before sorting:\n");
772           dump_coalesce_list (dump_file, cl);
773         }
774
775       sort_coalesce_list (cl);
776
777       if (dump_file && (dump_flags & TDF_DETAILS))
778         {
779           fprintf (dump_file, "\nAfter sorting:\n");
780           dump_coalesce_list (dump_file, cl);
781         }
782     }
783
784   /* Put the single element variables back in.  */
785   root_var_decompact (rv);
786
787   /* First, coalesce all live on entry variables to their root variable. 
788      This will ensure the first use is coming from the correct location.  */
789
790   live = sbitmap_alloc (num_var_partitions (map));
791   sbitmap_zero (live);
792
793   /* Set 'live' vector to indicate live on entry partitions.  */
794   num = num_var_partitions (map);
795   for (x = 0 ; x < num; x++)
796     {
797       var = partition_to_var (map, x);
798       if (default_def (SSA_NAME_VAR (var)) == var)
799         SET_BIT (live, x);
800     }
801
802   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
803     {
804       delete_tree_live_info (liveinfo);
805       liveinfo = NULL;
806     }
807
808   /* Assign root variable as partition representative for each live on entry
809      partition.  */
810   EXECUTE_IF_SET_IN_SBITMAP (live, 0, x, sbi)
811     {
812       var = root_var (rv, root_var_find (rv, x));
813       ann = var_ann (var);
814       /* If these aren't already coalesced...  */
815       if (partition_to_var (map, x) != var)
816         {
817           /* This root variable should have not already been assigned
818              to another partition which is not coalesced with this one.  */
819           gcc_assert (!ann->out_of_ssa_tag);
820
821           if (dump_file && (dump_flags & TDF_DETAILS))
822             {
823               print_exprs (dump_file, "Must coalesce ", 
824                            partition_to_var (map, x),
825                            " with the root variable ", var, ".\n");
826             }
827
828           change_partition_var (map, var, x);
829         }
830     }
831
832   sbitmap_free (live);
833
834   /* Coalesce partitions live across abnormal edges.  */
835   coalesce_abnormal_edges (map, graph, rv);
836
837   if (dump_file && (dump_flags & TDF_DETAILS))
838     dump_var_map (dump_file, map);
839
840   /* Coalesce partitions.  */
841   coalesce_tpa_members (rv, graph, map, cl,
842                         ((dump_flags & TDF_DETAILS) ? dump_file
843                          : NULL));
844
845   if (flags & SSANORM_COALESCE_PARTITIONS)
846     coalesce_tpa_members (rv, graph, map, NULL,
847                           ((dump_flags & TDF_DETAILS) ? dump_file
848                            : NULL));
849   if (cl)
850     delete_coalesce_list (cl);
851   root_var_delete (rv);
852   conflict_graph_delete (graph);
853
854   return liveinfo;
855 }
856
857
858 /* Take the ssa-name var_map MAP, and assign real variables to each 
859    partition.  */
860
861 static void
862 assign_vars (var_map map)
863 {
864   int x, i, num, rep;
865   tree t, var;
866   var_ann_t ann;
867   root_var_p rv;
868
869   rv = root_var_init (map);
870   if (!rv) 
871     return;
872
873   /* Coalescing may already have forced some partitions to their root 
874      variable. Find these and tag them.  */
875
876   num = num_var_partitions (map);
877   for (x = 0; x < num; x++)
878     {
879       var = partition_to_var (map, x);
880       if (TREE_CODE (var) != SSA_NAME)
881         {
882           /* Coalescing will already have verified that more than one
883              partition doesn't have the same root variable. Simply marked
884              the variable as assigned.  */
885           ann = var_ann (var);
886           ann->out_of_ssa_tag = 1;
887           if (dump_file && (dump_flags & TDF_DETAILS))
888             {
889               fprintf (dump_file, "partition %d has variable ", x);
890               print_generic_expr (dump_file, var, TDF_SLIM);
891               fprintf (dump_file, " assigned to it.\n");
892             }
893
894         }
895     }
896
897   num = root_var_num (rv);
898   for (x = 0; x < num; x++)
899     {
900       var = root_var (rv, x);
901       ann = var_ann (var);
902       for (i = root_var_first_partition (rv, x);
903            i != ROOT_VAR_NONE;
904            i = root_var_next_partition (rv, i))
905         {
906           t = partition_to_var (map, i);
907
908           if (t == var || TREE_CODE (t) != SSA_NAME)
909             continue;
910
911           rep = var_to_partition (map, t);
912           
913           if (!ann->out_of_ssa_tag)
914             {
915               if (dump_file && (dump_flags & TDF_DETAILS))
916                 print_exprs (dump_file, "", t, "  --> ", var, "\n");
917               change_partition_var (map, var, rep);
918               continue;
919             }
920
921           if (dump_file && (dump_flags & TDF_DETAILS))
922             print_exprs (dump_file, "", t, " not coalesced with ", var, 
923                          "");
924
925           var = create_temp (t);
926           change_partition_var (map, var, rep);
927           ann = var_ann (var);
928
929           if (dump_file && (dump_flags & TDF_DETAILS))
930             {
931               fprintf (dump_file, " -->  New temp:  '");
932               print_generic_expr (dump_file, var, TDF_SLIM);
933               fprintf (dump_file, "'\n");
934             }
935         }
936     }
937
938   root_var_delete (rv);
939 }
940
941
942 /* Replace use operand P with whatever variable it has been rewritten to based 
943    on the partitions in MAP.  EXPR is an optional expression vector over SSA 
944    versions which is used to replace P with an expression instead of a variable.
945    If the stmt is changed, return true.  */ 
946
947 static inline bool
948 replace_use_variable (var_map map, use_operand_p p, tree *expr)
949 {
950   tree new_var;
951   tree var = USE_FROM_PTR (p);
952
953   /* Check if we are replacing this variable with an expression.  */
954   if (expr)
955     {
956       int version = SSA_NAME_VERSION (var);
957       if (expr[version])
958         {
959           tree new_expr = TREE_OPERAND (expr[version], 1);
960           SET_USE (p, new_expr);
961           /* Clear the stmt's RHS, or GC might bite us.  */
962           TREE_OPERAND (expr[version], 1) = NULL_TREE;
963           return true;
964         }
965     }
966
967   new_var = var_to_partition_to_var (map, var);
968   if (new_var)
969     {
970       SET_USE (p, new_var);
971       set_is_used (new_var);
972       return true;
973     }
974   return false;
975 }
976
977
978 /* Replace def operand DEF_P with whatever variable it has been rewritten to 
979    based on the partitions in MAP.  EXPR is an optional expression vector over
980    SSA versions which is used to replace DEF_P with an expression instead of a 
981    variable.  If the stmt is changed, return true.  */ 
982
983 static inline bool
984 replace_def_variable (var_map map, def_operand_p def_p, tree *expr)
985 {
986   tree new_var;
987   tree var = DEF_FROM_PTR (def_p);
988
989   /* Check if we are replacing this variable with an expression.  */
990   if (expr)
991     {
992       int version = SSA_NAME_VERSION (var);
993       if (expr[version])
994         {
995           tree new_expr = TREE_OPERAND (expr[version], 1);
996           SET_DEF (def_p, new_expr);
997           /* Clear the stmt's RHS, or GC might bite us.  */
998           TREE_OPERAND (expr[version], 1) = NULL_TREE;
999           return true;
1000         }
1001     }
1002
1003   new_var = var_to_partition_to_var (map, var);
1004   if (new_var)
1005     {
1006       SET_DEF (def_p, new_var);
1007       set_is_used (new_var);
1008       return true;
1009     }
1010   return false;
1011 }
1012
1013
1014 /* Remove any PHI node which is a virtual PHI.  */
1015
1016 static void
1017 eliminate_virtual_phis (void)
1018 {
1019   basic_block bb;
1020   tree phi, next;
1021
1022   FOR_EACH_BB (bb)
1023     {
1024       for (phi = phi_nodes (bb); phi; phi = next)
1025         {
1026           next = PHI_CHAIN (phi);
1027           if (!is_gimple_reg (SSA_NAME_VAR (PHI_RESULT (phi))))
1028             {
1029 #ifdef ENABLE_CHECKING
1030               int i;
1031               /* There should be no arguments of this PHI which are in
1032                  the partition list, or we get incorrect results.  */
1033               for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1034                 {
1035                   tree arg = PHI_ARG_DEF (phi, i);
1036                   if (TREE_CODE (arg) == SSA_NAME 
1037                       && is_gimple_reg (SSA_NAME_VAR (arg)))
1038                     {
1039                       fprintf (stderr, "Argument of PHI is not virtual (");
1040                       print_generic_expr (stderr, arg, TDF_SLIM);
1041                       fprintf (stderr, "), but the result is :");
1042                       print_generic_stmt (stderr, phi, TDF_SLIM);
1043                       internal_error ("SSA corruption");
1044                     }
1045                 }
1046 #endif
1047               remove_phi_node (phi, NULL_TREE);
1048             }
1049         }
1050     }
1051 }
1052
1053
1054 /* This routine will coalesce variables in MAP of the same type which do not 
1055    interfere with each other. LIVEINFO is the live range info for variables
1056    of interest.  This will both reduce the memory footprint of the stack, and 
1057    allow us to coalesce together local copies of globals and scalarized 
1058    component refs.  */
1059
1060 static void
1061 coalesce_vars (var_map map, tree_live_info_p liveinfo)
1062 {
1063   basic_block bb;
1064   type_var_p tv;
1065   tree var;
1066   unsigned x, p, p2;
1067   coalesce_list_p cl;
1068   conflict_graph graph;
1069
1070   cl = create_coalesce_list (map);
1071
1072   /* Merge all the live on entry vectors for coalesced partitions.  */
1073   for (x = 0; x < num_var_partitions (map); x++)
1074     {
1075       var = partition_to_var (map, x);
1076       p = var_to_partition (map, var);
1077       if (p != x)
1078         live_merge_and_clear (liveinfo, p, x);
1079     }
1080
1081   /* When PHI nodes are turned into copies, the result of each PHI node
1082      becomes live on entry to the block. Mark these now.  */
1083   FOR_EACH_BB (bb)
1084     {
1085       tree phi, arg;
1086       unsigned p;
1087       
1088       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1089         {
1090           p = var_to_partition (map, PHI_RESULT (phi));
1091
1092           /* Skip virtual PHI nodes.  */
1093           if (p == (unsigned)NO_PARTITION)
1094             continue;
1095
1096           make_live_on_entry (liveinfo, bb, p);
1097
1098           /* Each argument is a potential copy operation. Add any arguments 
1099              which are not coalesced to the result to the coalesce list.  */
1100           for (x = 0; x < (unsigned)PHI_NUM_ARGS (phi); x++)
1101             {
1102               arg = PHI_ARG_DEF (phi, x);
1103               if (!phi_ssa_name_p (arg))
1104                 continue;
1105               p2 = var_to_partition (map, arg);
1106               if (p2 == (unsigned)NO_PARTITION)
1107                 continue;
1108               if (p != p2)
1109                 {
1110                   edge e = PHI_ARG_EDGE (phi, x);
1111
1112                   add_coalesce (cl, p, p2, 
1113                                 coalesce_cost (EDGE_FREQUENCY (e),
1114                                                maybe_hot_bb_p (bb),
1115                                                EDGE_CRITICAL_P (e)));
1116                 }
1117             }
1118         }
1119    }
1120
1121   
1122   /* Re-calculate live on exit info.  */
1123   calculate_live_on_exit (liveinfo);
1124
1125   if (dump_file && (dump_flags & TDF_DETAILS))
1126     {
1127       fprintf (dump_file, "Live range info for variable memory coalescing.\n");
1128       dump_live_info (dump_file, liveinfo, LIVEDUMP_ALL);
1129
1130       fprintf (dump_file, "Coalesce list from phi nodes:\n");
1131       dump_coalesce_list (dump_file, cl);
1132     }
1133
1134
1135   tv = type_var_init (map);
1136   if (dump_file)
1137     type_var_dump (dump_file, tv);
1138   type_var_compact (tv);
1139   if (dump_file)
1140     type_var_dump (dump_file, tv);
1141
1142   graph = build_tree_conflict_graph (liveinfo, tv, cl);
1143
1144   type_var_decompact (tv);
1145   if (dump_file && (dump_flags & TDF_DETAILS))
1146     {
1147       fprintf (dump_file, "type var list now looks like:n");
1148       type_var_dump (dump_file, tv);
1149
1150       fprintf (dump_file, "Coalesce list after conflict graph build:\n");
1151       dump_coalesce_list (dump_file, cl);
1152     }
1153
1154   sort_coalesce_list (cl);
1155   if (dump_file && (dump_flags & TDF_DETAILS))
1156     {
1157       fprintf (dump_file, "Coalesce list after sorting:\n");
1158       dump_coalesce_list (dump_file, cl);
1159     }
1160
1161   coalesce_tpa_members (tv, graph, map, cl, 
1162                         ((dump_flags & TDF_DETAILS) ? dump_file : NULL));
1163
1164   type_var_delete (tv);
1165   delete_coalesce_list (cl);
1166 }
1167
1168
1169 /* Temporary Expression Replacement (TER)
1170
1171    Replace SSA version variables during out-of-ssa with their defining
1172    expression if there is only one use of the variable.
1173
1174    A pass is made through the function, one block at a time.  No cross block
1175    information is tracked.
1176
1177    Variables which only have one use, and whose defining stmt is considered
1178    a replaceable expression (see check_replaceable) are entered into 
1179    consideration by adding a list of dependent partitions to the version_info
1180    vector for that ssa_name_version.  This information comes from the partition
1181    mapping for each USE.  At the same time, the partition_dep_list vector for 
1182    these partitions have this version number entered into their lists.
1183
1184    When the use of a replaceable ssa_variable is encountered, the dependence
1185    list in version_info[] is moved to the "pending_dependence" list in case
1186    the current expression is also replaceable. (To be determined later in 
1187    processing this stmt.) version_info[] for the version is then updated to 
1188    point to the defining stmt and the 'replaceable' bit is set.
1189
1190    Any partition which is defined by a statement 'kills' any expression which
1191    is dependent on this partition.  Every ssa version in the partitions' 
1192    dependence list is removed from future consideration.
1193
1194    All virtual references are lumped together.  Any expression which is
1195    dependent on any virtual variable (via a VUSE) has a dependence added
1196    to the special partition defined by VIRTUAL_PARTITION.
1197
1198    Whenever a V_MAY_DEF is seen, all expressions dependent this 
1199    VIRTUAL_PARTITION are removed from consideration.
1200
1201    At the end of a basic block, all expression are removed from consideration
1202    in preparation for the next block.  
1203    
1204    The end result is a vector over SSA_NAME_VERSION which is passed back to
1205    rewrite_out_of_ssa.  As the SSA variables are being rewritten, instead of
1206    replacing the SSA_NAME tree element with the partition it was assigned, 
1207    it is replaced with the RHS of the defining expression.  */
1208
1209
1210 /* Dependency list element.  This can contain either a partition index or a
1211    version number, depending on which list it is in.  */
1212
1213 typedef struct value_expr_d 
1214 {
1215   int value;
1216   struct value_expr_d *next;
1217 } *value_expr_p;
1218
1219
1220 /* Temporary Expression Replacement (TER) table information.  */
1221
1222 typedef struct temp_expr_table_d 
1223 {
1224   var_map map;
1225   void **version_info;          
1226   value_expr_p *partition_dep_list;
1227   bitmap replaceable;
1228   bool saw_replaceable;
1229   int virtual_partition;
1230   bitmap partition_in_use;
1231   value_expr_p free_list;
1232   value_expr_p pending_dependence;
1233 } *temp_expr_table_p;
1234
1235 /* Used to indicate a dependency on V_MAY_DEFs.  */
1236 #define VIRTUAL_PARTITION(table)        (table->virtual_partition)
1237
1238 static temp_expr_table_p new_temp_expr_table (var_map);
1239 static tree *free_temp_expr_table (temp_expr_table_p);
1240 static inline value_expr_p new_value_expr (temp_expr_table_p);
1241 static inline void free_value_expr (temp_expr_table_p, value_expr_p);
1242 static inline value_expr_p find_value_in_list (value_expr_p, int, 
1243                                                value_expr_p *);
1244 static inline void add_value_to_list (temp_expr_table_p, value_expr_p *, int);
1245 static inline void add_info_to_list (temp_expr_table_p, value_expr_p *, 
1246                                      value_expr_p);
1247 static value_expr_p remove_value_from_list (value_expr_p *, int);
1248 static void add_dependance (temp_expr_table_p, int, tree);
1249 static bool check_replaceable (temp_expr_table_p, tree);
1250 static void finish_expr (temp_expr_table_p, int, bool);
1251 static void mark_replaceable (temp_expr_table_p, tree);
1252 static inline void kill_expr (temp_expr_table_p, int, bool);
1253 static inline void kill_virtual_exprs (temp_expr_table_p, bool);
1254 static void find_replaceable_in_bb (temp_expr_table_p, basic_block);
1255 static tree *find_replaceable_exprs (var_map);
1256 static void dump_replaceable_exprs (FILE *, tree *);
1257
1258
1259 /* Create a new TER table for MAP.  */
1260
1261 static temp_expr_table_p
1262 new_temp_expr_table (var_map map)
1263 {
1264   temp_expr_table_p t;
1265
1266   t = (temp_expr_table_p) xmalloc (sizeof (struct temp_expr_table_d));
1267   t->map = map;
1268
1269   t->version_info = xcalloc (num_ssa_names + 1, sizeof (void *));
1270   t->partition_dep_list = xcalloc (num_var_partitions (map) + 1, 
1271                                    sizeof (value_expr_p));
1272
1273   t->replaceable = BITMAP_ALLOC (NULL);
1274   t->partition_in_use = BITMAP_ALLOC (NULL);
1275
1276   t->saw_replaceable = false;
1277   t->virtual_partition = num_var_partitions (map);
1278   t->free_list = NULL;
1279   t->pending_dependence = NULL;
1280
1281   return t;
1282 }
1283
1284
1285 /* Free TER table T.  If there are valid replacements, return the expression 
1286    vector.  */
1287
1288 static tree *
1289 free_temp_expr_table (temp_expr_table_p t)
1290 {
1291   value_expr_p p;
1292   tree *ret = NULL;
1293
1294 #ifdef ENABLE_CHECKING
1295   unsigned x;
1296   for (x = 0; x <= num_var_partitions (t->map); x++)
1297     gcc_assert (!t->partition_dep_list[x]);
1298 #endif
1299
1300   while ((p = t->free_list))
1301     {
1302       t->free_list = p->next;
1303       free (p);
1304     }
1305
1306   BITMAP_FREE (t->partition_in_use);
1307   BITMAP_FREE (t->replaceable);
1308
1309   free (t->partition_dep_list);
1310   if (t->saw_replaceable)
1311     ret = (tree *)t->version_info;
1312   else
1313     free (t->version_info);
1314   
1315   free (t);
1316   return ret;
1317 }
1318
1319
1320 /* Allocate a new value list node. Take it from the free list in TABLE if 
1321    possible.  */
1322
1323 static inline value_expr_p
1324 new_value_expr (temp_expr_table_p table)
1325 {
1326   value_expr_p p;
1327   if (table->free_list)
1328     {
1329       p = table->free_list;
1330       table->free_list = p->next;
1331     }
1332   else
1333     p = (value_expr_p) xmalloc (sizeof (struct value_expr_d));
1334
1335   return p;
1336 }
1337
1338
1339 /* Add value list node P to the free list in TABLE.  */
1340
1341 static inline void
1342 free_value_expr (temp_expr_table_p table, value_expr_p p)
1343 {
1344   p->next = table->free_list;
1345   table->free_list = p;
1346 }
1347
1348
1349 /* Find VALUE if it's in LIST.  Return a pointer to the list object if found,  
1350    else return NULL.  If LAST_PTR is provided, it will point to the previous 
1351    item upon return, or NULL if this is the first item in the list.  */
1352
1353 static inline value_expr_p
1354 find_value_in_list (value_expr_p list, int value, value_expr_p *last_ptr)
1355 {
1356   value_expr_p curr;
1357   value_expr_p last = NULL;
1358
1359   for (curr = list; curr; last = curr, curr = curr->next)
1360     {
1361       if (curr->value == value)
1362         break;
1363     }
1364   if (last_ptr)
1365     *last_ptr = last;
1366   return curr;
1367 }
1368
1369
1370 /* Add VALUE to LIST, if it isn't already present.  TAB is the expression 
1371    table */
1372
1373 static inline void
1374 add_value_to_list (temp_expr_table_p tab, value_expr_p *list, int value)
1375 {
1376   value_expr_p info;
1377
1378   if (!find_value_in_list (*list, value, NULL))
1379     {
1380       info = new_value_expr (tab);
1381       info->value = value;
1382       info->next = *list;
1383       *list = info;
1384     }
1385 }
1386
1387
1388 /* Add value node INFO if it's value isn't already in LIST.  Free INFO if
1389    it is already in the list. TAB is the expression table.  */
1390
1391 static inline void
1392 add_info_to_list (temp_expr_table_p tab, value_expr_p *list, value_expr_p info)
1393 {
1394   if (find_value_in_list (*list, info->value, NULL))
1395     free_value_expr (tab, info);
1396   else
1397     {
1398       info->next = *list;
1399       *list = info;
1400     }
1401 }
1402
1403
1404 /* Look for VALUE in LIST.  If found, remove it from the list and return it's 
1405    pointer.  */
1406
1407 static value_expr_p
1408 remove_value_from_list (value_expr_p *list, int value)
1409 {
1410   value_expr_p info, last;
1411
1412   info = find_value_in_list (*list, value, &last);
1413   if (!info)
1414     return NULL;
1415   if (!last)
1416     *list = info->next;
1417   else
1418     last->next = info->next;
1419  
1420   return info;
1421 }
1422
1423
1424 /* Add a dependency between the def of ssa VERSION and VAR.  If VAR is 
1425    replaceable by an expression, add a dependence each of the elements of the 
1426    expression.  These are contained in the pending list.  TAB is the
1427    expression table.  */
1428
1429 static void
1430 add_dependance (temp_expr_table_p tab, int version, tree var)
1431 {
1432   int i, x;
1433   value_expr_p info;
1434
1435   i = SSA_NAME_VERSION (var);
1436   if (bitmap_bit_p (tab->replaceable, i))
1437     {
1438       /* This variable is being substituted, so use whatever dependences
1439          were queued up when we marked this as replaceable earlier.  */
1440       while ((info = tab->pending_dependence))
1441         {
1442           tab->pending_dependence = info->next;
1443           /* Get the partition this variable was dependent on. Reuse this
1444              object to represent the current  expression instead.  */
1445           x = info->value;
1446           info->value = version;
1447           add_info_to_list (tab, &(tab->partition_dep_list[x]), info);
1448           add_value_to_list (tab, 
1449                              (value_expr_p *)&(tab->version_info[version]), x);
1450           bitmap_set_bit (tab->partition_in_use, x);
1451         }
1452     }
1453   else
1454     {
1455       i = var_to_partition (tab->map, var);
1456       gcc_assert (i != NO_PARTITION);
1457       add_value_to_list (tab, &(tab->partition_dep_list[i]), version);
1458       add_value_to_list (tab, 
1459                          (value_expr_p *)&(tab->version_info[version]), i);
1460       bitmap_set_bit (tab->partition_in_use, i);
1461     }
1462 }
1463
1464
1465 /* Check if expression STMT is suitable for replacement in table TAB.  If so, 
1466    create an expression entry.  Return true if this stmt is replaceable.  */
1467
1468 static bool
1469 check_replaceable (temp_expr_table_p tab, tree stmt)
1470 {
1471   tree var, def;
1472   int version;
1473   var_map map = tab->map;
1474   ssa_op_iter iter;
1475   tree call_expr;
1476
1477   if (TREE_CODE (stmt) != MODIFY_EXPR)
1478     return false;
1479   
1480   /* Punt if there is more than 1 def, or more than 1 use.  */
1481   def = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_DEF);
1482   if (!def)
1483     return false;
1484
1485   if (version_ref_count (map, def) != 1)
1486     return false;
1487
1488   /* There must be no V_MAY_DEFS or V_MUST_DEFS.  */
1489   if (!(ZERO_SSA_OPERANDS (stmt, (SSA_OP_VMAYDEF | SSA_OP_VMUSTDEF))))
1490     return false;
1491
1492   /* Float expressions must go through memory if float-store is on.  */
1493   if (flag_float_store && FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 1))))
1494     return false;
1495
1496   /* Calls to functions with side-effects cannot be replaced.  */
1497   if ((call_expr = get_call_expr_in (stmt)) != NULL_TREE)
1498     {
1499       int call_flags = call_expr_flags (call_expr);
1500       if (TREE_SIDE_EFFECTS (call_expr)
1501           && !(call_flags & (ECF_PURE | ECF_CONST | ECF_NORETURN)))
1502         return false;
1503     }
1504
1505   version = SSA_NAME_VERSION (def);
1506
1507   /* Add this expression to the dependency list for each use partition.  */
1508   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_USE)
1509     {
1510       add_dependance (tab, version, var);
1511     }
1512
1513   /* If there are VUSES, add a dependence on virtual defs.  */
1514   if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_VUSE))
1515     {
1516       add_value_to_list (tab, (value_expr_p *)&(tab->version_info[version]), 
1517                          VIRTUAL_PARTITION (tab));
1518       add_value_to_list (tab, 
1519                          &(tab->partition_dep_list[VIRTUAL_PARTITION (tab)]), 
1520                          version);
1521       bitmap_set_bit (tab->partition_in_use, VIRTUAL_PARTITION (tab));
1522     }
1523
1524   return true;
1525 }
1526
1527
1528 /* This function will remove the expression for VERSION from replacement 
1529    consideration.n table TAB  If 'replace' is true, it is marked as 
1530    replaceable, otherwise not.  */
1531
1532 static void
1533 finish_expr (temp_expr_table_p tab, int version, bool replace)
1534 {
1535   value_expr_p info, tmp;
1536   int partition;
1537
1538   /* Remove this expression from its dependent lists.  The partition dependence
1539      list is retained and transfered later to whomever uses this version.  */
1540   for (info = (value_expr_p) tab->version_info[version]; info; info = tmp)
1541     {
1542       partition = info->value;
1543       gcc_assert (tab->partition_dep_list[partition]);
1544       tmp = remove_value_from_list (&(tab->partition_dep_list[partition]), 
1545                                     version);
1546       gcc_assert (tmp);
1547       free_value_expr (tab, tmp);
1548       /* Only clear the bit when the dependency list is emptied via 
1549          a replacement. Otherwise kill_expr will take care of it.  */
1550       if (!(tab->partition_dep_list[partition]) && replace)
1551         bitmap_clear_bit (tab->partition_in_use, partition);
1552       tmp = info->next;
1553       if (!replace)
1554         free_value_expr (tab, info);
1555     }
1556
1557   if (replace)
1558     {
1559       tab->saw_replaceable = true;
1560       bitmap_set_bit (tab->replaceable, version);
1561     }
1562   else
1563     {
1564       gcc_assert (!bitmap_bit_p (tab->replaceable, version));
1565       tab->version_info[version] = NULL;
1566     }
1567 }
1568
1569
1570 /* Mark the expression associated with VAR as replaceable, and enter
1571    the defining stmt into the version_info table TAB.  */
1572
1573 static void
1574 mark_replaceable (temp_expr_table_p tab, tree var)
1575 {
1576   value_expr_p info;
1577   int version = SSA_NAME_VERSION (var);
1578   finish_expr (tab, version, true);
1579
1580   /* Move the dependence list to the pending list.  */
1581   if (tab->version_info[version])
1582     {
1583       info = (value_expr_p) tab->version_info[version]; 
1584       for ( ; info->next; info = info->next)
1585         continue;
1586       info->next = tab->pending_dependence;
1587       tab->pending_dependence = (value_expr_p)tab->version_info[version];
1588     }
1589
1590   tab->version_info[version] = SSA_NAME_DEF_STMT (var);
1591 }
1592
1593
1594 /* This function marks any expression in TAB which is dependent on PARTITION
1595    as NOT replaceable.  CLEAR_BIT is used to determine whether partition_in_use
1596    should have its bit cleared.  Since this routine can be called within an
1597    EXECUTE_IF_SET_IN_BITMAP, the bit can't always be cleared.  */
1598
1599 static inline void
1600 kill_expr (temp_expr_table_p tab, int partition, bool clear_bit)
1601 {
1602   value_expr_p ptr;
1603
1604   /* Mark every active expr dependent on this var as not replaceable.  */
1605   while ((ptr = tab->partition_dep_list[partition]) != NULL)
1606     finish_expr (tab, ptr->value, false);
1607
1608   if (clear_bit)
1609     bitmap_clear_bit (tab->partition_in_use, partition);
1610 }
1611
1612
1613 /* This function kills all expressions in TAB which are dependent on virtual 
1614    DEFs.  CLEAR_BIT determines whether partition_in_use gets cleared.  */
1615
1616 static inline void
1617 kill_virtual_exprs (temp_expr_table_p tab, bool clear_bit)
1618 {
1619   kill_expr (tab, VIRTUAL_PARTITION (tab), clear_bit);
1620 }
1621
1622
1623 /* This function processes basic block BB, and looks for variables which can
1624    be replaced by their expressions.  Results are stored in TAB.  */
1625
1626 static void
1627 find_replaceable_in_bb (temp_expr_table_p tab, basic_block bb)
1628 {
1629   block_stmt_iterator bsi;
1630   tree stmt, def;
1631   stmt_ann_t ann;
1632   int partition;
1633   var_map map = tab->map;
1634   value_expr_p p;
1635   ssa_op_iter iter;
1636
1637   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1638     {
1639       stmt = bsi_stmt (bsi);
1640       ann = stmt_ann (stmt);
1641
1642       /* Determine if this stmt finishes an existing expression.  */
1643       FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_USE)
1644         {
1645           if (tab->version_info[SSA_NAME_VERSION (def)])
1646             {
1647               bool same_root_var = false;
1648               tree def2;
1649               ssa_op_iter iter2;
1650
1651               /* See if the root variables are the same.  If they are, we
1652                  do not want to do the replacement to avoid problems with
1653                  code size, see PR tree-optimization/17549.  */
1654               FOR_EACH_SSA_TREE_OPERAND (def2, stmt, iter2, SSA_OP_DEF)
1655                 if (SSA_NAME_VAR (def) == SSA_NAME_VAR (def2))
1656                   {
1657                     same_root_var = true;
1658                     break;
1659                   }
1660
1661               /* Mark expression as replaceable unless stmt is volatile
1662                  or DEF sets the same root variable as STMT.  */
1663               if (!ann->has_volatile_ops && !same_root_var)
1664                 mark_replaceable (tab, def);
1665               else
1666                 finish_expr (tab, SSA_NAME_VERSION (def), false);
1667             }
1668         }
1669       
1670       /* Next, see if this stmt kills off an active expression.  */
1671       FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
1672         {
1673           partition = var_to_partition (map, def);
1674           if (partition != NO_PARTITION && tab->partition_dep_list[partition])
1675             kill_expr (tab, partition, true);
1676         }
1677
1678       /* Now see if we are creating a new expression or not.  */
1679       if (!ann->has_volatile_ops)
1680         check_replaceable (tab, stmt);
1681
1682       /* Free any unused dependency lists.  */
1683       while ((p = tab->pending_dependence))
1684         {
1685           tab->pending_dependence = p->next;
1686           free_value_expr (tab, p);
1687         }
1688
1689       /* A V_{MAY,MUST}_DEF kills any expression using a virtual operand.  */
1690       if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_VIRTUAL_DEFS))
1691         kill_virtual_exprs (tab, true);
1692     }
1693 }
1694
1695
1696 /* This function is the driver routine for replacement of temporary expressions
1697    in the SSA->normal phase, operating on MAP.  If there are replaceable 
1698    expressions, a table is returned which maps SSA versions to the 
1699    expressions they should be replaced with.  A NULL_TREE indicates no 
1700    replacement should take place.  If there are no replacements at all, 
1701    NULL is returned by the function, otherwise an expression vector indexed
1702    by SSA_NAME version numbers.  */
1703
1704 static tree *
1705 find_replaceable_exprs (var_map map)
1706 {
1707   basic_block bb;
1708   unsigned i;
1709   temp_expr_table_p table;
1710   tree *ret;
1711
1712   table = new_temp_expr_table (map);
1713   FOR_EACH_BB (bb)
1714     {
1715       bitmap_iterator bi;
1716
1717       find_replaceable_in_bb (table, bb);
1718       EXECUTE_IF_SET_IN_BITMAP ((table->partition_in_use), 0, i, bi)
1719         {
1720           kill_expr (table, i, false);
1721         }
1722     }
1723
1724   ret = free_temp_expr_table (table);
1725   return ret;
1726 }
1727
1728
1729 /* Dump TER expression table EXPR to file F.  */
1730
1731 static void
1732 dump_replaceable_exprs (FILE *f, tree *expr)
1733 {
1734   tree stmt, var;
1735   int x;
1736   fprintf (f, "\nReplacing Expressions\n");
1737   for (x = 0; x < (int)num_ssa_names + 1; x++)
1738     if (expr[x])
1739       {
1740         stmt = expr[x];
1741         var = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_DEF);
1742         gcc_assert (var != NULL_TREE);
1743         print_generic_expr (f, var, TDF_SLIM);
1744         fprintf (f, " replace with --> ");
1745         print_generic_expr (f, TREE_OPERAND (stmt, 1), TDF_SLIM);
1746         fprintf (f, "\n");
1747       }
1748   fprintf (f, "\n");
1749 }
1750
1751
1752 /* Helper function for discover_nonconstant_array_refs. 
1753    Look for ARRAY_REF nodes with non-constant indexes and mark them
1754    addressable.  */
1755
1756 static tree
1757 discover_nonconstant_array_refs_r (tree * tp, int *walk_subtrees,
1758                                    void *data ATTRIBUTE_UNUSED)
1759 {
1760   tree t = *tp;
1761
1762   if (IS_TYPE_OR_DECL_P (t))
1763     *walk_subtrees = 0;
1764   else if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1765     {
1766       while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1767               && is_gimple_min_invariant (TREE_OPERAND (t, 1))
1768               && (!TREE_OPERAND (t, 2)
1769                   || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1770              || (TREE_CODE (t) == COMPONENT_REF
1771                  && (!TREE_OPERAND (t,2)
1772                      || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
1773              || TREE_CODE (t) == BIT_FIELD_REF
1774              || TREE_CODE (t) == REALPART_EXPR
1775              || TREE_CODE (t) == IMAGPART_EXPR
1776              || TREE_CODE (t) == VIEW_CONVERT_EXPR
1777              || TREE_CODE (t) == NOP_EXPR
1778              || TREE_CODE (t) == CONVERT_EXPR)
1779         t = TREE_OPERAND (t, 0);
1780
1781       if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
1782         {
1783           t = get_base_address (t);
1784           if (t && DECL_P (t))
1785             TREE_ADDRESSABLE (t) = 1;
1786         }
1787
1788       *walk_subtrees = 0;
1789     }
1790
1791   return NULL_TREE;
1792 }
1793
1794
1795 /* RTL expansion is not able to compile array references with variable
1796    offsets for arrays stored in single register.  Discover such
1797    expressions and mark variables as addressable to avoid this
1798    scenario.  */
1799
1800 static void
1801 discover_nonconstant_array_refs (void)
1802 {
1803   basic_block bb;
1804   block_stmt_iterator bsi;
1805
1806   FOR_EACH_BB (bb)
1807     {
1808       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1809         walk_tree (bsi_stmt_ptr (bsi), discover_nonconstant_array_refs_r,
1810                    NULL , NULL);
1811     }
1812 }
1813
1814
1815 /* This function will rewrite the current program using the variable mapping
1816    found in MAP.  If the replacement vector VALUES is provided, any 
1817    occurrences of partitions with non-null entries in the vector will be 
1818    replaced with the expression in the vector instead of its mapped 
1819    variable.  */
1820
1821 static void
1822 rewrite_trees (var_map map, tree *values)
1823 {
1824   elim_graph g;
1825   basic_block bb;
1826   block_stmt_iterator si;
1827   edge e;
1828   tree phi;
1829   bool changed;
1830  
1831 #ifdef ENABLE_CHECKING
1832   /* Search for PHIs where the destination has no partition, but one
1833      or more arguments has a partition.  This should not happen and can
1834      create incorrect code.  */
1835   FOR_EACH_BB (bb)
1836     {
1837       tree phi;
1838
1839       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1840         {
1841           tree T0 = var_to_partition_to_var (map, PHI_RESULT (phi));
1842       
1843           if (T0 == NULL_TREE)
1844             {
1845               int i;
1846
1847               for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1848                 {
1849                   tree arg = PHI_ARG_DEF (phi, i);
1850
1851                   if (TREE_CODE (arg) == SSA_NAME
1852                       && var_to_partition (map, arg) != NO_PARTITION)
1853                     {
1854                       fprintf (stderr, "Argument of PHI is in a partition :(");
1855                       print_generic_expr (stderr, arg, TDF_SLIM);
1856                       fprintf (stderr, "), but the result is not :");
1857                       print_generic_stmt (stderr, phi, TDF_SLIM);
1858                       internal_error ("SSA corruption");
1859                     }
1860                 }
1861             }
1862         }
1863     }
1864 #endif
1865
1866   /* Replace PHI nodes with any required copies.  */
1867   g = new_elim_graph (map->num_partitions);
1868   g->map = map;
1869   FOR_EACH_BB (bb)
1870     {
1871       for (si = bsi_start (bb); !bsi_end_p (si); )
1872         {
1873           tree stmt = bsi_stmt (si);
1874           use_operand_p use_p, copy_use_p;
1875           def_operand_p def_p;
1876           bool remove = false, is_copy = false;
1877           int num_uses = 0;
1878           stmt_ann_t ann;
1879           ssa_op_iter iter;
1880
1881           ann = stmt_ann (stmt);
1882           changed = false;
1883
1884           if (TREE_CODE (stmt) == MODIFY_EXPR 
1885               && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME))
1886             is_copy = true;
1887
1888           copy_use_p = NULL_USE_OPERAND_P;
1889           FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1890             {
1891               if (replace_use_variable (map, use_p, values))
1892                 changed = true;
1893               copy_use_p = use_p;
1894               num_uses++;
1895             }
1896
1897           if (num_uses != 1)
1898             is_copy = false;
1899
1900           def_p = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF);
1901
1902           if (def_p != NULL)
1903             {
1904               /* Mark this stmt for removal if it is the list of replaceable 
1905                  expressions.  */
1906               if (values && values[SSA_NAME_VERSION (DEF_FROM_PTR (def_p))])
1907                 remove = true;
1908               else
1909                 {
1910                   if (replace_def_variable (map, def_p, NULL))
1911                     changed = true;
1912                   /* If both SSA_NAMEs coalesce to the same variable,
1913                      mark the now redundant copy for removal.  */
1914                   if (is_copy)
1915                     {
1916                       gcc_assert (copy_use_p != NULL_USE_OPERAND_P);
1917                       if (DEF_FROM_PTR (def_p) == USE_FROM_PTR (copy_use_p))
1918                         remove = true;
1919                     }
1920                 }
1921             }
1922           else
1923             FOR_EACH_SSA_DEF_OPERAND (def_p, stmt, iter, SSA_OP_DEF)
1924               if (replace_def_variable (map, def_p, NULL))
1925                 changed = true;
1926
1927           /* Remove any stmts marked for removal.  */
1928           if (remove)
1929             bsi_remove (&si);
1930           else
1931             bsi_next (&si);
1932         }
1933
1934       phi = phi_nodes (bb);
1935       if (phi)
1936         {
1937           edge_iterator ei;
1938           FOR_EACH_EDGE (e, ei, bb->preds)
1939             eliminate_phi (e, g);
1940         }
1941     }
1942
1943   delete_elim_graph (g);
1944 }
1945
1946
1947 DEF_VEC_ALLOC_P(edge,heap);
1948
1949 /* These are the local work structures used to determine the best place to 
1950    insert the copies that were placed on edges by the SSA->normal pass..  */
1951 static VEC(edge,heap) *edge_leader;
1952 static VEC(tree,heap) *stmt_list;
1953 static bitmap leader_has_match = NULL;
1954 static edge leader_match = NULL;
1955
1956
1957 /* Pass this function to make_forwarder_block so that all the edges with
1958    matching PENDING_STMT lists to 'curr_stmt_list' get redirected.  */
1959 static bool 
1960 same_stmt_list_p (edge e)
1961 {
1962   return (e->aux == (PTR) leader_match) ? true : false;
1963 }
1964
1965
1966 /* Return TRUE if S1 and S2 are equivalent copies.  */
1967 static inline bool
1968 identical_copies_p (tree s1, tree s2)
1969 {
1970 #ifdef ENABLE_CHECKING
1971   gcc_assert (TREE_CODE (s1) == MODIFY_EXPR);
1972   gcc_assert (TREE_CODE (s2) == MODIFY_EXPR);
1973   gcc_assert (DECL_P (TREE_OPERAND (s1, 0)));
1974   gcc_assert (DECL_P (TREE_OPERAND (s2, 0)));
1975 #endif
1976
1977   if (TREE_OPERAND (s1, 0) != TREE_OPERAND (s2, 0))
1978     return false;
1979
1980   s1 = TREE_OPERAND (s1, 1);
1981   s2 = TREE_OPERAND (s2, 1);
1982
1983   if (s1 != s2)
1984     return false;
1985
1986   return true;
1987 }
1988
1989
1990 /* Compare the PENDING_STMT list for two edges, and return true if the lists
1991    contain the same sequence of copies.  */
1992
1993 static inline bool 
1994 identical_stmt_lists_p (edge e1, edge e2)
1995 {
1996   tree t1 = PENDING_STMT (e1);
1997   tree t2 = PENDING_STMT (e2);
1998   tree_stmt_iterator tsi1, tsi2;
1999
2000   gcc_assert (TREE_CODE (t1) == STATEMENT_LIST);
2001   gcc_assert (TREE_CODE (t2) == STATEMENT_LIST);
2002
2003   for (tsi1 = tsi_start (t1), tsi2 = tsi_start (t2);
2004        !tsi_end_p (tsi1) && !tsi_end_p (tsi2); 
2005        tsi_next (&tsi1), tsi_next (&tsi2))
2006     {
2007       if (!identical_copies_p (tsi_stmt (tsi1), tsi_stmt (tsi2)))
2008         break;
2009     }
2010
2011   if (!tsi_end_p (tsi1) || ! tsi_end_p (tsi2))
2012     return false;
2013
2014   return true;
2015 }
2016
2017
2018 /* Allocate data structures used in analyze_edges_for_bb.   */
2019
2020 static void
2021 init_analyze_edges_for_bb (void)
2022 {
2023   edge_leader = VEC_alloc (edge, heap, 25);
2024   stmt_list = VEC_alloc (tree, heap, 25);
2025   leader_has_match = BITMAP_ALLOC (NULL);
2026 }
2027
2028
2029 /* Free data structures used in analyze_edges_for_bb.   */
2030
2031 static void
2032 fini_analyze_edges_for_bb (void)
2033 {
2034   VEC_free (edge, heap, edge_leader);
2035   VEC_free (tree, heap, stmt_list);
2036   BITMAP_FREE (leader_has_match);
2037 }
2038
2039
2040 /* Look at all the incoming edges to block BB, and decide where the best place
2041    to insert the stmts on each edge are, and perform those insertions.   Output
2042    any debug information to DEBUG_FILE.  */
2043
2044 static void
2045 analyze_edges_for_bb (basic_block bb, FILE *debug_file)
2046 {
2047   edge e;
2048   edge_iterator ei;
2049   int count;
2050   unsigned int x;
2051   bool have_opportunity;
2052   block_stmt_iterator bsi;
2053   tree stmt;
2054   edge single_edge = NULL;
2055   bool is_label;
2056   edge leader;
2057
2058   count = 0;
2059
2060   /* Blocks which contain at least one abnormal edge cannot use 
2061      make_forwarder_block.  Look for these blocks, and commit any PENDING_STMTs
2062      found on edges in these block.  */
2063   have_opportunity = true;
2064   FOR_EACH_EDGE (e, ei, bb->preds)
2065     if (e->flags & EDGE_ABNORMAL)
2066       {
2067         have_opportunity = false;
2068         break;
2069       }
2070
2071   if (!have_opportunity)
2072     {
2073       FOR_EACH_EDGE (e, ei, bb->preds)
2074         if (PENDING_STMT (e))
2075           bsi_commit_one_edge_insert (e, NULL);
2076       return;
2077     }
2078   /* Find out how many edges there are with interesting pending stmts on them.  
2079      Commit the stmts on edges we are not interested in.  */
2080   FOR_EACH_EDGE (e, ei, bb->preds)
2081     {
2082       if (PENDING_STMT (e))
2083         {
2084           gcc_assert (!(e->flags & EDGE_ABNORMAL));
2085           if (e->flags & EDGE_FALLTHRU)
2086             {
2087               bsi = bsi_start (e->src);
2088               if (!bsi_end_p (bsi))
2089                 {
2090                   stmt = bsi_stmt (bsi);
2091                   bsi_next (&bsi);
2092                   gcc_assert (stmt != NULL_TREE);
2093                   is_label = (TREE_CODE (stmt) == LABEL_EXPR);
2094                   /* Punt if it has non-label stmts, or isn't local.  */
2095                   if (!is_label || DECL_NONLOCAL (TREE_OPERAND (stmt, 0)) 
2096                       || !bsi_end_p (bsi))
2097                     {
2098                       bsi_commit_one_edge_insert (e, NULL);
2099                       continue;
2100                     }
2101                 }
2102             }
2103           single_edge = e;
2104           count++;
2105         }
2106     }
2107
2108   /* If there aren't at least 2 edges, no sharing will happen.  */
2109   if (count < 2)
2110     {
2111       if (single_edge)
2112         bsi_commit_one_edge_insert (single_edge, NULL);
2113       return;
2114     }
2115
2116   /* Ensure that we have empty worklists.  */
2117 #ifdef ENABLE_CHECKING
2118   gcc_assert (VEC_length (edge, edge_leader) == 0);
2119   gcc_assert (VEC_length (tree, stmt_list) == 0);
2120   gcc_assert (bitmap_empty_p (leader_has_match));
2121 #endif
2122
2123   /* Find the "leader" block for each set of unique stmt lists.  Preference is
2124      given to FALLTHRU blocks since they would need a GOTO to arrive at another
2125      block.  The leader edge destination is the block which all the other edges
2126      with the same stmt list will be redirected to.  */
2127   have_opportunity = false;
2128   FOR_EACH_EDGE (e, ei, bb->preds)
2129     {
2130       if (PENDING_STMT (e))
2131         {
2132           bool found = false;
2133
2134           /* Look for the same stmt list in edge leaders list.  */
2135           for (x = 0; VEC_iterate (edge, edge_leader, x, leader); x++)
2136             {
2137               if (identical_stmt_lists_p (leader, e))
2138                 {
2139                   /* Give this edge the same stmt list pointer.  */
2140                   PENDING_STMT (e) = NULL;
2141                   e->aux = leader;
2142                   bitmap_set_bit (leader_has_match, x);
2143                   have_opportunity = found = true;
2144                   break;
2145                 }
2146             }
2147
2148           /* If no similar stmt list, add this edge to the leader list.  */
2149           if (!found)
2150             {
2151               VEC_safe_push (edge, heap, edge_leader, e);
2152               VEC_safe_push (tree, heap, stmt_list, PENDING_STMT (e));
2153             }
2154         }
2155      }
2156
2157   /* If there are no similar lists, just issue the stmts.  */
2158   if (!have_opportunity)
2159     {
2160       for (x = 0; VEC_iterate (edge, edge_leader, x, leader); x++)
2161         bsi_commit_one_edge_insert (leader, NULL);
2162       VEC_truncate (edge, edge_leader, 0);
2163       VEC_truncate (tree, stmt_list, 0);
2164       bitmap_clear (leader_has_match);
2165       return;
2166     }
2167
2168
2169   if (debug_file)
2170     fprintf (debug_file, "\nOpportunities in BB %d for stmt/block reduction:\n",
2171              bb->index);
2172
2173   
2174   /* For each common list, create a forwarding block and issue the stmt's
2175      in that block.  */
2176   for (x = 0; VEC_iterate (edge, edge_leader, x, leader); x++)
2177     if (bitmap_bit_p (leader_has_match, x))
2178       {
2179         edge new_edge;
2180         block_stmt_iterator bsi;
2181         tree curr_stmt_list;
2182
2183         leader_match = leader;
2184
2185         /* The tree_* cfg manipulation routines use the PENDING_EDGE field
2186            for various PHI manipulations, so it gets cleared whhen calls are 
2187            made to make_forwarder_block(). So make sure the edge is clear, 
2188            and use the saved stmt list.  */
2189         PENDING_STMT (leader) = NULL;
2190         leader->aux = leader;
2191         curr_stmt_list = VEC_index (tree, stmt_list, x);
2192
2193         new_edge = make_forwarder_block (leader->dest, same_stmt_list_p, 
2194                                          NULL);
2195         bb = new_edge->dest;
2196         if (debug_file)
2197           {
2198             fprintf (debug_file, "Splitting BB %d for Common stmt list.  ", 
2199                      leader->dest->index);
2200             fprintf (debug_file, "Original block is now BB%d.\n", bb->index);
2201             print_generic_stmt (debug_file, curr_stmt_list, TDF_VOPS);
2202           }
2203
2204         FOR_EACH_EDGE (e, ei, new_edge->src->preds)
2205           {
2206             e->aux = NULL;
2207             if (debug_file)
2208               fprintf (debug_file, "  Edge (%d->%d) lands here.\n", 
2209                        e->src->index, e->dest->index);
2210           }
2211
2212         bsi = bsi_last (leader->dest);
2213         bsi_insert_after (&bsi, curr_stmt_list, BSI_NEW_STMT);
2214
2215         leader_match = NULL;
2216         /* We should never get a new block now.  */
2217       }
2218     else
2219       {
2220         PENDING_STMT (leader) = VEC_index (tree, stmt_list, x);
2221         bsi_commit_one_edge_insert (leader, NULL);
2222       }
2223
2224    
2225   /* Clear the working data structures.  */
2226   VEC_truncate (edge, edge_leader, 0);
2227   VEC_truncate (tree, stmt_list, 0);
2228   bitmap_clear (leader_has_match);
2229 }
2230
2231
2232 /* This function will analyze the insertions which were performed on edges,
2233    and decide whether they should be left on that edge, or whether it is more
2234    efficient to emit some subset of them in a single block.  All stmts are
2235    inserted somewhere, and if non-NULL, debug information is printed via 
2236    DUMP_FILE.  */
2237
2238 static void
2239 perform_edge_inserts (FILE *dump_file)
2240 {
2241   basic_block bb;
2242
2243   if (dump_file)
2244     fprintf(dump_file, "Analyzing Edge Insertions.\n");
2245
2246   /* analyze_edges_for_bb calls make_forwarder_block, which tries to
2247      incrementally update the dominator information.  Since we don't
2248      need dominator information after this pass, go ahead and free the
2249      dominator information.  */
2250   free_dominance_info (CDI_DOMINATORS);
2251   free_dominance_info (CDI_POST_DOMINATORS);
2252
2253   /* Allocate data structures used in analyze_edges_for_bb.   */
2254   init_analyze_edges_for_bb ();
2255
2256   FOR_EACH_BB (bb)
2257     analyze_edges_for_bb (bb, dump_file);
2258
2259   analyze_edges_for_bb (EXIT_BLOCK_PTR, dump_file);
2260
2261   /* Free data structures used in analyze_edges_for_bb.   */
2262   fini_analyze_edges_for_bb ();
2263
2264 #ifdef ENABLE_CHECKING
2265   {
2266     edge_iterator ei;
2267     edge e;
2268     FOR_EACH_BB (bb)
2269       {
2270         FOR_EACH_EDGE (e, ei, bb->preds)
2271           {
2272             if (PENDING_STMT (e))
2273               error (" Pending stmts not issued on PRED edge (%d, %d)\n", 
2274                      e->src->index, e->dest->index);
2275           }
2276         FOR_EACH_EDGE (e, ei, bb->succs)
2277           {
2278             if (PENDING_STMT (e))
2279               error (" Pending stmts not issued on SUCC edge (%d, %d)\n", 
2280                      e->src->index, e->dest->index);
2281           }
2282       }
2283     FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2284       {
2285         if (PENDING_STMT (e))
2286           error (" Pending stmts not issued on ENTRY edge (%d, %d)\n", 
2287                  e->src->index, e->dest->index);
2288       }
2289     FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2290       {
2291         if (PENDING_STMT (e))
2292           error (" Pending stmts not issued on EXIT edge (%d, %d)\n", 
2293                  e->src->index, e->dest->index);
2294       }
2295   }
2296 #endif
2297 }
2298
2299
2300 /* Remove the variables specified in MAP from SSA form.  Any debug information
2301    is sent to DUMP.  FLAGS indicate what options should be used.  */
2302
2303 static void
2304 remove_ssa_form (FILE *dump, var_map map, int flags)
2305 {
2306   tree_live_info_p liveinfo;
2307   basic_block bb;
2308   tree phi, next;
2309   FILE *save;
2310   tree *values = NULL;
2311
2312   save = dump_file;
2313   dump_file = dump;
2314
2315   /* If we are not combining temps, don't calculate live ranges for variables
2316      with only one SSA version.  */
2317   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
2318     compact_var_map (map, VARMAP_NO_SINGLE_DEFS);
2319   else
2320     compact_var_map (map, VARMAP_NORMAL);
2321
2322   if (dump_file && (dump_flags & TDF_DETAILS))
2323     dump_var_map (dump_file, map);
2324
2325   liveinfo = coalesce_ssa_name (map, flags);
2326
2327   /* Make sure even single occurrence variables are in the list now.  */
2328   if ((flags & SSANORM_COMBINE_TEMPS) == 0)
2329     compact_var_map (map, VARMAP_NORMAL);
2330
2331   if (dump_file && (dump_flags & TDF_DETAILS))
2332     {
2333       fprintf (dump_file, "After Coalescing:\n");
2334       dump_var_map (dump_file, map);
2335     }
2336
2337   if (flags & SSANORM_PERFORM_TER)
2338     {
2339       values = find_replaceable_exprs (map);
2340       if (values && dump_file && (dump_flags & TDF_DETAILS))
2341         dump_replaceable_exprs (dump_file, values);
2342     }
2343
2344   /* Assign real variables to the partitions now.  */
2345   assign_vars (map);
2346
2347   if (dump_file && (dump_flags & TDF_DETAILS))
2348     {
2349       fprintf (dump_file, "After Root variable replacement:\n");
2350       dump_var_map (dump_file, map);
2351     }
2352
2353   if ((flags & SSANORM_COMBINE_TEMPS) && liveinfo)
2354     {
2355       coalesce_vars (map, liveinfo);
2356       if (dump_file && (dump_flags & TDF_DETAILS))
2357         {
2358           fprintf (dump_file, "After variable memory coalescing:\n");
2359           dump_var_map (dump_file, map);
2360         }
2361     }
2362   
2363   if (liveinfo)
2364     delete_tree_live_info (liveinfo);
2365
2366   rewrite_trees (map, values);
2367
2368   if (values)
2369     free (values);
2370
2371   /* Remove phi nodes which have been translated back to real variables.  */
2372   FOR_EACH_BB (bb)
2373     {
2374       for (phi = phi_nodes (bb); phi; phi = next)
2375         {
2376           next = PHI_CHAIN (phi);
2377           remove_phi_node (phi, NULL_TREE);
2378         }
2379     }
2380
2381   /* we no longer maintain the SSA operand cache at this point.  */
2382   fini_ssa_operands ();
2383
2384   /* If any copies were inserted on edges, analyze and insert them now.  */
2385   perform_edge_inserts (dump_file);
2386
2387   dump_file = save;
2388 }
2389
2390 /* Search every PHI node for arguments associated with backedges which
2391    we can trivially determine will need a copy (the argument is either
2392    not an SSA_NAME or the argument has a different underlying variable
2393    than the PHI result).
2394
2395    Insert a copy from the PHI argument to a new destination at the
2396    end of the block with the backedge to the top of the loop.  Update
2397    the PHI argument to reference this new destination.  */
2398
2399 static void
2400 insert_backedge_copies (void)
2401 {
2402   basic_block bb;
2403
2404   FOR_EACH_BB (bb)
2405     {
2406       tree phi;
2407
2408       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2409         {
2410           tree result = PHI_RESULT (phi);
2411           tree result_var;
2412           int i;
2413
2414           if (!is_gimple_reg (result))
2415             continue;
2416
2417           result_var = SSA_NAME_VAR (result);
2418           for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2419             {
2420               tree arg = PHI_ARG_DEF (phi, i);
2421               edge e = PHI_ARG_EDGE (phi, i);
2422
2423               /* If the argument is not an SSA_NAME, then we will
2424                  need a constant initialization.  If the argument is
2425                  an SSA_NAME with a different underlying variable and
2426                  we are not combining temporaries, then we will
2427                  need a copy statement.  */
2428               if ((e->flags & EDGE_DFS_BACK)
2429                   && (TREE_CODE (arg) != SSA_NAME
2430                       || (!flag_tree_combine_temps
2431                           && SSA_NAME_VAR (arg) != result_var)))
2432                 {
2433                   tree stmt, name, last = NULL;
2434                   block_stmt_iterator bsi;
2435
2436                   bsi = bsi_last (PHI_ARG_EDGE (phi, i)->src);
2437                   if (!bsi_end_p (bsi))
2438                     last = bsi_stmt (bsi);
2439
2440                   /* In theory the only way we ought to get back to the
2441                      start of a loop should be with a COND_EXPR or GOTO_EXPR.
2442                      However, better safe than sorry. 
2443
2444                      If the block ends with a control statement or
2445                      something that might throw, then we have to
2446                      insert this assignment before the last
2447                      statement.  Else insert it after the last statement.  */
2448                   if (last && stmt_ends_bb_p (last))
2449                     {
2450                       /* If the last statement in the block is the definition
2451                          site of the PHI argument, then we can't insert
2452                          anything after it.  */
2453                       if (TREE_CODE (arg) == SSA_NAME
2454                           && SSA_NAME_DEF_STMT (arg) == last)
2455                         continue;
2456                     }
2457
2458                   /* Create a new instance of the underlying
2459                      variable of the PHI result.  */
2460                   stmt = build (MODIFY_EXPR, TREE_TYPE (result_var),
2461                                 NULL, PHI_ARG_DEF (phi, i));
2462                   name = make_ssa_name (result_var, stmt);
2463                   TREE_OPERAND (stmt, 0) = name;
2464
2465                   /* Insert the new statement into the block and update
2466                      the PHI node.  */
2467                   if (last && stmt_ends_bb_p (last))
2468                     bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
2469                   else
2470                     bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2471                   SET_PHI_ARG_DEF (phi, i, name);
2472                 }
2473             }
2474         }
2475     }
2476 }
2477
2478 /* Take the current function out of SSA form, as described in
2479    R. Morgan, ``Building an Optimizing Compiler'',
2480    Butterworth-Heinemann, Boston, MA, 1998. pp 176-186.  */
2481
2482 static void
2483 rewrite_out_of_ssa (void)
2484 {
2485   var_map map;
2486   int var_flags = 0;
2487   int ssa_flags = 0;
2488
2489   /* If elimination of a PHI requires inserting a copy on a backedge,
2490      then we will have to split the backedge which has numerous
2491      undesirable performance effects.
2492
2493      A significant number of such cases can be handled here by inserting
2494      copies into the loop itself.  */
2495   insert_backedge_copies ();
2496
2497   if (!flag_tree_live_range_split)
2498     ssa_flags |= SSANORM_COALESCE_PARTITIONS;
2499     
2500   eliminate_virtual_phis ();
2501
2502   if (dump_file && (dump_flags & TDF_DETAILS))
2503     dump_tree_cfg (dump_file, dump_flags & ~TDF_DETAILS);
2504
2505   /* We cannot allow unssa to un-gimplify trees before we instrument them.  */
2506   if (flag_tree_ter && !flag_mudflap)
2507     var_flags = SSA_VAR_MAP_REF_COUNT;
2508
2509   map = create_ssa_var_map (var_flags);
2510
2511   if (flag_tree_combine_temps)
2512     ssa_flags |= SSANORM_COMBINE_TEMPS;
2513   if (flag_tree_ter && !flag_mudflap)
2514     ssa_flags |= SSANORM_PERFORM_TER;
2515
2516   remove_ssa_form (dump_file, map, ssa_flags);
2517
2518   if (dump_file && (dump_flags & TDF_DETAILS))
2519     dump_tree_cfg (dump_file, dump_flags & ~TDF_DETAILS);
2520
2521   /* Flush out flow graph and SSA data.  */
2522   delete_var_map (map);
2523
2524   /* Mark arrays indexed with non-constant indices with TREE_ADDRESSABLE.  */
2525   discover_nonconstant_array_refs ();
2526
2527   in_ssa_p = false;
2528 }
2529
2530
2531 /* Define the parameters of the out of SSA pass.  */
2532
2533 struct tree_opt_pass pass_del_ssa = 
2534 {
2535   "optimized",                          /* name */
2536   NULL,                                 /* gate */
2537   rewrite_out_of_ssa,                   /* execute */
2538   NULL,                                 /* sub */
2539   NULL,                                 /* next */
2540   0,                                    /* static_pass_number */
2541   TV_TREE_SSA_TO_NORMAL,                /* tv_id */
2542   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2543   0,                                    /* properties_provided */
2544   /* ??? If TER is enabled, we also kill gimple.  */
2545   PROP_ssa,                             /* properties_destroyed */
2546   TODO_verify_ssa | TODO_verify_flow
2547     | TODO_verify_stmts,                /* todo_flags_start */
2548   TODO_dump_func | TODO_ggc_collect,    /* todo_flags_finish */
2549   0                                     /* letter */
2550 };