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