ssa.c (ssa_uses): Remove definition.
[platform/upstream/gcc.git] / gcc / ssa.c
1 /* Static Single Assignment conversion routines for the GNU compiler.
2    Copyright (C) 2000 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 GNU CC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.  */
20
21 /* References:
22
23    Building an Optimizing Compiler
24    Robert Morgan
25    Butterworth-Heinemann, 1998
26
27    Static Single Assignment Construction
28    Preston Briggs, Tim Harvey, Taylor Simpson
29    Technical Report, Rice University, 1995
30    ftp://ftp.cs.rice.edu/public/preston/optimizer/SSA.ps.gz.  */
31
32 #include "config.h"
33 #include "system.h"
34
35 #include "rtl.h"
36 #include "expr.h"
37 #include "varray.h"
38 #include "partition.h"
39 #include "sbitmap.h"
40 #include "hashtab.h"
41 #include "regs.h"
42 #include "hard-reg-set.h"
43 #include "flags.h"
44 #include "function.h"
45 #include "real.h"
46 #include "insn-config.h"
47 #include "recog.h"
48 #include "basic-block.h"
49 #include "output.h"
50 #include "ssa.h"
51
52 /* TODO: 
53
54    Handle subregs better, maybe.  For now, if a reg that's set in a
55    subreg expression is duplicated going into SSA form, an extra copy
56    is inserted first that copies the entire reg into the duplicate, so
57    that the other bits are preserved.  This isn't strictly SSA, since
58    at least part of the reg is assigned in more than one place (though
59    they are adjacent).
60
61    ??? What to do about strict_low_part.  Probably I'll have to split
62    them out of their current instructions first thing.
63
64    Actually the best solution may be to have a kind of "mid-level rtl"
65    in which the RTL encodes exactly what we want, without exposing a
66    lot of niggling processor details.  At some later point we lower
67    the representation, calling back into optabs to finish any necessary
68    expansion.  */
69
70 /* All pseudo-registers and select hard registers are converted to SSA
71    form.  When converting out of SSA, these select hard registers are
72    guaranteed to be mapped to their original register number.  Each
73    machine's .h file should define CONVERT_HARD_REGISTER_TO_SSA_P
74    indicating which hard registers should be converted.
75
76    When converting out of SSA, temporaries for all registers are
77    partitioned.  The partition is checked to ensure that all uses of
78    the same hard register in the same machine mode are in the same
79    class.  */
80
81 /* If conservative_reg_partition is non-zero, use a conservative
82    register partitioning algorithm (which leaves more regs after
83    emerging from SSA) instead of the coalescing one.  This is being
84    left in for a limited time only, as a debugging tool until the
85    coalescing algorithm is validated.  */
86
87 static int conservative_reg_partition;
88
89 /* This flag is set when the CFG is in SSA form.  */
90 int in_ssa_form = 0;
91
92 /* Element I is the single instruction that sets register I.  */
93 varray_type ssa_definition;
94
95 /* Element I-PSEUDO is the normal register that originated the ssa
96    register in question.  */
97 varray_type ssa_rename_from;
98
99 /* Element I is the normal register that originated the ssa
100    register in question.
101
102    A hash table stores the (register, rtl) pairs.  These are each
103    xmalloc'ed and deleted when the hash table is destroyed.  */
104 htab_t ssa_rename_from_ht;
105
106 /* The running target ssa register for a given pseudo register.
107    (Pseudo registers appear in only one mode.)  */
108 static rtx *ssa_rename_to_pseudo;
109 /* Similar, but for hard registers.  A hard register can appear in
110    many modes, so we store an equivalent pseudo for each of the
111    modes.  */
112 static rtx ssa_rename_to_hard[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];
113
114 /* ssa_rename_from maps pseudo registers to the original corresponding
115    RTL.  It is implemented as using a hash table.  */
116
117 typedef struct {
118   unsigned int reg;
119   rtx original;
120 } ssa_rename_from_pair;
121
122 struct ssa_rename_from_hash_table_data {
123   sbitmap canonical_elements;
124   partition reg_partition;
125 };
126
127 static void ssa_rename_from_initialize
128   PARAMS ((void));
129 static rtx ssa_rename_from_lookup
130   PARAMS ((int reg));
131 static unsigned int original_register
132   PARAMS ((unsigned int regno));
133 static void ssa_rename_from_insert
134   PARAMS ((unsigned int reg, rtx r));
135 static void ssa_rename_from_free
136   PARAMS ((void));
137 typedef int (*srf_trav) PARAMS ((int regno, rtx r, sbitmap canonical_elements, partition reg_partition));
138 static void ssa_rename_from_traverse
139   PARAMS ((htab_trav callback_function, sbitmap canonical_elements, partition reg_partition));
140 /*static Avoid warnign message.  */ void ssa_rename_from_print
141   PARAMS ((void));
142 static int ssa_rename_from_print_1
143   PARAMS ((void **slot, void *data));
144 static hashval_t ssa_rename_from_hash_function
145   PARAMS ((const void * srfp));
146 static int ssa_rename_from_equal
147   PARAMS ((const void *srfp1, const void *srfp2));
148 static void ssa_rename_from_delete
149   PARAMS ((void *srfp));
150
151 static rtx ssa_rename_to_lookup
152   PARAMS ((rtx reg));
153 static void ssa_rename_to_insert
154   PARAMS ((rtx reg, rtx r));
155
156 /* The number of registers that were live on entry to the SSA routines.  */
157 static unsigned int ssa_max_reg_num;
158
159 /* Local function prototypes.  */
160
161 struct rename_context;
162
163 static inline rtx * phi_alternative
164   PARAMS ((rtx, int));
165 static rtx first_insn_after_basic_block_note
166   PARAMS ((basic_block));
167 static int remove_phi_alternative
168   PARAMS ((rtx, int));
169 static void compute_dominance_frontiers_1
170   PARAMS ((sbitmap *frontiers, int *idom, int bb, sbitmap done));
171 static void compute_dominance_frontiers
172   PARAMS ((sbitmap *frontiers, int *idom));
173 static void find_evaluations_1
174   PARAMS ((rtx dest, rtx set, void *data));
175 static void find_evaluations
176   PARAMS ((sbitmap *evals, int nregs));
177 static void compute_iterated_dominance_frontiers
178   PARAMS ((sbitmap *idfs, sbitmap *frontiers, sbitmap *evals, int nregs));
179 static void insert_phi_node
180   PARAMS ((int regno, int b));
181 static void insert_phi_nodes
182   PARAMS ((sbitmap *idfs, sbitmap *evals, int nregs));
183 static void create_delayed_rename 
184   PARAMS ((struct rename_context *, rtx *));
185 static void apply_delayed_renames 
186   PARAMS ((struct rename_context *));
187 static int rename_insn_1 
188   PARAMS ((rtx *ptr, void *data));
189 static void rename_block 
190   PARAMS ((int b, int *idom));
191 static void rename_registers 
192   PARAMS ((int nregs, int *idom));
193
194 static inline int ephi_add_node
195   PARAMS ((rtx reg, rtx *nodes, int *n_nodes));
196 static int * ephi_forward
197   PARAMS ((int t, sbitmap visited, sbitmap *succ, int *tstack));
198 static void ephi_backward
199   PARAMS ((int t, sbitmap visited, sbitmap *pred, rtx *nodes));
200 static void ephi_create
201   PARAMS ((int t, sbitmap visited, sbitmap *pred, sbitmap *succ, rtx *nodes));
202 static void eliminate_phi
203   PARAMS ((edge e, partition reg_partition));
204 static int make_regs_equivalent_over_bad_edges 
205   PARAMS ((int bb, partition reg_partition));
206
207 /* These are used only in the conservative register partitioning
208    algorithms.  */
209 static int make_equivalent_phi_alternatives_equivalent 
210   PARAMS ((int bb, partition reg_partition));
211 static partition compute_conservative_reg_partition 
212   PARAMS ((void));
213 static int record_canonical_element_1
214   PARAMS ((void **srfp, void *data));
215 static int check_hard_regs_in_partition
216   PARAMS ((partition reg_partition));
217 static int rename_equivalent_regs_in_insn 
218   PARAMS ((rtx *ptr, void *data));
219
220 /* These are used in the register coalescing algorithm.  */
221 static int coalesce_if_unconflicting
222   PARAMS ((partition p, conflict_graph conflicts, int reg1, int reg2));
223 static int coalesce_regs_in_copies
224   PARAMS ((basic_block bb, partition p, conflict_graph conflicts));
225 static int coalesce_reg_in_phi
226   PARAMS ((rtx, int dest_regno, int src_regno, void *data));
227 static int coalesce_regs_in_successor_phi_nodes
228   PARAMS ((basic_block bb, partition p, conflict_graph conflicts));
229 static partition compute_coalesced_reg_partition
230   PARAMS ((void));
231 static int mark_reg_in_phi 
232   PARAMS ((rtx *ptr, void *data));
233 static void mark_phi_and_copy_regs
234   PARAMS ((regset phi_set));
235
236 static int rename_equivalent_regs_in_insn 
237   PARAMS ((rtx *ptr, void *data));
238 static void rename_equivalent_regs 
239   PARAMS ((partition reg_partition));
240
241 /* Deal with hard registers.  */
242 static int conflicting_hard_regs_p
243   PARAMS ((int reg1, int reg2));
244
245 /* ssa_rename_to maps registers and machine modes to SSA pseudo registers.  */
246
247 /* Find the register associated with REG in the indicated mode.  */
248
249 static rtx
250 ssa_rename_to_lookup (reg)
251      rtx reg;
252 {
253   if (!HARD_REGISTER_P (reg))
254     return ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER];
255   else
256     return ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)];
257 }
258
259 /* Store a new value mapping REG to R in ssa_rename_to.  */
260
261 static void
262 ssa_rename_to_insert(reg, r)
263      rtx reg;
264      rtx r;
265 {
266   if (!HARD_REGISTER_P (reg))
267     ssa_rename_to_pseudo[REGNO (reg) - FIRST_PSEUDO_REGISTER] = r;
268   else
269     ssa_rename_to_hard[REGNO (reg)][GET_MODE (reg)] = r;
270 }
271
272 /* Prepare ssa_rename_from for use.  */
273
274 static void
275 ssa_rename_from_initialize ()
276 {
277   /* We use an arbitrary initial hash table size of 64.  */
278   ssa_rename_from_ht = htab_create (64,
279                                     &ssa_rename_from_hash_function,
280                                     &ssa_rename_from_equal,
281                                     &ssa_rename_from_delete);
282 }
283
284 /* Find the REG entry in ssa_rename_from.  Return NULL_RTX if no entry is
285    found.  */
286
287 static rtx
288 ssa_rename_from_lookup (reg)
289      int reg;
290 {
291   ssa_rename_from_pair srfp;
292   ssa_rename_from_pair *answer;
293   srfp.reg = reg;
294   srfp.original = NULL_RTX;
295   answer = (ssa_rename_from_pair *)
296     htab_find_with_hash (ssa_rename_from_ht, (void *) &srfp, reg);
297   return (answer == 0 ? NULL_RTX : answer->original);
298 }
299
300 /* Find the number of the original register specified by REGNO.  If
301    the register is a pseudo, return the original register's number.
302    Otherwise, return this register number REGNO.  */
303
304 static unsigned int
305 original_register (regno)
306      unsigned int regno;
307 {
308   rtx original_rtx = ssa_rename_from_lookup (regno);
309   return original_rtx != NULL_RTX ? REGNO (original_rtx) : regno;
310 }
311
312 /* Add mapping from R to REG to ssa_rename_from even if already present.  */
313
314 static void
315 ssa_rename_from_insert (reg, r)
316      unsigned int reg;
317      rtx r;
318 {
319   void **slot;
320   ssa_rename_from_pair *srfp = xmalloc (sizeof (ssa_rename_from_pair));
321   srfp->reg = reg;
322   srfp->original = r;
323   slot = htab_find_slot_with_hash (ssa_rename_from_ht, (const void *) srfp,
324                                    reg, INSERT);
325   if (*slot != 0)
326     free ((void *) *slot);
327   *slot = srfp;
328 }
329
330 /* Apply the CALLBACK_FUNCTION to each element in ssa_rename_from.
331    CANONICAL_ELEMENTS and REG_PARTITION pass data needed by the only
332    current use of this function.  */
333
334 static void
335 ssa_rename_from_traverse (callback_function,
336                           canonical_elements, reg_partition)
337      htab_trav callback_function;
338      sbitmap canonical_elements;
339      partition reg_partition;
340 {
341   struct ssa_rename_from_hash_table_data srfhd;
342   srfhd.canonical_elements = canonical_elements;
343   srfhd.reg_partition = reg_partition;
344   htab_traverse (ssa_rename_from_ht, callback_function, (void *) &srfhd);
345 }
346
347 /* Destroy ssa_rename_from.  */
348
349 static void
350 ssa_rename_from_free ()
351 {
352   htab_delete (ssa_rename_from_ht);
353 }
354
355 /* Print the contents of ssa_rename_from.  */
356
357 /* static  Avoid erroneous error message.  */
358 void
359 ssa_rename_from_print ()
360 {
361   printf ("ssa_rename_from's hash table contents:\n");
362   htab_traverse (ssa_rename_from_ht, &ssa_rename_from_print_1, NULL);
363 }
364
365 /* Print the contents of the hash table entry SLOT, passing the unused
366    sttribute DATA.  Used as a callback function with htab_traverse ().  */
367
368 static int
369 ssa_rename_from_print_1 (slot, data)
370      void **slot;
371      void *data ATTRIBUTE_UNUSED;
372 {
373   ssa_rename_from_pair * p = *slot;
374   printf ("ssa_rename_from maps pseudo %i to original %i.\n",
375           p->reg, REGNO (p->original));
376   return 1;
377 }
378
379 /* Given a hash entry SRFP, yield a hash value.  */
380
381 static hashval_t
382 ssa_rename_from_hash_function (srfp)
383      const void *srfp;
384 {
385   return ((const ssa_rename_from_pair *) srfp)->reg;
386 }
387
388 /* Test whether two hash table entries SRFP1 and SRFP2 are equal.  */
389
390 static int
391 ssa_rename_from_equal (srfp1, srfp2)
392      const void *srfp1;
393      const void *srfp2;
394 {
395   return ssa_rename_from_hash_function (srfp1) ==
396     ssa_rename_from_hash_function (srfp2);
397 }
398
399 /* Delete the hash table entry SRFP.  */
400
401 static void
402 ssa_rename_from_delete (srfp)
403      void *srfp;
404 {
405   free (srfp);
406 }
407
408 /* Given the SET of a PHI node, return the address of the alternative
409    for predecessor block C.  */
410
411 static inline rtx *
412 phi_alternative (set, c)
413      rtx set;
414      int c;
415 {
416   rtvec phi_vec = XVEC (SET_SRC (set), 0);
417   int v;
418
419   for (v = GET_NUM_ELEM (phi_vec) - 2; v >= 0; v -= 2)
420     if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
421       return &RTVEC_ELT (phi_vec, v);
422
423   return NULL;
424 }
425
426 /* Given the SET of a phi node, remove the alternative for predecessor
427    block C.  Return non-zero on success, or zero if no alternative is
428    found for C.  */
429
430 static int
431 remove_phi_alternative (set, c)
432      rtx set;
433      int c;
434 {
435   rtvec phi_vec = XVEC (SET_SRC (set), 0);
436   int num_elem = GET_NUM_ELEM (phi_vec);
437   int v;
438
439   for (v = num_elem - 2; v >= 0; v -= 2)
440     if (INTVAL (RTVEC_ELT (phi_vec, v + 1)) == c)
441       {
442         if (v < num_elem - 2)
443           {
444             RTVEC_ELT (phi_vec, v) = RTVEC_ELT (phi_vec, num_elem - 2);
445             RTVEC_ELT (phi_vec, v + 1) = RTVEC_ELT (phi_vec, num_elem - 1);
446           }
447         PUT_NUM_ELEM (phi_vec, num_elem - 2);
448         return 1;
449       }
450
451   return 0;
452 }
453
454 /* For all registers, find all blocks in which they are set.
455
456    This is the transform of what would be local kill information that
457    we ought to be getting from flow.  */
458
459 static sbitmap *fe_evals;
460 static int fe_current_bb;
461
462 static void
463 find_evaluations_1 (dest, set, data)
464      rtx dest;
465      rtx set ATTRIBUTE_UNUSED;
466      void *data ATTRIBUTE_UNUSED;
467 {
468   if (GET_CODE (dest) == REG
469       && CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
470     SET_BIT (fe_evals[REGNO (dest)], fe_current_bb);
471 }
472
473 static void
474 find_evaluations (evals, nregs)
475      sbitmap *evals;
476      int nregs;
477 {
478   int bb;
479
480   sbitmap_vector_zero (evals, nregs);
481   fe_evals = evals;
482
483   for (bb = n_basic_blocks; --bb >= 0; )
484     {
485       rtx p, last;
486
487       fe_current_bb = bb;
488       p = BLOCK_HEAD (bb);
489       last = BLOCK_END (bb);
490       while (1)
491         {
492           if (INSN_P (p))
493             note_stores (PATTERN (p), find_evaluations_1, NULL);
494
495           if (p == last)
496             break;
497           p = NEXT_INSN (p);
498         }
499     }
500 }
501
502 /* Computing the Dominance Frontier:
503   
504    As decribed in Morgan, section 3.5, this may be done simply by 
505    walking the dominator tree bottom-up, computing the frontier for
506    the children before the parent.  When considering a block B,
507    there are two cases:
508
509    (1) A flow graph edge leaving B that does not lead to a child
510    of B in the dominator tree must be a block that is either equal
511    to B or not dominated by B.  Such blocks belong in the frontier
512    of B.
513
514    (2) Consider a block X in the frontier of one of the children C
515    of B.  If X is not equal to B and is not dominated by B, it
516    is in the frontier of B.
517 */
518
519 static void
520 compute_dominance_frontiers_1 (frontiers, idom, bb, done)
521      sbitmap *frontiers;
522      int *idom;
523      int bb;
524      sbitmap done;
525 {
526   basic_block b = BASIC_BLOCK (bb);
527   edge e;
528   int c;
529
530   SET_BIT (done, bb);
531   sbitmap_zero (frontiers[bb]);
532
533   /* Do the frontier of the children first.  Not all children in the
534      dominator tree (blocks dominated by this one) are children in the
535      CFG, so check all blocks.  */
536   for (c = 0; c < n_basic_blocks; ++c)
537     if (idom[c] == bb && ! TEST_BIT (done, c))
538       compute_dominance_frontiers_1 (frontiers, idom, c, done);
539
540   /* Find blocks conforming to rule (1) above.  */
541   for (e = b->succ; e; e = e->succ_next)
542     {
543       if (e->dest == EXIT_BLOCK_PTR)
544         continue;
545       if (idom[e->dest->index] != bb)
546         SET_BIT (frontiers[bb], e->dest->index);
547     }
548
549   /* Find blocks conforming to rule (2).  */
550   for (c = 0; c < n_basic_blocks; ++c)
551     if (idom[c] == bb)
552       {
553         int x;
554         EXECUTE_IF_SET_IN_SBITMAP (frontiers[c], 0, x,
555           {
556             if (idom[x] != bb)
557               SET_BIT (frontiers[bb], x);
558           });
559       }
560 }
561
562 static void
563 compute_dominance_frontiers (frontiers, idom)
564      sbitmap *frontiers;
565      int *idom;
566 {
567   sbitmap done = sbitmap_alloc (n_basic_blocks);
568   sbitmap_zero (done);
569
570   compute_dominance_frontiers_1 (frontiers, idom, 0, done);
571
572   sbitmap_free (done);
573 }
574
575 /* Computing the Iterated Dominance Frontier:
576
577    This is the set of merge points for a given register.
578
579    This is not particularly intuitive.  See section 7.1 of Morgan, in
580    particular figures 7.3 and 7.4 and the immediately surrounding text.
581 */
582
583 static void
584 compute_iterated_dominance_frontiers (idfs, frontiers, evals, nregs)
585      sbitmap *idfs;
586      sbitmap *frontiers;
587      sbitmap *evals;
588      int nregs;
589 {
590   sbitmap worklist;
591   int reg, passes = 0;
592
593   worklist = sbitmap_alloc (n_basic_blocks);
594
595   for (reg = 0; reg < nregs; ++reg)
596     {
597       sbitmap idf = idfs[reg];
598       int b, changed;
599
600       /* Start the iterative process by considering those blocks that
601          evaluate REG.  We'll add their dominance frontiers to the
602          IDF, and then consider the blocks we just added.  */
603       sbitmap_copy (worklist, evals[reg]);
604
605       /* Morgan's algorithm is incorrect here.  Blocks that evaluate
606          REG aren't necessarily in REG's IDF.  Start with an empty IDF.  */
607       sbitmap_zero (idf);
608
609       /* Iterate until the worklist is empty.  */
610       do
611         {
612           changed = 0;
613           passes++;
614           EXECUTE_IF_SET_IN_SBITMAP (worklist, 0, b,
615             {
616               RESET_BIT (worklist, b);
617               /* For each block on the worklist, add to the IDF all
618                  blocks on its dominance frontier that aren't already
619                  on the IDF.  Every block that's added is also added
620                  to the worklist.  */
621               sbitmap_union_of_diff (worklist, worklist, frontiers[b], idf);
622               sbitmap_a_or_b (idf, idf, frontiers[b]);
623               changed = 1;
624             });
625         }
626       while (changed);
627     }
628
629   sbitmap_free (worklist);
630
631   if (rtl_dump_file)
632     {
633       fprintf(rtl_dump_file,
634               "Iterated dominance frontier: %d passes on %d regs.\n",
635               passes, nregs);
636     }
637 }
638
639 /* Return the INSN immediately following the NOTE_INSN_BASIC_BLOCK
640    note associated with the BLOCK.  */
641
642 static rtx
643 first_insn_after_basic_block_note (block)
644      basic_block block;
645 {
646   rtx insn;
647
648   /* Get the first instruction in the block.  */
649   insn = block->head;
650
651   if (insn == NULL_RTX)
652     return NULL_RTX;
653   if (GET_CODE (insn) == CODE_LABEL)
654     insn = NEXT_INSN (insn);
655   if (!NOTE_INSN_BASIC_BLOCK_P (insn))
656     abort ();
657
658   return NEXT_INSN (insn);
659 }
660
661 /* Insert the phi nodes.  */
662
663 static void
664 insert_phi_node (regno, bb)
665      int regno, bb;
666 {
667   basic_block b = BASIC_BLOCK (bb);
668   edge e;
669   int npred, i;
670   rtvec vec;
671   rtx phi, reg;
672   rtx insn;
673   int end_p;
674
675   /* Find out how many predecessors there are.  */
676   for (e = b->pred, npred = 0; e; e = e->pred_next)
677     if (e->src != ENTRY_BLOCK_PTR)
678       npred++;
679
680   /* If this block has no "interesting" preds, then there is nothing to
681      do.  Consider a block that only has the entry block as a pred.  */
682   if (npred == 0)
683     return;
684
685   /* This is the register to which the phi function will be assigned.  */
686   reg = regno_reg_rtx[regno];
687
688   /* Construct the arguments to the PHI node.  The use of pc_rtx is just
689      a placeholder; we'll insert the proper value in rename_registers.  */
690   vec = rtvec_alloc (npred * 2);
691   for (e = b->pred, i = 0; e ; e = e->pred_next, i += 2)
692     if (e->src != ENTRY_BLOCK_PTR)
693       {
694         RTVEC_ELT (vec, i + 0) = pc_rtx;
695         RTVEC_ELT (vec, i + 1) = GEN_INT (e->src->index);
696       }
697
698   phi = gen_rtx_PHI (VOIDmode, vec);
699   phi = gen_rtx_SET (VOIDmode, reg, phi);
700
701   insn = first_insn_after_basic_block_note (b);
702   end_p = PREV_INSN (insn) == b->end;
703   emit_insn_before (phi, insn);
704   if (end_p)
705     b->end = PREV_INSN (insn);
706 }
707
708 static void
709 insert_phi_nodes (idfs, evals, nregs)
710      sbitmap *idfs;
711      sbitmap *evals ATTRIBUTE_UNUSED;
712      int nregs;
713 {
714   int reg;
715
716   for (reg = 0; reg < nregs; ++reg)
717     if (CONVERT_REGISTER_TO_SSA_P (reg))
718     {
719       int b;
720       EXECUTE_IF_SET_IN_SBITMAP (idfs[reg], 0, b,
721         {
722           if (REGNO_REG_SET_P (BASIC_BLOCK (b)->global_live_at_start, reg))
723             insert_phi_node (reg, b);
724         });
725     }
726 }
727
728 /* Rename the registers to conform to SSA. 
729
730    This is essentially the algorithm presented in Figure 7.8 of Morgan,
731    with a few changes to reduce pattern search time in favour of a bit
732    more memory usage.  */
733
734 /* One of these is created for each set.  It will live in a list local
735    to its basic block for the duration of that block's processing.  */
736 struct rename_set_data
737 {
738   struct rename_set_data *next;
739   /* This is the SET_DEST of the (first) SET that sets the REG.  */
740   rtx *reg_loc;
741   /* This is what used to be at *REG_LOC.  */
742   rtx old_reg;
743   /* This is the REG that will replace OLD_REG.  It's set only
744      when the rename data is moved onto the DONE_RENAMES queue.  */
745   rtx new_reg;
746   /* This is what to restore ssa_rename_to_lookup (old_reg) to.  It is
747      usually the previous contents of ssa_rename_to_lookup (old_reg).  */
748   rtx prev_reg;
749   /* This is the insn that contains all the SETs of the REG.  */
750   rtx set_insn;
751 };
752
753 /* This struct is used to pass information to callback functions while
754    renaming registers.  */
755 struct rename_context
756 {
757   struct rename_set_data *new_renames;
758   struct rename_set_data *done_renames;
759   rtx current_insn;
760 };
761
762 /* Queue the rename of *REG_LOC.  */
763 static void
764 create_delayed_rename (c, reg_loc)
765      struct rename_context *c;
766      rtx *reg_loc;
767 {
768   struct rename_set_data *r;
769   r = (struct rename_set_data *) xmalloc (sizeof(*r));
770   
771   if (GET_CODE (*reg_loc) != REG
772       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*reg_loc)))
773     abort();
774
775   r->reg_loc = reg_loc;
776   r->old_reg = *reg_loc;
777   r->prev_reg = ssa_rename_to_lookup(r->old_reg);
778   r->set_insn = c->current_insn;
779   r->next = c->new_renames;
780   c->new_renames = r;
781 }
782
783 /* This is part of a rather ugly hack to allow the pre-ssa regno to be
784    reused.  If, during processing, a register has not yet been touched,
785    ssa_rename_to[regno][machno] will be NULL.  Now, in the course of pushing
786    and popping values from ssa_rename_to, when we would ordinarily 
787    pop NULL back in, we pop RENAME_NO_RTX.  We treat this exactly the
788    same as NULL, except that it signals that the original regno has
789    already been reused.  */
790 #define RENAME_NO_RTX  pc_rtx
791
792 /* Move all the entries from NEW_RENAMES onto DONE_RENAMES by
793    applying all the renames on NEW_RENAMES.  */
794
795 static void
796 apply_delayed_renames (c)
797        struct rename_context *c;
798 {
799   struct rename_set_data *r;
800   struct rename_set_data *last_r = NULL;
801
802   for (r = c->new_renames; r != NULL; r = r->next)
803     {
804       int new_regno;
805       
806       /* Failure here means that someone has a PARALLEL that sets
807          a register twice (bad!).  */
808       if (ssa_rename_to_lookup (r->old_reg) != r->prev_reg)
809         abort();
810       /* Failure here means we have changed REG_LOC before applying
811          the rename.  */
812       /* For the first set we come across, reuse the original regno.  */
813       if (r->prev_reg == NULL_RTX && !HARD_REGISTER_P (r->old_reg))
814         {
815           r->new_reg = r->old_reg;
816           /* We want to restore RENAME_NO_RTX rather than NULL_RTX. */
817           r->prev_reg = RENAME_NO_RTX;
818         }
819       else
820         r->new_reg = gen_reg_rtx (GET_MODE (r->old_reg));
821       new_regno = REGNO (r->new_reg);
822       ssa_rename_to_insert (r->old_reg, r->new_reg);
823
824       if (new_regno >= (int) ssa_definition->num_elements)
825         {
826           int new_limit = new_regno * 5 / 4;
827           VARRAY_GROW (ssa_definition, new_limit);
828         }
829
830       VARRAY_RTX (ssa_definition, new_regno) = r->set_insn;
831       ssa_rename_from_insert (new_regno, r->old_reg);
832       last_r = r;
833     }
834   if (last_r != NULL)
835     {
836       last_r->next = c->done_renames;
837       c->done_renames = c->new_renames;
838       c->new_renames = NULL;
839     }
840 }
841
842 /* Part one of the first step of rename_block, called through for_each_rtx. 
843    Mark pseudos that are set for later update.  Transform uses of pseudos.  */
844
845 static int
846 rename_insn_1 (ptr, data)
847      rtx *ptr;
848      void *data;
849 {
850   rtx x = *ptr;
851   struct rename_context *context = data;
852
853   if (x == NULL_RTX)
854     return 0;
855
856   switch (GET_CODE (x))
857     {
858     case SET:
859       {
860         rtx *destp = &SET_DEST (x);
861         rtx dest = SET_DEST (x);
862
863         /* Some SETs also use the REG specified in their LHS.
864            These can be detected by the presence of
865            STRICT_LOW_PART, SUBREG, SIGN_EXTRACT, and ZERO_EXTRACT
866            in the LHS.  Handle these by changing
867            (set (subreg (reg foo)) ...)
868            into
869            (sequence [(set (reg foo_1) (reg foo))
870                       (set (subreg (reg foo_1)) ...)])  
871
872            FIXME: Much of the time this is too much.  For many libcalls,
873            paradoxical SUBREGs, etc., the input register is dead.  We should
874            recognise this in rename_block or here and not make a false
875            dependency.  */
876            
877         if (GET_CODE (dest) == STRICT_LOW_PART
878             || GET_CODE (dest) == SUBREG
879             || GET_CODE (dest) == SIGN_EXTRACT
880             || GET_CODE (dest) == ZERO_EXTRACT)
881           {
882             rtx i, reg;
883             reg = dest;
884             
885             while (GET_CODE (reg) == STRICT_LOW_PART
886                    || GET_CODE (reg) == SUBREG
887                    || GET_CODE (reg) == SIGN_EXTRACT
888                    || GET_CODE (reg) == ZERO_EXTRACT)
889                 reg = XEXP (reg, 0);
890             
891             if (GET_CODE (reg) == REG
892                 && CONVERT_REGISTER_TO_SSA_P (REGNO (reg)))
893               {
894                 /* Generate (set reg reg), and do renaming on it so
895                    that it becomes (set reg_1 reg_0), and we will
896                    replace reg with reg_1 in the SUBREG.  */
897
898                 struct rename_set_data *saved_new_renames;
899                 saved_new_renames = context->new_renames;
900                 context->new_renames = NULL;
901                 i = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
902                 for_each_rtx (&i, rename_insn_1, data);
903                 apply_delayed_renames (context);
904                 context->new_renames = saved_new_renames;
905               }
906           }
907         else if (GET_CODE (dest) == REG &&
908                  CONVERT_REGISTER_TO_SSA_P (REGNO (dest)))
909           {
910             /* We found a genuine set of an interesting register.  Tag
911                it so that we can create a new name for it after we finish
912                processing this insn.  */
913
914             create_delayed_rename (context, destp);
915
916             /* Since we do not wish to (directly) traverse the
917                SET_DEST, recurse through for_each_rtx for the SET_SRC
918                and return.  */
919             if (GET_CODE (x) == SET)
920               for_each_rtx (&SET_SRC (x), rename_insn_1, data);
921             return -1;
922           }
923
924         /* Otherwise, this was not an interesting destination.  Continue
925            on, marking uses as normal.  */
926         return 0;
927       }
928
929     case REG:
930       if (CONVERT_REGISTER_TO_SSA_P (REGNO (x)) &&
931           REGNO (x) < ssa_max_reg_num)
932         {
933           rtx new_reg = ssa_rename_to_lookup (x);
934
935           if (new_reg != NULL_RTX && new_reg != RENAME_NO_RTX)
936             {
937               if (GET_MODE (x) != GET_MODE (new_reg))
938                 abort ();
939               *ptr = new_reg;
940             }
941           /* Else this is a use before a set.  Warn?  */
942         }
943       return -1;
944
945     case CLOBBER:
946       /* There is considerable debate on how CLOBBERs ought to be
947          handled in SSA.  For now, we're keeping the CLOBBERs, which
948          means that we don't really have SSA form.  There are a couple
949          of proposals for how to fix this problem, but neither is
950          implemented yet.  */
951       {
952         rtx dest = XCEXP (x, 0, CLOBBER);
953         if (REG_P (dest))
954           {
955             if (CONVERT_REGISTER_TO_SSA_P (REGNO (dest))
956                 && REGNO (dest) < ssa_max_reg_num)
957               {
958                 rtx new_reg = ssa_rename_to_lookup (dest);
959                 if (new_reg != NULL_RTX && new_reg != RENAME_NO_RTX)
960                     XCEXP (x, 0, CLOBBER) = new_reg;
961               }
962             /* Stop traversing.  */
963             return -1;
964           }         
965         else
966           /* Continue traversing.  */
967           return 0;
968       }
969
970     case PHI:
971       /* Never muck with the phi.  We do that elsewhere, special-like.  */
972       return -1;
973
974     default:
975       /* Anything else, continue traversing.  */
976       return 0;
977     }
978 }
979
980 static void
981 rename_block (bb, idom)
982      int bb;
983      int *idom;
984 {
985   basic_block b = BASIC_BLOCK (bb);
986   edge e;
987   rtx insn, next, last;
988   struct rename_set_data *set_data = NULL;
989   int c;
990
991   /* Step One: Walk the basic block, adding new names for sets and
992      replacing uses.  */
993      
994   next = b->head;
995   last = b->end;
996   do
997     {
998       insn = next;
999       if (INSN_P (insn))
1000         {
1001           struct rename_context context;
1002           context.done_renames = set_data;
1003           context.new_renames = NULL;
1004           context.current_insn = insn;
1005
1006           start_sequence ();
1007           for_each_rtx (&PATTERN (insn), rename_insn_1, &context);
1008           for_each_rtx (&REG_NOTES (insn), rename_insn_1, &context);
1009
1010           /* Sometimes, we end up with a sequence of insns that
1011              SSA needs to treat as a single insn.  Wrap these in a
1012              SEQUENCE.  (Any notes now get attached to the SEQUENCE,
1013              not to the old version inner insn.)  */
1014           if (get_insns () != NULL_RTX)
1015             {
1016               rtx seq;
1017               int i;
1018               
1019               emit (PATTERN (insn));
1020               seq = gen_sequence ();
1021               /* We really want a SEQUENCE of SETs, not a SEQUENCE
1022                  of INSNs.  */
1023               for (i = 0; i < XVECLEN (seq, 0); i++)
1024                 XVECEXP (seq, 0, i) = PATTERN (XVECEXP (seq, 0, i));
1025               PATTERN (insn) = seq;
1026             }
1027           end_sequence ();
1028           
1029           apply_delayed_renames (&context);
1030           set_data = context.done_renames;
1031         }
1032
1033       next = NEXT_INSN (insn);
1034     }
1035   while (insn != last);
1036
1037   /* Step Two: Update the phi nodes of this block's successors.  */
1038
1039   for (e = b->succ; e; e = e->succ_next)
1040     {
1041       if (e->dest == EXIT_BLOCK_PTR)
1042         continue;
1043
1044       insn = first_insn_after_basic_block_note (e->dest);
1045
1046       while (PHI_NODE_P (insn))
1047         {
1048           rtx phi = PATTERN (insn);
1049           rtx reg;
1050
1051           /* Find out which of our outgoing registers this node is
1052              intended to replace.  Note that if this is not the first PHI
1053              node to have been created for this register, we have to
1054              jump through rename links to figure out which register
1055              we're talking about.  This can easily be recognized by
1056              noting that the regno is new to this pass.  */
1057           reg = SET_DEST (phi);
1058           if (REGNO (reg) >= ssa_max_reg_num)
1059             reg = ssa_rename_from_lookup (REGNO (reg));
1060           if (reg == NULL_RTX)
1061             abort ();
1062           reg = ssa_rename_to_lookup (reg);
1063
1064           /* It is possible for the variable to be uninitialized on
1065              edges in.  Reduce the arity of the PHI so that we don't
1066              consider those edges.  */
1067           if (reg == NULL || reg == RENAME_NO_RTX)
1068             {
1069               if (! remove_phi_alternative (phi, bb))
1070                 abort ();
1071             }
1072           else
1073             {
1074               /* When we created the PHI nodes, we did not know what mode
1075              the register should be.  Now that we've found an original,
1076              we can fill that in.  */
1077               if (GET_MODE (SET_DEST (phi)) == VOIDmode)
1078                 PUT_MODE (SET_DEST (phi), GET_MODE (reg));
1079               else if (GET_MODE (SET_DEST (phi)) != GET_MODE (reg))
1080                 abort();
1081
1082               *phi_alternative (phi, bb) = reg;
1083             }
1084
1085           insn = NEXT_INSN (insn);
1086         }
1087     }
1088
1089   /* Step Three: Do the same to the children of this block in
1090      dominator order.  */
1091
1092   for (c = 0; c < n_basic_blocks; ++c)
1093     if (idom[c] == bb)
1094       rename_block (c, idom);
1095
1096   /* Step Four: Update the sets to refer to their new register,
1097      and restore ssa_rename_to to its previous state.  */
1098
1099   while (set_data)
1100     {
1101       struct rename_set_data *next;
1102       rtx old_reg = *set_data->reg_loc;
1103
1104       if (*set_data->reg_loc != set_data->old_reg)
1105         abort();
1106       *set_data->reg_loc = set_data->new_reg;
1107
1108       ssa_rename_to_insert (old_reg, set_data->prev_reg);
1109
1110       next = set_data->next;
1111       free (set_data);
1112       set_data = next;
1113     }      
1114 }
1115
1116 static void
1117 rename_registers (nregs, idom)
1118      int nregs;
1119      int *idom;
1120 {
1121   VARRAY_RTX_INIT (ssa_definition, nregs * 3, "ssa_definition");
1122   ssa_rename_from_initialize ();
1123
1124   ssa_rename_to_pseudo = (rtx *) alloca (nregs * sizeof(rtx));
1125   memset ((char *) ssa_rename_to_pseudo, 0, nregs * sizeof(rtx));
1126   memset ((char *) ssa_rename_to_hard, 0, 
1127          FIRST_PSEUDO_REGISTER * NUM_MACHINE_MODES * sizeof (rtx));
1128
1129   rename_block (0, idom);
1130
1131   /* ??? Update basic_block_live_at_start, and other flow info 
1132      as needed.  */
1133
1134   ssa_rename_to_pseudo = NULL;
1135 }
1136
1137 /* The main entry point for moving to SSA.  */
1138
1139 void
1140 convert_to_ssa ()
1141 {
1142   /* Element I is the set of blocks that set register I.  */
1143   sbitmap *evals;
1144
1145   /* Dominator bitmaps.  */
1146   sbitmap *dfs;
1147   sbitmap *idfs;
1148
1149   /* Element I is the immediate dominator of block I.  */
1150   int *idom;
1151
1152   int nregs;
1153
1154   /* Don't do it twice.  */
1155   if (in_ssa_form)
1156     abort ();
1157
1158   /* Need global_live_at_{start,end} up to date.  */
1159   life_analysis (get_insns (), NULL, PROP_KILL_DEAD_CODE | PROP_SCAN_DEAD_CODE);
1160
1161   idom = (int *) alloca (n_basic_blocks * sizeof (int));
1162   memset ((void *)idom, -1, (size_t)n_basic_blocks * sizeof (int));
1163   calculate_dominance_info (idom, NULL, CDI_DOMINATORS);
1164
1165   if (rtl_dump_file)
1166     {
1167       int i;
1168       fputs (";; Immediate Dominators:\n", rtl_dump_file);
1169       for (i = 0; i < n_basic_blocks; ++i)
1170         fprintf (rtl_dump_file, ";\t%3d = %3d\n", i, idom[i]);
1171       fflush (rtl_dump_file);
1172     }
1173
1174   /* Compute dominance frontiers.  */
1175
1176   dfs = sbitmap_vector_alloc (n_basic_blocks, n_basic_blocks);
1177   compute_dominance_frontiers (dfs, idom);
1178
1179   if (rtl_dump_file)
1180     {
1181       dump_sbitmap_vector (rtl_dump_file, ";; Dominance Frontiers:",
1182                            "; Basic Block", dfs, n_basic_blocks);
1183       fflush (rtl_dump_file);
1184     }
1185
1186   /* Compute register evaluations.  */
1187
1188   ssa_max_reg_num = max_reg_num();
1189   nregs = ssa_max_reg_num;
1190   evals = sbitmap_vector_alloc (nregs, n_basic_blocks);
1191   find_evaluations (evals, nregs);
1192
1193   /* Compute the iterated dominance frontier for each register.  */
1194
1195   idfs = sbitmap_vector_alloc (nregs, n_basic_blocks);
1196   compute_iterated_dominance_frontiers (idfs, dfs, evals, nregs);
1197
1198   if (rtl_dump_file)
1199     {
1200       dump_sbitmap_vector (rtl_dump_file, ";; Iterated Dominance Frontiers:",
1201                            "; Register", idfs, nregs);
1202       fflush (rtl_dump_file);
1203     }
1204
1205   /* Insert the phi nodes.  */
1206
1207   insert_phi_nodes (idfs, evals, nregs);
1208
1209   /* Rename the registers to satisfy SSA.  */
1210
1211   rename_registers (nregs, idom);
1212
1213   /* All done!  Clean up and go home.  */
1214
1215   sbitmap_vector_free (dfs);
1216   sbitmap_vector_free (evals);
1217   sbitmap_vector_free (idfs);
1218   in_ssa_form = 1;
1219
1220   reg_scan (get_insns (), max_reg_num (), 1);
1221 }
1222
1223 /* REG is the representative temporary of its partition.  Add it to the
1224    set of nodes to be processed, if it hasn't been already.  Return the
1225    index of this register in the node set.  */
1226
1227 static inline int
1228 ephi_add_node (reg, nodes, n_nodes)
1229      rtx reg, *nodes;
1230      int *n_nodes;
1231 {
1232   int i;
1233   for (i = *n_nodes - 1; i >= 0; --i)
1234     if (REGNO (reg) == REGNO (nodes[i]))
1235       return i;
1236
1237   nodes[i = (*n_nodes)++] = reg;
1238   return i;
1239 }
1240
1241 /* Part one of the topological sort.  This is a forward (downward) search
1242    through the graph collecting a stack of nodes to process.  Assuming no
1243    cycles, the nodes at top of the stack when we are finished will have
1244    no other dependancies.  */
1245
1246 static int *
1247 ephi_forward (t, visited, succ, tstack)
1248      int t;
1249      sbitmap visited;
1250      sbitmap *succ;
1251      int *tstack;
1252 {
1253   int s;
1254
1255   SET_BIT (visited, t);
1256
1257   EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
1258     {
1259       if (! TEST_BIT (visited, s))
1260         tstack = ephi_forward (s, visited, succ, tstack);
1261     });
1262
1263   *tstack++ = t;
1264   return tstack;
1265 }
1266
1267 /* Part two of the topological sort.  The is a backward search through
1268    a cycle in the graph, copying the data forward as we go.  */
1269
1270 static void
1271 ephi_backward (t, visited, pred, nodes)
1272      int t;
1273      sbitmap visited, *pred;
1274      rtx *nodes;
1275 {
1276   int p;
1277
1278   SET_BIT (visited, t);
1279
1280   EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1281     {
1282       if (! TEST_BIT (visited, p))
1283         {
1284           ephi_backward (p, visited, pred, nodes);
1285           emit_move_insn (nodes[p], nodes[t]);
1286         }
1287     });
1288 }
1289
1290 /* Part two of the topological sort.  Create the copy for a register
1291    and any cycle of which it is a member.  */
1292
1293 static void
1294 ephi_create (t, visited, pred, succ, nodes)
1295      int t;
1296      sbitmap visited, *pred, *succ;
1297      rtx *nodes;
1298 {
1299   rtx reg_u = NULL_RTX;
1300   int unvisited_predecessors = 0;
1301   int p;
1302
1303   /* Iterate through the predecessor list looking for unvisited nodes.
1304      If there are any, we have a cycle, and must deal with that.  At 
1305      the same time, look for a visited predecessor.  If there is one,
1306      we won't need to create a temporary.  */
1307
1308   EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1309     {
1310       if (! TEST_BIT (visited, p))
1311         unvisited_predecessors = 1;
1312       else if (!reg_u)
1313         reg_u = nodes[p];
1314     });
1315
1316   if (unvisited_predecessors)
1317     {
1318       /* We found a cycle.  Copy out one element of the ring (if necessary),
1319          then traverse the ring copying as we go.  */
1320
1321       if (!reg_u)
1322         {
1323           reg_u = gen_reg_rtx (GET_MODE (nodes[t]));
1324           emit_move_insn (reg_u, nodes[t]);
1325         }
1326
1327       EXECUTE_IF_SET_IN_SBITMAP (pred[t], 0, p,
1328         {
1329           if (! TEST_BIT (visited, p))
1330             {
1331               ephi_backward (p, visited, pred, nodes);
1332               emit_move_insn (nodes[p], reg_u);
1333             }
1334         });
1335     }  
1336   else 
1337     {
1338       /* No cycle.  Just copy the value from a successor.  */
1339
1340       int s;
1341       EXECUTE_IF_SET_IN_SBITMAP (succ[t], 0, s,
1342         {
1343           SET_BIT (visited, t);
1344           emit_move_insn (nodes[t], nodes[s]);
1345           return;
1346         });
1347     }
1348 }
1349
1350 /* Convert the edge to normal form.  */
1351
1352 static void
1353 eliminate_phi (e, reg_partition)
1354      edge e;
1355      partition reg_partition;
1356 {
1357   int n_nodes;
1358   sbitmap *pred, *succ;
1359   sbitmap visited;
1360   rtx *nodes;
1361   int *stack, *tstack;
1362   rtx insn;
1363   int i;
1364
1365   /* Collect an upper bound on the number of registers needing processing.  */
1366
1367   insn = first_insn_after_basic_block_note (e->dest);
1368
1369   n_nodes = 0;
1370   while (PHI_NODE_P (insn))
1371     {
1372       insn = next_nonnote_insn (insn);
1373       n_nodes += 2;
1374     }
1375
1376   if (n_nodes == 0)
1377     return;
1378
1379   /* Build the auxilliary graph R(B). 
1380
1381      The nodes of the graph are the members of the register partition
1382      present in Phi(B).  There is an edge from FIND(T0)->FIND(T1) for
1383      each T0 = PHI(...,T1,...), where T1 is for the edge from block C.  */
1384
1385   nodes = (rtx *) alloca (n_nodes * sizeof(rtx));
1386   pred = sbitmap_vector_alloc (n_nodes, n_nodes);
1387   succ = sbitmap_vector_alloc (n_nodes, n_nodes);
1388   sbitmap_vector_zero (pred, n_nodes);
1389   sbitmap_vector_zero (succ, n_nodes);
1390
1391   insn = first_insn_after_basic_block_note (e->dest);
1392
1393   n_nodes = 0;
1394   for (; PHI_NODE_P (insn); insn = next_nonnote_insn (insn))
1395     {
1396       rtx* preg = phi_alternative (PATTERN (insn), e->src->index);
1397       rtx tgt = SET_DEST (PATTERN (insn));
1398       rtx reg;
1399
1400       /* There may be no phi alternative corresponding to this edge.
1401          This indicates that the phi variable is undefined along this
1402          edge.  */
1403       if (preg == NULL)
1404         continue;
1405       reg = *preg;
1406
1407       if (GET_CODE (reg) != REG || GET_CODE (tgt) != REG)
1408         abort();
1409
1410       reg = regno_reg_rtx[partition_find (reg_partition, REGNO (reg))];
1411       tgt = regno_reg_rtx[partition_find (reg_partition, REGNO (tgt))];
1412       /* If the two registers are already in the same partition, 
1413          nothing will need to be done.  */
1414       if (reg != tgt)
1415         {
1416           int ireg, itgt;
1417
1418           ireg = ephi_add_node (reg, nodes, &n_nodes);
1419           itgt = ephi_add_node (tgt, nodes, &n_nodes);
1420
1421           SET_BIT (pred[ireg], itgt);
1422           SET_BIT (succ[itgt], ireg);
1423         }
1424     }
1425
1426   if (n_nodes == 0)
1427     goto out;
1428
1429   /* Begin a topological sort of the graph.  */
1430
1431   visited = sbitmap_alloc (n_nodes);
1432   sbitmap_zero (visited);
1433
1434   tstack = stack = (int *) alloca (n_nodes * sizeof (int));
1435
1436   for (i = 0; i < n_nodes; ++i)
1437     if (! TEST_BIT (visited, i))
1438       tstack = ephi_forward (i, visited, succ, tstack);
1439
1440   sbitmap_zero (visited);
1441
1442   /* As we find a solution to the tsort, collect the implementation 
1443      insns in a sequence.  */
1444   start_sequence ();
1445   
1446   while (tstack != stack)
1447     {
1448       i = *--tstack;
1449       if (! TEST_BIT (visited, i))
1450         ephi_create (i, visited, pred, succ, nodes);
1451     }
1452
1453   insn = gen_sequence ();
1454   end_sequence ();
1455   insert_insn_on_edge (insn, e);
1456   if (rtl_dump_file)
1457     fprintf (rtl_dump_file, "Emitting copy on edge (%d,%d)\n",
1458              e->src->index, e->dest->index);
1459
1460   sbitmap_free (visited);
1461 out:
1462   sbitmap_vector_free (pred);
1463   sbitmap_vector_free (succ);
1464 }
1465
1466 /* For basic block B, consider all phi insns which provide an
1467    alternative corresponding to an incoming abnormal critical edge.
1468    Place the phi alternative corresponding to that abnormal critical
1469    edge in the same register class as the destination of the set.  
1470
1471    From Morgan, p. 178:
1472
1473      For each abnormal critical edge (C, B), 
1474      if T0 = phi (T1, ..., Ti, ..., Tm) is a phi node in B, 
1475      and C is the ith predecessor of B, 
1476      then T0 and Ti must be equivalent. 
1477
1478    Return non-zero iff any such cases were found for which the two
1479    regs were not already in the same class.  */
1480
1481 static int
1482 make_regs_equivalent_over_bad_edges (bb, reg_partition)
1483      int bb;
1484      partition reg_partition;
1485 {
1486   int changed = 0;
1487   basic_block b = BASIC_BLOCK (bb);
1488   rtx phi;
1489
1490   /* Advance to the first phi node.  */
1491   phi = first_insn_after_basic_block_note (b);
1492
1493   /* Scan all the phi nodes.  */
1494   for (; 
1495        PHI_NODE_P (phi);
1496        phi = next_nonnote_insn (phi))
1497     {
1498       edge e;
1499       int tgt_regno;
1500       rtx set = PATTERN (phi);
1501       rtx tgt = SET_DEST (set);
1502
1503       /* The set target is expected to be an SSA register.  */
1504       if (GET_CODE (tgt) != REG 
1505           || !CONVERT_REGISTER_TO_SSA_P (REGNO (tgt)))
1506         abort ();
1507       tgt_regno = REGNO (tgt);
1508
1509       /* Scan incoming abnormal critical edges.  */
1510       for (e = b->pred; e; e = e->pred_next)
1511         if ((e->flags & (EDGE_ABNORMAL | EDGE_CRITICAL)) 
1512                 == (EDGE_ABNORMAL | EDGE_CRITICAL))
1513           {
1514             rtx *alt = phi_alternative (set, e->src->index);
1515             int alt_regno;
1516
1517             /* If there is no alternative corresponding to this edge,
1518                the value is undefined along the edge, so just go on.  */
1519             if (alt == 0)
1520               continue;
1521
1522             /* The phi alternative is expected to be an SSA register.  */
1523             if (GET_CODE (*alt) != REG 
1524                 || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
1525               abort ();
1526             alt_regno = REGNO (*alt);
1527
1528             /* If the set destination and the phi alternative aren't
1529                already in the same class...  */
1530             if (partition_find (reg_partition, tgt_regno) 
1531                 != partition_find (reg_partition, alt_regno))
1532               {
1533                 /* ... make them such.  */
1534                 if (conflicting_hard_regs_p (tgt_regno, alt_regno))
1535                   /* It is illegal to unify a hard register with a
1536                      different register.  */
1537                   abort ();
1538                 
1539                 partition_union (reg_partition, 
1540                                  tgt_regno, alt_regno);
1541                 ++changed;
1542               }
1543           }
1544     }
1545
1546   return changed;
1547 }
1548
1549 /* Consider phi insns in basic block BB pairwise.  If the set target
1550    of both isns are equivalent pseudos, make the corresponding phi
1551    alternatives in each phi corresponding equivalent.
1552
1553    Return nonzero if any new register classes were unioned.  */
1554
1555 static int
1556 make_equivalent_phi_alternatives_equivalent (bb, reg_partition)
1557      int bb;
1558      partition reg_partition;
1559 {
1560   int changed = 0;
1561   basic_block b = BASIC_BLOCK (bb);
1562   rtx phi;
1563
1564   /* Advance to the first phi node.  */
1565   phi = first_insn_after_basic_block_note (b);
1566
1567   /* Scan all the phi nodes.  */
1568   for (; 
1569        PHI_NODE_P (phi);
1570        phi = next_nonnote_insn (phi))
1571     {
1572       rtx set = PATTERN (phi);
1573       /* The regno of the destination of the set.  */
1574       int tgt_regno = REGNO (SET_DEST (PATTERN (phi)));
1575
1576       rtx phi2 = next_nonnote_insn (phi);
1577
1578       /* Scan all phi nodes following this one.  */
1579       for (;
1580            PHI_NODE_P (phi2);
1581            phi2 = next_nonnote_insn (phi2))
1582         {
1583           rtx set2 = PATTERN (phi2);
1584           /* The regno of the destination of the set.  */
1585           int tgt2_regno = REGNO (SET_DEST (set2));
1586                   
1587           /* Are the set destinations equivalent regs?  */
1588           if (partition_find (reg_partition, tgt_regno) ==
1589               partition_find (reg_partition, tgt2_regno))
1590             {
1591               edge e;
1592               /* Scan over edges.  */
1593               for (e = b->pred; e; e = e->pred_next)
1594                 {
1595                   int pred_block = e->src->index;
1596                   /* Identify the phi alternatives from both phi
1597                      nodes corresponding to this edge.  */
1598                   rtx *alt = phi_alternative (set, pred_block);
1599                   rtx *alt2 = phi_alternative (set2, pred_block);
1600
1601                   /* If one of the phi nodes doesn't have a
1602                      corresponding alternative, just skip it.  */
1603                   if (alt == 0 || alt2 == 0)
1604                     continue;
1605
1606                   /* Both alternatives should be SSA registers.  */
1607                   if (GET_CODE (*alt) != REG
1608                       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt)))
1609                     abort ();
1610                   if (GET_CODE (*alt2) != REG
1611                       || !CONVERT_REGISTER_TO_SSA_P (REGNO (*alt2)))
1612                     abort ();
1613
1614                   /* If the alternatives aren't already in the same
1615                      class ... */
1616                   if (partition_find (reg_partition, REGNO (*alt)) 
1617                       != partition_find (reg_partition, REGNO (*alt2)))
1618                     {
1619                       /* ... make them so.  */
1620                       if (conflicting_hard_regs_p (REGNO (*alt), REGNO (*alt2)))
1621                         /* It is illegal to unify a hard register with
1622                            a different register. */
1623                         abort ();
1624
1625                       partition_union (reg_partition, 
1626                                        REGNO (*alt), REGNO (*alt2));
1627                       ++changed;
1628                     }
1629                 }
1630             }
1631         }
1632     }
1633
1634   return changed;
1635 }
1636
1637 /* Compute a conservative partition of outstanding pseudo registers.
1638    See Morgan 7.3.1.  */
1639
1640 static partition
1641 compute_conservative_reg_partition ()
1642 {
1643   int bb;
1644   int changed = 0;
1645
1646   /* We don't actually work with hard registers, but it's easier to
1647      carry them around anyway rather than constantly doing register
1648      number arithmetic.  */
1649   partition p = 
1650     partition_new (ssa_definition->num_elements);
1651
1652   /* The first priority is to make sure registers that might have to
1653      be copied on abnormal critical edges are placed in the same
1654      partition.  This saves us from having to split abnormal critical
1655      edges.  */
1656   for (bb = n_basic_blocks; --bb >= 0; )
1657     changed += make_regs_equivalent_over_bad_edges (bb, p);
1658   
1659   /* Now we have to insure that corresponding arguments of phi nodes
1660      assigning to corresponding regs are equivalent.  Iterate until
1661      nothing changes.  */
1662   while (changed > 0)
1663     {
1664       changed = 0;
1665       for (bb = n_basic_blocks; --bb >= 0; )
1666         changed += make_equivalent_phi_alternatives_equivalent (bb, p);
1667     }
1668
1669   return p;
1670 }
1671
1672 /* The following functions compute a register partition that attempts
1673    to eliminate as many reg copies and phi node copies as possible by
1674    coalescing registers.   This is the strategy:
1675
1676     1. As in the conservative case, the top priority is to coalesce
1677        registers that otherwise would cause copies to be placed on
1678        abnormal critical edges (which isn't possible).
1679
1680     2. Figure out which regs are involved (in the LHS or RHS) of
1681        copies and phi nodes.  Compute conflicts among these regs.  
1682
1683     3. Walk around the instruction stream, placing two regs in the
1684        same class of the partition if one appears on the LHS and the
1685        other on the RHS of a copy or phi node and the two regs don't
1686        conflict.  The conflict information of course needs to be
1687        updated.  
1688
1689     4. If anything has changed, there may be new opportunities to
1690        coalesce regs, so go back to 2.
1691 */
1692
1693 /* If REG1 and REG2 don't conflict in CONFLICTS, place them in the
1694    same class of partition P, if they aren't already.  Update
1695    CONFLICTS appropriately.  
1696
1697    Returns one if REG1 and REG2 were placed in the same class but were
1698    not previously; zero otherwise.  
1699
1700    See Morgan figure 11.15.  */
1701
1702 static int 
1703 coalesce_if_unconflicting (p, conflicts, reg1, reg2)
1704      partition p;
1705      conflict_graph conflicts;
1706      int reg1;
1707      int reg2;
1708 {
1709   int reg;
1710
1711   /* Work only on SSA registers. */
1712   if (!CONVERT_REGISTER_TO_SSA_P (reg1) || !CONVERT_REGISTER_TO_SSA_P (reg2))
1713     return 0;
1714
1715   /* Find the canonical regs for the classes containing REG1 and
1716      REG2.  */
1717   reg1 = partition_find (p, reg1);
1718   reg2 = partition_find (p, reg2);
1719   
1720   /* If they're already in the same class, there's nothing to do.  */
1721   if (reg1 == reg2)
1722     return 0;
1723
1724   /* If the regs conflict, our hands are tied.  */
1725   if (conflicting_hard_regs_p (reg1, reg2) ||
1726       conflict_graph_conflict_p (conflicts, reg1, reg2))
1727     return 0;
1728
1729   /* We're good to go.  Put the regs in the same partition.  */
1730   partition_union (p, reg1, reg2);
1731
1732   /* Find the new canonical reg for the merged class.  */
1733   reg = partition_find (p, reg1);
1734   
1735   /* Merge conflicts from the two previous classes.  */
1736   conflict_graph_merge_regs (conflicts, reg, reg1);
1737   conflict_graph_merge_regs (conflicts, reg, reg2);
1738
1739   return 1;
1740 }
1741
1742 /* For each register copy insn in basic block BB, place the LHS and
1743    RHS regs in the same class in partition P if they do not conflict
1744    according to CONFLICTS.
1745
1746    Returns the number of changes that were made to P.
1747
1748    See Morgan figure 11.14.  */
1749
1750 static int
1751 coalesce_regs_in_copies (bb, p, conflicts)
1752      basic_block bb;
1753      partition p;
1754      conflict_graph conflicts;
1755 {
1756   int changed = 0;
1757   rtx insn;
1758   rtx end = bb->end;
1759
1760   /* Scan the instruction stream of the block.  */
1761   for (insn = bb->head; insn != end; insn = NEXT_INSN (insn))
1762     {
1763       rtx pattern;
1764       rtx src;
1765       rtx dest;
1766
1767       /* If this isn't a set insn, go to the next insn.  */
1768       if (GET_CODE (insn) != INSN)
1769         continue;
1770       pattern = PATTERN (insn);
1771       if (GET_CODE (pattern) != SET)
1772         continue;
1773
1774       src = SET_SRC (pattern);
1775       dest = SET_DEST (pattern);
1776
1777       /* We're only looking for copies.  */
1778       if (GET_CODE (src) != REG || GET_CODE (dest) != REG)
1779         continue;
1780
1781       /* Coalesce only if the reg modes are the same.  As long as
1782          each reg's rtx is unique, it can have only one mode, so two
1783          pseudos of different modes can't be coalesced into one.  
1784
1785          FIXME: We can probably get around this by inserting SUBREGs
1786          where appropriate, but for now we don't bother.  */
1787       if (GET_MODE (src) != GET_MODE (dest))
1788         continue;
1789
1790       /* Found a copy; see if we can use the same reg for both the
1791          source and destination (and thus eliminate the copy,
1792          ultimately).  */
1793       changed += coalesce_if_unconflicting (p, conflicts, 
1794                                             REGNO (src), REGNO (dest));
1795     }
1796
1797   return changed;
1798 }
1799
1800 struct phi_coalesce_context
1801 {
1802   partition p;
1803   conflict_graph conflicts;
1804   int changed;
1805 };
1806
1807 /* Callback function for for_each_successor_phi.  If the set
1808    destination and the phi alternative regs do not conflict, place
1809    them in the same paritition class.  DATA is a pointer to a
1810    phi_coalesce_context struct.  */
1811
1812 static int
1813 coalesce_reg_in_phi (insn, dest_regno, src_regno, data)
1814      rtx insn ATTRIBUTE_UNUSED;
1815      int dest_regno;
1816      int src_regno;
1817      void *data;
1818 {
1819   struct phi_coalesce_context *context = 
1820     (struct phi_coalesce_context *) data;
1821   
1822   /* Attempt to use the same reg, if they don't conflict.  */
1823   context->changed 
1824     += coalesce_if_unconflicting (context->p, context->conflicts, 
1825                                   dest_regno, src_regno);
1826   return 0;
1827 }
1828
1829 /* For each alternative in a phi function corresponding to basic block
1830    BB (in phi nodes in successor block to BB), place the reg in the
1831    phi alternative and the reg to which the phi value is set into the
1832    same class in partition P, if allowed by CONFLICTS.  
1833
1834    Return the number of changes that were made to P.
1835    
1836    See Morgan figure 11.14.  */
1837
1838 static int
1839 coalesce_regs_in_successor_phi_nodes (bb, p, conflicts)
1840      basic_block bb;
1841      partition p;
1842      conflict_graph conflicts;
1843 {
1844   struct phi_coalesce_context context;
1845   context.p = p;
1846   context.conflicts = conflicts;
1847   context.changed = 0;
1848
1849   for_each_successor_phi (bb, &coalesce_reg_in_phi, &context);
1850
1851   return context.changed;
1852 }
1853
1854 /* Compute and return a partition of pseudos.  Where possible,
1855    non-conflicting pseudos are placed in the same class.  
1856
1857    The caller is responsible for deallocating the returned partition.  */
1858
1859 static partition
1860 compute_coalesced_reg_partition ()
1861 {
1862   int bb;
1863   int changed = 0;
1864
1865   partition p = 
1866     partition_new (ssa_definition->num_elements);
1867
1868   /* The first priority is to make sure registers that might have to
1869      be copied on abnormal critical edges are placed in the same
1870      partition.  This saves us from having to split abnormal critical
1871      edges (which can't be done).  */
1872   for (bb = n_basic_blocks; --bb >= 0; )
1873     make_regs_equivalent_over_bad_edges (bb, p);
1874
1875   do
1876     {
1877       regset_head phi_set;
1878       conflict_graph conflicts;
1879
1880       changed = 0;
1881
1882       /* Build the set of registers involved in phi nodes, either as
1883          arguments to the phi function or as the target of a set.  */
1884       INITIALIZE_REG_SET (phi_set);
1885       mark_phi_and_copy_regs (&phi_set);
1886
1887       /* Compute conflicts.  */
1888       conflicts = conflict_graph_compute (&phi_set, p);
1889
1890       /* FIXME: Better would be to process most frequently executed
1891          blocks first, so that most frequently executed copies would
1892          be more likely to be removed by register coalescing.  But any
1893          order will generate correct, if non-optimal, results.  */
1894       for (bb = n_basic_blocks; --bb >= 0; )
1895         {
1896           basic_block block = BASIC_BLOCK (bb);
1897           changed += coalesce_regs_in_copies (block, p, conflicts);
1898           changed += 
1899             coalesce_regs_in_successor_phi_nodes (block, p, conflicts);
1900         }
1901
1902       conflict_graph_delete (conflicts);
1903     }
1904   while (changed > 0);
1905
1906   return p;
1907 }
1908
1909 /* Mark the regs in a phi node.  PTR is a phi expression or one of its
1910    components (a REG or a CONST_INT).  DATA is a reg set in which to
1911    set all regs.  Called from for_each_rtx.  */
1912
1913 static int
1914 mark_reg_in_phi (ptr, data)
1915      rtx *ptr;
1916      void *data;
1917 {
1918   rtx expr = *ptr;
1919   regset set = (regset) data;
1920
1921   switch (GET_CODE (expr))
1922     {
1923     case REG:
1924       SET_REGNO_REG_SET (set, REGNO (expr));
1925       /* Fall through.  */
1926     case CONST_INT:
1927     case PHI:
1928       return 0;
1929     default:
1930       abort ();
1931     }
1932 }
1933
1934 /* Mark in PHI_SET all pseudos that are used in a phi node -- either
1935    set from a phi expression, or used as an argument in one.  Also
1936    mark regs that are the source or target of a reg copy.  Uses
1937    ssa_definition.  */
1938
1939 static void
1940 mark_phi_and_copy_regs (phi_set)
1941      regset phi_set;
1942 {
1943   unsigned int reg;
1944
1945   /* Scan the definitions of all regs.  */
1946   for (reg = 0; reg < VARRAY_SIZE (ssa_definition); ++reg)
1947     if (CONVERT_REGISTER_TO_SSA_P (reg))
1948       {
1949         rtx insn = VARRAY_RTX (ssa_definition, reg);
1950         rtx pattern;
1951         rtx src;
1952
1953         if (insn == NULL)
1954           continue;
1955         pattern = PATTERN (insn);
1956         /* Sometimes we get PARALLEL insns.  These aren't phi nodes or
1957            copies.  */
1958         if (GET_CODE (pattern) != SET)
1959           continue;
1960         src = SET_SRC (pattern);
1961
1962         if (GET_CODE (src) == REG)
1963           {
1964             /* It's a reg copy.  */
1965             SET_REGNO_REG_SET (phi_set, reg);
1966             SET_REGNO_REG_SET (phi_set, REGNO (src));
1967           }
1968         else if (GET_CODE (src) == PHI)
1969           {
1970             /* It's a phi node.  Mark the reg being set.  */
1971             SET_REGNO_REG_SET (phi_set, reg);
1972             /* Mark the regs used in the phi function.  */
1973             for_each_rtx (&src, mark_reg_in_phi, phi_set);
1974           }
1975         /* ... else nothing to do.  */
1976       }
1977 }
1978
1979 /* Rename regs in insn PTR that are equivalent.  DATA is the register
1980    partition which specifies equivalences.  */
1981
1982 static int
1983 rename_equivalent_regs_in_insn (ptr, data)
1984      rtx *ptr;
1985      void* data;
1986 {
1987   rtx x = *ptr;
1988   partition reg_partition = (partition) data;
1989
1990   if (x == NULL_RTX)
1991     return 0;
1992
1993   switch (GET_CODE (x))
1994     {
1995     case REG:
1996       if (CONVERT_REGISTER_TO_SSA_P (REGNO (x)))
1997         {
1998           unsigned int regno = REGNO (x);
1999           unsigned int new_regno = partition_find (reg_partition, regno);
2000           rtx canonical_element_rtx = ssa_rename_from_lookup (new_regno);
2001
2002           if (canonical_element_rtx != NULL_RTX && 
2003               HARD_REGISTER_P (canonical_element_rtx))
2004             {
2005               if (REGNO (canonical_element_rtx) != regno)
2006                 *ptr = canonical_element_rtx;
2007             }
2008           else if (regno != new_regno)
2009             {
2010               rtx new_reg = regno_reg_rtx[new_regno];
2011               if (GET_MODE (x) != GET_MODE (new_reg))
2012                 abort ();
2013               *ptr = new_reg;
2014             }
2015         }
2016       return -1;
2017
2018     case PHI:
2019       /* No need to rename the phi nodes.  We'll check equivalence
2020          when inserting copies.  */
2021       return -1;
2022
2023     default:
2024       /* Anything else, continue traversing.  */
2025       return 0;
2026     }
2027 }
2028
2029 /* Record the register's canonical element stored in SRFP in the
2030    canonical_elements sbitmap packaged in DATA.  This function is used
2031    as a callback function for traversing ssa_rename_from.  */
2032
2033 static int
2034 record_canonical_element_1 (srfp, data)
2035      void **srfp;
2036      void *data;
2037 {
2038   unsigned int reg = ((ssa_rename_from_pair *) *srfp)->reg;
2039   sbitmap canonical_elements =
2040     ((struct ssa_rename_from_hash_table_data *) data)->canonical_elements;
2041   partition reg_partition =
2042     ((struct ssa_rename_from_hash_table_data *) data)->reg_partition;
2043   
2044   SET_BIT (canonical_elements, partition_find (reg_partition, reg));
2045   return 1;
2046 }
2047
2048 /* For each class in the REG_PARTITION corresponding to a particular
2049    hard register and machine mode, check that there are no other
2050    classes with the same hard register and machine mode.  Returns
2051    nonzero if this is the case, i.e., the partition is acceptable.  */
2052
2053 static int
2054 check_hard_regs_in_partition (reg_partition)
2055      partition reg_partition;
2056 {
2057   /* CANONICAL_ELEMENTS has a nonzero bit if a class with the given register
2058      number and machine mode has already been seen.  This is a
2059      problem with the partition.  */
2060   sbitmap canonical_elements;
2061   int element_index;
2062   int already_seen[FIRST_PSEUDO_REGISTER][NUM_MACHINE_MODES];
2063   int reg;
2064   int mach_mode;
2065
2066   /* Collect a list of canonical elements.  */
2067   canonical_elements = sbitmap_alloc (max_reg_num ());
2068   sbitmap_zero (canonical_elements);
2069   ssa_rename_from_traverse (&record_canonical_element_1,
2070                             canonical_elements, reg_partition);
2071
2072   /* We have not seen any hard register uses.  */
2073   for (reg = 0; reg < FIRST_PSEUDO_REGISTER; ++reg)
2074     for (mach_mode = 0; mach_mode < NUM_MACHINE_MODES; ++mach_mode)
2075       already_seen[reg][mach_mode] = 0;
2076
2077   /* Check for classes with the same hard register and machine mode.  */
2078   EXECUTE_IF_SET_IN_SBITMAP (canonical_elements, 0, element_index,
2079   {
2080     rtx hard_reg_rtx = ssa_rename_from_lookup (element_index);
2081     if (hard_reg_rtx != NULL_RTX &&
2082         HARD_REGISTER_P (hard_reg_rtx) &&
2083         already_seen[REGNO (hard_reg_rtx)][GET_MODE (hard_reg_rtx)] != 0)
2084           /* Two distinct partition classes should be mapped to the same
2085              hard register.  */
2086           return 0;
2087   });
2088
2089   sbitmap_free (canonical_elements);
2090
2091   return 1;
2092 }
2093
2094 /* Rename regs that are equivalent in REG_PARTITION.  Also collapse
2095    any SEQUENCE insns.  */
2096
2097 static void
2098 rename_equivalent_regs (reg_partition)
2099      partition reg_partition;
2100 {
2101   int bb;
2102
2103   for (bb = n_basic_blocks; --bb >= 0; )
2104     {
2105       basic_block b = BASIC_BLOCK (bb);
2106       rtx next = b->head;
2107       rtx last = b->end;
2108       rtx insn;
2109
2110       do
2111         {
2112           insn = next;
2113           if (INSN_P (insn))
2114             {
2115               for_each_rtx (&PATTERN (insn), 
2116                             rename_equivalent_regs_in_insn, 
2117                             reg_partition);
2118               for_each_rtx (&REG_NOTES (insn), 
2119                             rename_equivalent_regs_in_insn, 
2120                             reg_partition);
2121
2122               if (GET_CODE (PATTERN (insn)) == SEQUENCE)
2123                 {
2124                   rtx s = PATTERN (insn);
2125                   int slen = XVECLEN (s, 0);
2126                   int i;
2127
2128                   if (slen <= 1)
2129                     abort();
2130
2131                   PATTERN (insn) = XVECEXP (s, 0, slen-1);
2132                   for (i = 0; i < slen - 1; i++)
2133                     emit_block_insn_before (XVECEXP (s, 0, i), insn, b);
2134                 }
2135             }
2136
2137           next = NEXT_INSN (insn);
2138         }
2139       while (insn != last);
2140     }
2141 }
2142
2143 /* The main entry point for moving from SSA.  */
2144
2145 void
2146 convert_from_ssa()
2147 {
2148   int bb;
2149   partition reg_partition;
2150   rtx insns = get_insns ();
2151
2152   /* Need global_live_at_{start,end} up to date.  */
2153   life_analysis (insns, NULL, 
2154                  PROP_KILL_DEAD_CODE | PROP_SCAN_DEAD_CODE | PROP_DEATH_NOTES);
2155
2156   /* Figure out which regs in copies and phi nodes don't conflict and
2157      therefore can be coalesced.  */
2158   if (conservative_reg_partition)
2159     reg_partition = compute_conservative_reg_partition ();
2160   else
2161     reg_partition = compute_coalesced_reg_partition ();
2162
2163   if (!check_hard_regs_in_partition (reg_partition))
2164     /* Two separate partitions should correspond to the same hard
2165        register but do not.  */
2166     abort ();
2167
2168   rename_equivalent_regs (reg_partition);
2169
2170   /* Eliminate the PHI nodes.  */
2171   for (bb = n_basic_blocks; --bb >= 0; )
2172     {
2173       basic_block b = BASIC_BLOCK (bb);
2174       edge e;
2175
2176       for (e = b->pred; e; e = e->pred_next)
2177         if (e->src != ENTRY_BLOCK_PTR)
2178           eliminate_phi (e, reg_partition);
2179     }
2180
2181   partition_delete (reg_partition);
2182
2183   /* Actually delete the PHI nodes.  */
2184   for (bb = n_basic_blocks; --bb >= 0; )
2185     {
2186       rtx insn = BLOCK_HEAD (bb);
2187
2188       while (1)
2189         {
2190           /* If this is a PHI node delete it.  */
2191           if (PHI_NODE_P (insn))
2192             {
2193               if (insn == BLOCK_END (bb))
2194                 BLOCK_END (bb) = PREV_INSN (insn);
2195               insn = delete_insn (insn);
2196             }
2197           /* Since all the phi nodes come at the beginning of the
2198              block, if we find an ordinary insn, we can stop looking
2199              for more phi nodes.  */
2200           else if (INSN_P (insn))
2201             break;
2202           /* If we've reached the end of the block, stop.  */
2203           else if (insn == BLOCK_END (bb))
2204             break;
2205           else 
2206             insn = NEXT_INSN (insn);
2207         }
2208     }
2209
2210   /* Commit all the copy nodes needed to convert out of SSA form.  */
2211   commit_edge_insertions ();
2212
2213   in_ssa_form = 0;
2214
2215   count_or_remove_death_notes (NULL, 1);
2216
2217   /* Deallocate the data structures.  */
2218   VARRAY_FREE (ssa_definition);
2219   ssa_rename_from_free ();
2220 }
2221
2222 /* Scan phi nodes in successors to BB.  For each such phi node that
2223    has a phi alternative value corresponding to BB, invoke FN.  FN
2224    is passed the entire phi node insn, the regno of the set
2225    destination, the regno of the phi argument corresponding to BB,
2226    and DATA.
2227
2228    If FN ever returns non-zero, stops immediately and returns this
2229    value.  Otherwise, returns zero.  */
2230
2231 int
2232 for_each_successor_phi (bb, fn, data)
2233      basic_block bb;
2234      successor_phi_fn fn;
2235      void *data;
2236 {
2237   edge e;
2238   
2239   if (bb == EXIT_BLOCK_PTR)
2240     return 0;
2241
2242   /* Scan outgoing edges.  */
2243   for (e = bb->succ; e != NULL; e = e->succ_next)
2244     {
2245       rtx insn;
2246
2247       basic_block successor = e->dest;
2248       if (successor == ENTRY_BLOCK_PTR 
2249           || successor == EXIT_BLOCK_PTR)
2250         continue;
2251
2252       /* Advance to the first non-label insn of the successor block.  */
2253       insn = first_insn_after_basic_block_note (successor);
2254
2255       if (insn == NULL)
2256         continue;
2257
2258       /* Scan phi nodes in the successor.  */
2259       for ( ; PHI_NODE_P (insn); insn = NEXT_INSN (insn))
2260         {
2261           int result;
2262           rtx phi_set = PATTERN (insn);
2263           rtx *alternative = phi_alternative (phi_set, bb->index);
2264           rtx phi_src;
2265           
2266           /* This phi function may not have an alternative
2267              corresponding to the incoming edge, indicating the
2268              assigned variable is not defined along the edge.  */
2269           if (alternative == NULL)
2270             continue;
2271           phi_src = *alternative;
2272
2273           /* Invoke the callback.  */
2274           result = (*fn) (insn, REGNO (SET_DEST (phi_set)), 
2275                           REGNO (phi_src), data);
2276
2277           /* Terminate if requested.  */
2278           if (result != 0)
2279             return result;
2280         }
2281     }
2282
2283   return 0;
2284 }
2285
2286 /* Assuming the ssa_rename_from mapping has been established, yields
2287    nonzero if 1) only one SSA register of REG1 and REG2 comes from a
2288    hard register or 2) both SSA registers REG1 and REG2 come from
2289    different hard registers.  */
2290
2291 static int
2292 conflicting_hard_regs_p (reg1, reg2)
2293      int reg1;
2294      int reg2;
2295 {
2296   int orig_reg1 = original_register (reg1);
2297   int orig_reg2 = original_register (reg2);
2298   if (HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2)
2299       && orig_reg1 != orig_reg2)
2300     return 1;
2301   if (HARD_REGISTER_NUM_P (orig_reg1) && !HARD_REGISTER_NUM_P (orig_reg2))
2302     return 1;
2303   if (!HARD_REGISTER_NUM_P (orig_reg1) && HARD_REGISTER_NUM_P (orig_reg2))
2304     return 1;
2305   
2306   return 0;
2307 }