OSDN Git Service

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