OSDN Git Service

PR tree-optimization/49960
[pf3gnuchains/gcc-fork.git] / gcc / cprop.c
1 /* Global constant/copy propagation for RTL.
2    Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3    2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "diagnostic-core.h"
26 #include "toplev.h"
27
28 #include "rtl.h"
29 #include "tree.h"
30 #include "tm_p.h"
31 #include "regs.h"
32 #include "hard-reg-set.h"
33 #include "flags.h"
34 #include "insn-config.h"
35 #include "recog.h"
36 #include "basic-block.h"
37 #include "output.h"
38 #include "function.h"
39 #include "expr.h"
40 #include "except.h"
41 #include "params.h"
42 #include "cselib.h"
43 #include "intl.h"
44 #include "obstack.h"
45 #include "timevar.h"
46 #include "tree-pass.h"
47 #include "hashtab.h"
48 #include "df.h"
49 #include "dbgcnt.h"
50 #include "target.h"
51
52 \f
53 /* An obstack for our working variables.  */
54 static struct obstack cprop_obstack;
55
56 /* Occurrence of an expression.
57    There is one per basic block.  If a pattern appears more than once the
58    last appearance is used.  */
59
60 struct occr
61 {
62   /* Next occurrence of this expression.  */
63   struct occr *next;
64   /* The insn that computes the expression.  */
65   rtx insn;
66 };
67
68 typedef struct occr *occr_t;
69 DEF_VEC_P (occr_t);
70 DEF_VEC_ALLOC_P (occr_t, heap);
71
72 /* Hash table entry for assignment expressions.  */
73
74 struct expr
75 {
76   /* The expression (DEST := SRC).  */
77   rtx dest;
78   rtx src;
79
80   /* Index in the available expression bitmaps.  */
81   int bitmap_index;
82   /* Next entry with the same hash.  */
83   struct expr *next_same_hash;
84   /* List of available occurrence in basic blocks in the function.
85      An "available occurrence" is one that is the last occurrence in the
86      basic block and whose operands are not modified by following statements
87      in the basic block [including this insn].  */
88   struct occr *avail_occr;
89 };
90
91 /* Hash table for copy propagation expressions.
92    Each hash table is an array of buckets.
93    ??? It is known that if it were an array of entries, structure elements
94    `next_same_hash' and `bitmap_index' wouldn't be necessary.  However, it is
95    not clear whether in the final analysis a sufficient amount of memory would
96    be saved as the size of the available expression bitmaps would be larger
97    [one could build a mapping table without holes afterwards though].
98    Someday I'll perform the computation and figure it out.  */
99
100 struct hash_table_d
101 {
102   /* The table itself.
103      This is an array of `set_hash_table_size' elements.  */
104   struct expr **table;
105
106   /* Size of the hash table, in elements.  */
107   unsigned int size;
108
109   /* Number of hash table elements.  */
110   unsigned int n_elems;
111 };
112
113 /* Copy propagation hash table.  */
114 static struct hash_table_d set_hash_table;
115
116 /* Array of implicit set patterns indexed by basic block index.  */
117 static rtx *implicit_sets;
118
119 /* Bitmap containing one bit for each register in the program.
120    Used when performing GCSE to track which registers have been set since
121    the start or end of the basic block while traversing that block.  */
122 static regset reg_set_bitmap;
123
124 /* Various variables for statistics gathering.  */
125
126 /* Memory used in a pass.
127    This isn't intended to be absolutely precise.  Its intent is only
128    to keep an eye on memory usage.  */
129 static int bytes_used;
130
131 /* Number of local constants propagated.  */
132 static int local_const_prop_count;
133 /* Number of local copies propagated.  */
134 static int local_copy_prop_count;
135 /* Number of global constants propagated.  */
136 static int global_const_prop_count;
137 /* Number of global copies propagated.  */
138 static int global_copy_prop_count;
139
140 #define GOBNEW(T)               ((T *) cprop_alloc (sizeof (T)))
141 #define GOBNEWVAR(T, S)         ((T *) cprop_alloc ((S)))
142
143 /* Cover function to obstack_alloc.  */
144
145 static void *
146 cprop_alloc (unsigned long size)
147 {
148   bytes_used += size;
149   return obstack_alloc (&cprop_obstack, size);
150 }
151 \f
152 /* Return nonzero if register X is unchanged from INSN to the end
153    of INSN's basic block.  */
154
155 static int
156 reg_available_p (const_rtx x, const_rtx insn ATTRIBUTE_UNUSED)
157 {
158   return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
159 }
160
161 /* Hash a set of register REGNO.
162
163    Sets are hashed on the register that is set.  This simplifies the PRE copy
164    propagation code.
165
166    ??? May need to make things more elaborate.  Later, as necessary.  */
167
168 static unsigned int
169 hash_set (int regno, int hash_table_size)
170 {
171   unsigned int hash;
172
173   hash = regno;
174   return hash % hash_table_size;
175 }
176
177 /* Insert assignment DEST:=SET from INSN in the hash table.
178    DEST is a register and SET is a register or a suitable constant.
179    If the assignment is already present in the table, record it as
180    the last occurrence in INSN's basic block.  */
181
182 static void
183 insert_set_in_table (rtx dest, rtx src, rtx insn, struct hash_table_d *table)
184 {
185   bool found = false;
186   unsigned int hash;
187   struct expr *cur_expr, *last_expr = NULL;
188   struct occr *cur_occr;
189
190   hash = hash_set (REGNO (dest), table->size);
191
192   for (cur_expr = table->table[hash]; cur_expr;
193        cur_expr = cur_expr->next_same_hash)
194     {
195       if (dest == cur_expr->dest
196           && src == cur_expr->src)
197         {
198           found = true;
199           break;
200         }
201       last_expr = cur_expr;
202     }
203
204   if (! found)
205     {
206       cur_expr = GOBNEW (struct expr);
207       bytes_used += sizeof (struct expr);
208       if (table->table[hash] == NULL)
209         /* This is the first pattern that hashed to this index.  */
210         table->table[hash] = cur_expr;
211       else
212         /* Add EXPR to end of this hash chain.  */
213         last_expr->next_same_hash = cur_expr;
214
215       /* Set the fields of the expr element.
216          We must copy X because it can be modified when copy propagation is
217          performed on its operands.  */
218       cur_expr->dest = copy_rtx (dest);
219       cur_expr->src = copy_rtx (src);
220       cur_expr->bitmap_index = table->n_elems++;
221       cur_expr->next_same_hash = NULL;
222       cur_expr->avail_occr = NULL;
223     }
224
225   /* Now record the occurrence.  */
226   cur_occr = cur_expr->avail_occr;
227
228   if (cur_occr
229       && BLOCK_FOR_INSN (cur_occr->insn) == BLOCK_FOR_INSN (insn))
230     {
231       /* Found another instance of the expression in the same basic block.
232          Prefer this occurrence to the currently recorded one.  We want
233          the last one in the block and the block is scanned from start
234          to end.  */
235       cur_occr->insn = insn;
236     }
237   else
238     {
239       /* First occurrence of this expression in this basic block.  */
240       cur_occr = GOBNEW (struct occr);
241       bytes_used += sizeof (struct occr);
242       cur_occr->insn = insn;
243       cur_occr->next = cur_expr->avail_occr;
244       cur_expr->avail_occr = cur_occr;
245     }
246 }
247
248 /* Determine whether the rtx X should be treated as a constant for CPROP.
249    Since X might be inserted more than once we have to take care that it
250    is sharable.  */
251
252 static bool
253 cprop_constant_p (const_rtx x)
254 {
255   return CONSTANT_P (x) && (GET_CODE (x) != CONST || shared_const_p (x));
256 }
257
258 /* Scan SET present in INSN and add an entry to the hash TABLE.  */
259
260 static void
261 hash_scan_set (rtx set, rtx insn, struct hash_table_d *table)
262 {
263   rtx src = SET_SRC (set);
264   rtx dest = SET_DEST (set);
265
266   if (REG_P (dest)
267       && ! HARD_REGISTER_P (dest)
268       && reg_available_p (dest, insn)
269       && can_copy_p (GET_MODE (dest)))
270     {
271       /* See if a REG_EQUAL note shows this equivalent to a simpler expression.
272
273          This allows us to do a single CPROP pass and still eliminate
274          redundant constants, addresses or other expressions that are
275          constructed with multiple instructions.
276
277          However, keep the original SRC if INSN is a simple reg-reg move.  In
278          In this case, there will almost always be a REG_EQUAL note on the
279          insn that sets SRC.  By recording the REG_EQUAL value here as SRC
280          for INSN, we miss copy propagation opportunities.
281
282          Note that this does not impede profitable constant propagations.  We
283          "look through" reg-reg sets in lookup_set.  */
284       rtx note = find_reg_equal_equiv_note (insn);
285       if (note != 0
286           && REG_NOTE_KIND (note) == REG_EQUAL
287           && !REG_P (src)
288           && cprop_constant_p (XEXP (note, 0)))
289         src = XEXP (note, 0), set = gen_rtx_SET (VOIDmode, dest, src);
290
291       /* Record sets for constant/copy propagation.  */
292       if ((REG_P (src)
293            && src != dest
294            && ! HARD_REGISTER_P (src)
295            && reg_available_p (src, insn))
296           || cprop_constant_p (src))
297         insert_set_in_table (dest, src, insn, table);
298     }
299 }
300
301 /* Process INSN and add hash table entries as appropriate.  */
302
303 static void
304 hash_scan_insn (rtx insn, struct hash_table_d *table)
305 {
306   rtx pat = PATTERN (insn);
307   int i;
308
309   /* Pick out the sets of INSN and for other forms of instructions record
310      what's been modified.  */
311
312   if (GET_CODE (pat) == SET)
313     hash_scan_set (pat, insn, table);
314   else if (GET_CODE (pat) == PARALLEL)
315     for (i = 0; i < XVECLEN (pat, 0); i++)
316       {
317         rtx x = XVECEXP (pat, 0, i);
318
319         if (GET_CODE (x) == SET)
320           hash_scan_set (x, insn, table);
321       }
322 }
323
324 /* Dump the hash table TABLE to file FILE under the name NAME.  */
325
326 static void
327 dump_hash_table (FILE *file, const char *name, struct hash_table_d *table)
328 {
329   int i;
330   /* Flattened out table, so it's printed in proper order.  */
331   struct expr **flat_table;
332   unsigned int *hash_val;
333   struct expr *expr;
334
335   flat_table = XCNEWVEC (struct expr *, table->n_elems);
336   hash_val = XNEWVEC (unsigned int, table->n_elems);
337
338   for (i = 0; i < (int) table->size; i++)
339     for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
340       {
341         flat_table[expr->bitmap_index] = expr;
342         hash_val[expr->bitmap_index] = i;
343       }
344
345   fprintf (file, "%s hash table (%d buckets, %d entries)\n",
346            name, table->size, table->n_elems);
347
348   for (i = 0; i < (int) table->n_elems; i++)
349     if (flat_table[i] != 0)
350       {
351         expr = flat_table[i];
352         fprintf (file, "Index %d (hash value %d)\n  ",
353                  expr->bitmap_index, hash_val[i]);
354         print_rtl (file, expr->dest);
355         fprintf (file, " := ");
356         print_rtl (file, expr->src);
357         fprintf (file, "\n");
358       }
359
360   fprintf (file, "\n");
361
362   free (flat_table);
363   free (hash_val);
364 }
365
366 /* Record as unavailable all registers that are DEF operands of INSN.  */
367
368 static void
369 make_set_regs_unavailable (rtx insn)
370 {
371   struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
372   df_ref *def_rec;
373
374   for (def_rec = DF_INSN_INFO_DEFS (insn_info); *def_rec; def_rec++)
375     SET_REGNO_REG_SET (reg_set_bitmap, DF_REF_REGNO (*def_rec));
376 }
377
378 /* Top level function to create an assignment hash table.
379
380    Assignment entries are placed in the hash table if
381    - they are of the form (set (pseudo-reg) src),
382    - src is something we want to perform const/copy propagation on,
383    - none of the operands or target are subsequently modified in the block
384
385    Currently src must be a pseudo-reg or a const_int.
386
387    TABLE is the table computed.  */
388
389 static void
390 compute_hash_table_work (struct hash_table_d *table)
391 {
392   basic_block bb;
393
394   /* Allocate vars to track sets of regs.  */
395   reg_set_bitmap = ALLOC_REG_SET (NULL);
396
397   FOR_EACH_BB (bb)
398     {
399       rtx insn;
400
401       /* Reset tables used to keep track of what's not yet invalid [since
402          the end of the block].  */
403       CLEAR_REG_SET (reg_set_bitmap);
404
405       /* Go over all insns from the last to the first.  This is convenient
406          for tracking available registers, i.e. not set between INSN and
407          the end of the basic block BB.  */
408       FOR_BB_INSNS_REVERSE (bb, insn)
409         {
410           /* Only real insns are interesting.  */
411           if (!NONDEBUG_INSN_P (insn))
412             continue;
413
414           /* Record interesting sets from INSN in the hash table.  */
415           hash_scan_insn (insn, table);
416
417           /* Any registers set in INSN will make SETs above it not AVAIL.  */
418           make_set_regs_unavailable (insn);
419         }
420
421       /* Insert implicit sets in the hash table, pretending they appear as
422          insns at the head of the basic block.  */
423       if (implicit_sets[bb->index] != NULL_RTX)
424         hash_scan_set (implicit_sets[bb->index], BB_HEAD (bb), table);
425     }
426
427   FREE_REG_SET (reg_set_bitmap);
428 }
429
430 /* Allocate space for the set/expr hash TABLE.
431    It is used to determine the number of buckets to use.  */
432
433 static void
434 alloc_hash_table (struct hash_table_d *table)
435 {
436   int n;
437
438   n = get_max_insn_count ();
439
440   table->size = n / 4;
441   if (table->size < 11)
442     table->size = 11;
443
444   /* Attempt to maintain efficient use of hash table.
445      Making it an odd number is simplest for now.
446      ??? Later take some measurements.  */
447   table->size |= 1;
448   n = table->size * sizeof (struct expr *);
449   table->table = XNEWVAR (struct expr *, n);
450 }
451
452 /* Free things allocated by alloc_hash_table.  */
453
454 static void
455 free_hash_table (struct hash_table_d *table)
456 {
457   free (table->table);
458 }
459
460 /* Compute the hash TABLE for doing copy/const propagation or
461    expression hash table.  */
462
463 static void
464 compute_hash_table (struct hash_table_d *table)
465 {
466   /* Initialize count of number of entries in hash table.  */
467   table->n_elems = 0;
468   memset (table->table, 0, table->size * sizeof (struct expr *));
469
470   compute_hash_table_work (table);
471 }
472 \f
473 /* Expression tracking support.  */
474
475 /* Lookup REGNO in the set TABLE.  The result is a pointer to the
476    table entry, or NULL if not found.  */
477
478 static struct expr *
479 lookup_set (unsigned int regno, struct hash_table_d *table)
480 {
481   unsigned int hash = hash_set (regno, table->size);
482   struct expr *expr;
483
484   expr = table->table[hash];
485
486   while (expr && REGNO (expr->dest) != regno)
487     expr = expr->next_same_hash;
488
489   return expr;
490 }
491
492 /* Return the next entry for REGNO in list EXPR.  */
493
494 static struct expr *
495 next_set (unsigned int regno, struct expr *expr)
496 {
497   do
498     expr = expr->next_same_hash;
499   while (expr && REGNO (expr->dest) != regno);
500
501   return expr;
502 }
503
504 /* Reset tables used to keep track of what's still available [since the
505    start of the block].  */
506
507 static void
508 reset_opr_set_tables (void)
509 {
510   /* Maintain a bitmap of which regs have been set since beginning of
511      the block.  */
512   CLEAR_REG_SET (reg_set_bitmap);
513 }
514
515 /* Return nonzero if the register X has not been set yet [since the
516    start of the basic block containing INSN].  */
517
518 static int
519 reg_not_set_p (const_rtx x, const_rtx insn ATTRIBUTE_UNUSED)
520 {
521   return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
522 }
523
524 /* Record things set by INSN.
525    This data is used by reg_not_set_p.  */
526
527 static void
528 mark_oprs_set (rtx insn)
529 {
530   struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
531   df_ref *def_rec;
532
533   for (def_rec = DF_INSN_INFO_DEFS (insn_info); *def_rec; def_rec++)
534     SET_REGNO_REG_SET (reg_set_bitmap, DF_REF_REGNO (*def_rec));
535 }
536 \f
537 /* Compute copy/constant propagation working variables.  */
538
539 /* Local properties of assignments.  */
540 static sbitmap *cprop_avloc;
541 static sbitmap *cprop_kill;
542
543 /* Global properties of assignments (computed from the local properties).  */
544 static sbitmap *cprop_avin;
545 static sbitmap *cprop_avout;
546
547 /* Allocate vars used for copy/const propagation.  N_BLOCKS is the number of
548    basic blocks.  N_SETS is the number of sets.  */
549
550 static void
551 alloc_cprop_mem (int n_blocks, int n_sets)
552 {
553   cprop_avloc = sbitmap_vector_alloc (n_blocks, n_sets);
554   cprop_kill = sbitmap_vector_alloc (n_blocks, n_sets);
555
556   cprop_avin = sbitmap_vector_alloc (n_blocks, n_sets);
557   cprop_avout = sbitmap_vector_alloc (n_blocks, n_sets);
558 }
559
560 /* Free vars used by copy/const propagation.  */
561
562 static void
563 free_cprop_mem (void)
564 {
565   sbitmap_vector_free (cprop_avloc);
566   sbitmap_vector_free (cprop_kill);
567   sbitmap_vector_free (cprop_avin);
568   sbitmap_vector_free (cprop_avout);
569 }
570
571 /* Compute the local properties of each recorded expression.
572
573    Local properties are those that are defined by the block, irrespective of
574    other blocks.
575
576    An expression is killed in a block if its operands, either DEST or SRC, are
577    modified in the block.
578
579    An expression is computed (locally available) in a block if it is computed
580    at least once and expression would contain the same value if the
581    computation was moved to the end of the block.
582
583    KILL and COMP are destination sbitmaps for recording local properties.  */
584
585 static void
586 compute_local_properties (sbitmap *kill, sbitmap *comp,
587                           struct hash_table_d *table)
588 {
589   unsigned int i;
590
591   /* Initialize the bitmaps that were passed in.  */
592   sbitmap_vector_zero (kill, last_basic_block);
593   sbitmap_vector_zero (comp, last_basic_block);
594
595   for (i = 0; i < table->size; i++)
596     {
597       struct expr *expr;
598
599       for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
600         {
601           int indx = expr->bitmap_index;
602           df_ref def;
603           struct occr *occr;
604
605           /* For each definition of the destination pseudo-reg, the expression
606              is killed in the block where the definition is.  */
607           for (def = DF_REG_DEF_CHAIN (REGNO (expr->dest));
608                def; def = DF_REF_NEXT_REG (def))
609             SET_BIT (kill[DF_REF_BB (def)->index], indx);
610
611           /* If the source is a pseudo-reg, for each definition of the source,
612              the expression is killed in the block where the definition is.  */
613           if (REG_P (expr->src))
614             for (def = DF_REG_DEF_CHAIN (REGNO (expr->src));
615                  def; def = DF_REF_NEXT_REG (def))
616               SET_BIT (kill[DF_REF_BB (def)->index], indx);
617
618           /* The occurrences recorded in avail_occr are exactly those that
619              are locally available in the block where they are.  */
620           for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
621             {
622               SET_BIT (comp[BLOCK_FOR_INSN (occr->insn)->index], indx);
623             }
624         }
625     }
626 }
627 \f
628 /* Hash table support.  */
629
630 /* Top level routine to do the dataflow analysis needed by copy/const
631    propagation.  */
632
633 static void
634 compute_cprop_data (void)
635 {
636   compute_local_properties (cprop_kill, cprop_avloc, &set_hash_table);
637   compute_available (cprop_avloc, cprop_kill, cprop_avout, cprop_avin);
638 }
639 \f
640 /* Copy/constant propagation.  */
641
642 /* Maximum number of register uses in an insn that we handle.  */
643 #define MAX_USES 8
644
645 /* Table of uses (registers, both hard and pseudo) found in an insn.
646    Allocated statically to avoid alloc/free complexity and overhead.  */
647 static rtx reg_use_table[MAX_USES];
648
649 /* Index into `reg_use_table' while building it.  */
650 static unsigned reg_use_count;
651
652 /* Set up a list of register numbers used in INSN.  The found uses are stored
653    in `reg_use_table'.  `reg_use_count' is initialized to zero before entry,
654    and contains the number of uses in the table upon exit.
655
656    ??? If a register appears multiple times we will record it multiple times.
657    This doesn't hurt anything but it will slow things down.  */
658
659 static void
660 find_used_regs (rtx *xptr, void *data ATTRIBUTE_UNUSED)
661 {
662   int i, j;
663   enum rtx_code code;
664   const char *fmt;
665   rtx x = *xptr;
666
667   /* repeat is used to turn tail-recursion into iteration since GCC
668      can't do it when there's no return value.  */
669  repeat:
670   if (x == 0)
671     return;
672
673   code = GET_CODE (x);
674   if (REG_P (x))
675     {
676       if (reg_use_count == MAX_USES)
677         return;
678
679       reg_use_table[reg_use_count] = x;
680       reg_use_count++;
681     }
682
683   /* Recursively scan the operands of this expression.  */
684
685   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
686     {
687       if (fmt[i] == 'e')
688         {
689           /* If we are about to do the last recursive call
690              needed at this level, change it into iteration.
691              This function is called enough to be worth it.  */
692           if (i == 0)
693             {
694               x = XEXP (x, 0);
695               goto repeat;
696             }
697
698           find_used_regs (&XEXP (x, i), data);
699         }
700       else if (fmt[i] == 'E')
701         for (j = 0; j < XVECLEN (x, i); j++)
702           find_used_regs (&XVECEXP (x, i, j), data);
703     }
704 }
705
706 /* Try to replace all uses of FROM in INSN with TO.
707    Return nonzero if successful.  */
708
709 static int
710 try_replace_reg (rtx from, rtx to, rtx insn)
711 {
712   rtx note = find_reg_equal_equiv_note (insn);
713   rtx src = 0;
714   int success = 0;
715   rtx set = single_set (insn);
716
717   /* Usually we substitute easy stuff, so we won't copy everything.
718      We however need to take care to not duplicate non-trivial CONST
719      expressions.  */
720   to = copy_rtx (to);
721
722   validate_replace_src_group (from, to, insn);
723   if (num_changes_pending () && apply_change_group ())
724     success = 1;
725
726   /* Try to simplify SET_SRC if we have substituted a constant.  */
727   if (success && set && CONSTANT_P (to))
728     {
729       src = simplify_rtx (SET_SRC (set));
730
731       if (src)
732         validate_change (insn, &SET_SRC (set), src, 0);
733     }
734
735   /* If there is already a REG_EQUAL note, update the expression in it
736      with our replacement.  */
737   if (note != 0 && REG_NOTE_KIND (note) == REG_EQUAL)
738     set_unique_reg_note (insn, REG_EQUAL,
739                          simplify_replace_rtx (XEXP (note, 0), from, to));
740   if (!success && set && reg_mentioned_p (from, SET_SRC (set)))
741     {
742       /* If above failed and this is a single set, try to simplify the source
743          of the set given our substitution.  We could perhaps try this for
744          multiple SETs, but it probably won't buy us anything.  */
745       src = simplify_replace_rtx (SET_SRC (set), from, to);
746
747       if (!rtx_equal_p (src, SET_SRC (set))
748           && validate_change (insn, &SET_SRC (set), src, 0))
749         success = 1;
750
751       /* If we've failed perform the replacement, have a single SET to
752          a REG destination and don't yet have a note, add a REG_EQUAL note
753          to not lose information.  */
754       if (!success && note == 0 && set != 0 && REG_P (SET_DEST (set)))
755         note = set_unique_reg_note (insn, REG_EQUAL, copy_rtx (src));
756     }
757
758   if (set && MEM_P (SET_DEST (set)) && reg_mentioned_p (from, SET_DEST (set)))
759     {
760       /* Registers can also appear as uses in SET_DEST if it is a MEM.
761          We could perhaps try this for multiple SETs, but it probably
762          won't buy us anything.  */
763       rtx dest = simplify_replace_rtx (SET_DEST (set), from, to);
764
765       if (!rtx_equal_p (dest, SET_DEST (set))
766           && validate_change (insn, &SET_DEST (set), dest, 0))
767         success = 1;
768     }
769
770   /* REG_EQUAL may get simplified into register.
771      We don't allow that. Remove that note. This code ought
772      not to happen, because previous code ought to synthesize
773      reg-reg move, but be on the safe side.  */
774   if (note && REG_NOTE_KIND (note) == REG_EQUAL && REG_P (XEXP (note, 0)))
775     remove_note (insn, note);
776
777   return success;
778 }
779
780 /* Find a set of REGNOs that are available on entry to INSN's block.  Return
781    NULL no such set is found.  */
782
783 static struct expr *
784 find_avail_set (int regno, rtx insn)
785 {
786   /* SET1 contains the last set found that can be returned to the caller for
787      use in a substitution.  */
788   struct expr *set1 = 0;
789
790   /* Loops are not possible here.  To get a loop we would need two sets
791      available at the start of the block containing INSN.  i.e. we would
792      need two sets like this available at the start of the block:
793
794        (set (reg X) (reg Y))
795        (set (reg Y) (reg X))
796
797      This can not happen since the set of (reg Y) would have killed the
798      set of (reg X) making it unavailable at the start of this block.  */
799   while (1)
800     {
801       rtx src;
802       struct expr *set = lookup_set (regno, &set_hash_table);
803
804       /* Find a set that is available at the start of the block
805          which contains INSN.  */
806       while (set)
807         {
808           if (TEST_BIT (cprop_avin[BLOCK_FOR_INSN (insn)->index],
809                         set->bitmap_index))
810             break;
811           set = next_set (regno, set);
812         }
813
814       /* If no available set was found we've reached the end of the
815          (possibly empty) copy chain.  */
816       if (set == 0)
817         break;
818
819       src = set->src;
820
821       /* We know the set is available.
822          Now check that SRC is locally anticipatable (i.e. none of the
823          source operands have changed since the start of the block).
824
825          If the source operand changed, we may still use it for the next
826          iteration of this loop, but we may not use it for substitutions.  */
827
828       if (cprop_constant_p (src) || reg_not_set_p (src, insn))
829         set1 = set;
830
831       /* If the source of the set is anything except a register, then
832          we have reached the end of the copy chain.  */
833       if (! REG_P (src))
834         break;
835
836       /* Follow the copy chain, i.e. start another iteration of the loop
837          and see if we have an available copy into SRC.  */
838       regno = REGNO (src);
839     }
840
841   /* SET1 holds the last set that was available and anticipatable at
842      INSN.  */
843   return set1;
844 }
845
846 /* Subroutine of cprop_insn that tries to propagate constants into
847    JUMP_INSNS.  JUMP must be a conditional jump.  If SETCC is non-NULL
848    it is the instruction that immediately precedes JUMP, and must be a
849    single SET of a register.  FROM is what we will try to replace,
850    SRC is the constant we will try to substitute for it.  Return nonzero
851    if a change was made.  */
852
853 static int
854 cprop_jump (basic_block bb, rtx setcc, rtx jump, rtx from, rtx src)
855 {
856   rtx new_rtx, set_src, note_src;
857   rtx set = pc_set (jump);
858   rtx note = find_reg_equal_equiv_note (jump);
859
860   if (note)
861     {
862       note_src = XEXP (note, 0);
863       if (GET_CODE (note_src) == EXPR_LIST)
864         note_src = NULL_RTX;
865     }
866   else note_src = NULL_RTX;
867
868   /* Prefer REG_EQUAL notes except those containing EXPR_LISTs.  */
869   set_src = note_src ? note_src : SET_SRC (set);
870
871   /* First substitute the SETCC condition into the JUMP instruction,
872      then substitute that given values into this expanded JUMP.  */
873   if (setcc != NULL_RTX
874       && !modified_between_p (from, setcc, jump)
875       && !modified_between_p (src, setcc, jump))
876     {
877       rtx setcc_src;
878       rtx setcc_set = single_set (setcc);
879       rtx setcc_note = find_reg_equal_equiv_note (setcc);
880       setcc_src = (setcc_note && GET_CODE (XEXP (setcc_note, 0)) != EXPR_LIST)
881                 ? XEXP (setcc_note, 0) : SET_SRC (setcc_set);
882       set_src = simplify_replace_rtx (set_src, SET_DEST (setcc_set),
883                                       setcc_src);
884     }
885   else
886     setcc = NULL_RTX;
887
888   new_rtx = simplify_replace_rtx (set_src, from, src);
889
890   /* If no simplification can be made, then try the next register.  */
891   if (rtx_equal_p (new_rtx, SET_SRC (set)))
892     return 0;
893
894   /* If this is now a no-op delete it, otherwise this must be a valid insn.  */
895   if (new_rtx == pc_rtx)
896     delete_insn (jump);
897   else
898     {
899       /* Ensure the value computed inside the jump insn to be equivalent
900          to one computed by setcc.  */
901       if (setcc && modified_in_p (new_rtx, setcc))
902         return 0;
903       if (! validate_unshare_change (jump, &SET_SRC (set), new_rtx, 0))
904         {
905           /* When (some) constants are not valid in a comparison, and there
906              are two registers to be replaced by constants before the entire
907              comparison can be folded into a constant, we need to keep
908              intermediate information in REG_EQUAL notes.  For targets with
909              separate compare insns, such notes are added by try_replace_reg.
910              When we have a combined compare-and-branch instruction, however,
911              we need to attach a note to the branch itself to make this
912              optimization work.  */
913
914           if (!rtx_equal_p (new_rtx, note_src))
915             set_unique_reg_note (jump, REG_EQUAL, copy_rtx (new_rtx));
916           return 0;
917         }
918
919       /* Remove REG_EQUAL note after simplification.  */
920       if (note_src)
921         remove_note (jump, note);
922      }
923
924 #ifdef HAVE_cc0
925   /* Delete the cc0 setter.  */
926   if (setcc != NULL && CC0_P (SET_DEST (single_set (setcc))))
927     delete_insn (setcc);
928 #endif
929
930   global_const_prop_count++;
931   if (dump_file != NULL)
932     {
933       fprintf (dump_file,
934                "GLOBAL CONST-PROP: Replacing reg %d in jump_insn %d with"
935                "constant ", REGNO (from), INSN_UID (jump));
936       print_rtl (dump_file, src);
937       fprintf (dump_file, "\n");
938     }
939   purge_dead_edges (bb);
940
941   /* If a conditional jump has been changed into unconditional jump, remove
942      the jump and make the edge fallthru - this is always called in
943      cfglayout mode.  */
944   if (new_rtx != pc_rtx && simplejump_p (jump))
945     {
946       edge e;
947       edge_iterator ei;
948
949       FOR_EACH_EDGE (e, ei, bb->succs)
950         if (e->dest != EXIT_BLOCK_PTR
951             && BB_HEAD (e->dest) == JUMP_LABEL (jump))
952           {
953             e->flags |= EDGE_FALLTHRU;
954             break;
955           }
956       delete_insn (jump);
957     }
958
959   return 1;
960 }
961
962 /* Subroutine of cprop_insn that tries to propagate constants.  FROM is what
963    we will try to replace, SRC is the constant we will try to substitute for
964    it and INSN is the instruction where this will be happening.  */
965
966 static int
967 constprop_register (rtx from, rtx src, rtx insn)
968 {
969   rtx sset;
970
971   /* Check for reg or cc0 setting instructions followed by
972      conditional branch instructions first.  */
973   if ((sset = single_set (insn)) != NULL
974       && NEXT_INSN (insn)
975       && any_condjump_p (NEXT_INSN (insn)) && onlyjump_p (NEXT_INSN (insn)))
976     {
977       rtx dest = SET_DEST (sset);
978       if ((REG_P (dest) || CC0_P (dest))
979           && cprop_jump (BLOCK_FOR_INSN (insn), insn, NEXT_INSN (insn),
980                          from, src))
981         return 1;
982     }
983
984   /* Handle normal insns next.  */
985   if (NONJUMP_INSN_P (insn) && try_replace_reg (from, src, insn))
986     return 1;
987
988   /* Try to propagate a CONST_INT into a conditional jump.
989      We're pretty specific about what we will handle in this
990      code, we can extend this as necessary over time.
991
992      Right now the insn in question must look like
993      (set (pc) (if_then_else ...))  */
994   else if (any_condjump_p (insn) && onlyjump_p (insn))
995     return cprop_jump (BLOCK_FOR_INSN (insn), NULL, insn, from, src);
996   return 0;
997 }
998
999 /* Perform constant and copy propagation on INSN.
1000    Return nonzero if a change was made.  */
1001
1002 static int
1003 cprop_insn (rtx insn)
1004 {
1005   unsigned i;
1006   int changed = 0, changed_this_round;
1007   rtx note;
1008
1009 retry:
1010   changed_this_round = 0;
1011   reg_use_count = 0;
1012   note_uses (&PATTERN (insn), find_used_regs, NULL);
1013
1014   /* We may win even when propagating constants into notes.  */
1015   note = find_reg_equal_equiv_note (insn);
1016   if (note)
1017     find_used_regs (&XEXP (note, 0), NULL);
1018
1019   for (i = 0; i < reg_use_count; i++)
1020     {
1021       rtx reg_used = reg_use_table[i];
1022       unsigned int regno = REGNO (reg_used);
1023       rtx src;
1024       struct expr *set;
1025
1026       /* If the register has already been set in this block, there's
1027          nothing we can do.  */
1028       if (! reg_not_set_p (reg_used, insn))
1029         continue;
1030
1031       /* Find an assignment that sets reg_used and is available
1032          at the start of the block.  */
1033       set = find_avail_set (regno, insn);
1034       if (! set)
1035         continue;
1036
1037       src = set->src;
1038
1039       /* Constant propagation.  */
1040       if (cprop_constant_p (src))
1041         {
1042           if (constprop_register (reg_used, src, insn))
1043             {
1044               changed_this_round = changed = 1;
1045               global_const_prop_count++;
1046               if (dump_file != NULL)
1047                 {
1048                   fprintf (dump_file,
1049                            "GLOBAL CONST-PROP: Replacing reg %d in ", regno);
1050                   fprintf (dump_file, "insn %d with constant ",
1051                            INSN_UID (insn));
1052                   print_rtl (dump_file, src);
1053                   fprintf (dump_file, "\n");
1054                 }
1055               if (INSN_DELETED_P (insn))
1056                 return 1;
1057             }
1058         }
1059       else if (REG_P (src)
1060                && REGNO (src) >= FIRST_PSEUDO_REGISTER
1061                && REGNO (src) != regno)
1062         {
1063           if (try_replace_reg (reg_used, src, insn))
1064             {
1065               changed_this_round = changed = 1;
1066               global_copy_prop_count++;
1067               if (dump_file != NULL)
1068                 {
1069                   fprintf (dump_file,
1070                            "GLOBAL COPY-PROP: Replacing reg %d in insn %d",
1071                            regno, INSN_UID (insn));
1072                   fprintf (dump_file, " with reg %d\n", REGNO (src));
1073                 }
1074
1075               /* The original insn setting reg_used may or may not now be
1076                  deletable.  We leave the deletion to DCE.  */
1077               /* FIXME: If it turns out that the insn isn't deletable,
1078                  then we may have unnecessarily extended register lifetimes
1079                  and made things worse.  */
1080             }
1081         }
1082
1083       /* If try_replace_reg simplified the insn, the regs found
1084          by find_used_regs may not be valid anymore.  Start over.  */
1085       if (changed_this_round)
1086         goto retry;
1087     }
1088
1089   if (changed && DEBUG_INSN_P (insn))
1090     return 0;
1091
1092   return changed;
1093 }
1094
1095 /* Like find_used_regs, but avoid recording uses that appear in
1096    input-output contexts such as zero_extract or pre_dec.  This
1097    restricts the cases we consider to those for which local cprop
1098    can legitimately make replacements.  */
1099
1100 static void
1101 local_cprop_find_used_regs (rtx *xptr, void *data)
1102 {
1103   rtx x = *xptr;
1104
1105   if (x == 0)
1106     return;
1107
1108   switch (GET_CODE (x))
1109     {
1110     case ZERO_EXTRACT:
1111     case SIGN_EXTRACT:
1112     case STRICT_LOW_PART:
1113       return;
1114
1115     case PRE_DEC:
1116     case PRE_INC:
1117     case POST_DEC:
1118     case POST_INC:
1119     case PRE_MODIFY:
1120     case POST_MODIFY:
1121       /* Can only legitimately appear this early in the context of
1122          stack pushes for function arguments, but handle all of the
1123          codes nonetheless.  */
1124       return;
1125
1126     case SUBREG:
1127       /* Setting a subreg of a register larger than word_mode leaves
1128          the non-written words unchanged.  */
1129       if (GET_MODE_BITSIZE (GET_MODE (SUBREG_REG (x))) > BITS_PER_WORD)
1130         return;
1131       break;
1132
1133     default:
1134       break;
1135     }
1136
1137   find_used_regs (xptr, data);
1138 }
1139
1140 /* Try to perform local const/copy propagation on X in INSN.  */
1141
1142 static bool
1143 do_local_cprop (rtx x, rtx insn)
1144 {
1145   rtx newreg = NULL, newcnst = NULL;
1146
1147   /* Rule out USE instructions and ASM statements as we don't want to
1148      change the hard registers mentioned.  */
1149   if (REG_P (x)
1150       && (REGNO (x) >= FIRST_PSEUDO_REGISTER
1151           || (GET_CODE (PATTERN (insn)) != USE
1152               && asm_noperands (PATTERN (insn)) < 0)))
1153     {
1154       cselib_val *val = cselib_lookup (x, GET_MODE (x), 0, VOIDmode);
1155       struct elt_loc_list *l;
1156
1157       if (!val)
1158         return false;
1159       for (l = val->locs; l; l = l->next)
1160         {
1161           rtx this_rtx = l->loc;
1162           rtx note;
1163
1164           if (cprop_constant_p (this_rtx))
1165             newcnst = this_rtx;
1166           if (REG_P (this_rtx) && REGNO (this_rtx) >= FIRST_PSEUDO_REGISTER
1167               /* Don't copy propagate if it has attached REG_EQUIV note.
1168                  At this point this only function parameters should have
1169                  REG_EQUIV notes and if the argument slot is used somewhere
1170                  explicitly, it means address of parameter has been taken,
1171                  so we should not extend the lifetime of the pseudo.  */
1172               && (!(note = find_reg_note (l->setting_insn, REG_EQUIV, NULL_RTX))
1173                   || ! MEM_P (XEXP (note, 0))))
1174             newreg = this_rtx;
1175         }
1176       if (newcnst && constprop_register (x, newcnst, insn))
1177         {
1178           if (dump_file != NULL)
1179             {
1180               fprintf (dump_file, "LOCAL CONST-PROP: Replacing reg %d in ",
1181                        REGNO (x));
1182               fprintf (dump_file, "insn %d with constant ",
1183                        INSN_UID (insn));
1184               print_rtl (dump_file, newcnst);
1185               fprintf (dump_file, "\n");
1186             }
1187           local_const_prop_count++;
1188           return true;
1189         }
1190       else if (newreg && newreg != x && try_replace_reg (x, newreg, insn))
1191         {
1192           if (dump_file != NULL)
1193             {
1194               fprintf (dump_file,
1195                        "LOCAL COPY-PROP: Replacing reg %d in insn %d",
1196                        REGNO (x), INSN_UID (insn));
1197               fprintf (dump_file, " with reg %d\n", REGNO (newreg));
1198             }
1199           local_copy_prop_count++;
1200           return true;
1201         }
1202     }
1203   return false;
1204 }
1205
1206 /* Do local const/copy propagation (i.e. within each basic block).  */
1207
1208 static int
1209 local_cprop_pass (void)
1210 {
1211   basic_block bb;
1212   rtx insn;
1213   bool changed = false;
1214   unsigned i;
1215
1216   cselib_init (0);
1217   FOR_EACH_BB (bb)
1218     {
1219       FOR_BB_INSNS (bb, insn)
1220         {
1221           if (INSN_P (insn))
1222             {
1223               rtx note = find_reg_equal_equiv_note (insn);
1224               do
1225                 {
1226                   reg_use_count = 0;
1227                   note_uses (&PATTERN (insn), local_cprop_find_used_regs,
1228                              NULL);
1229                   if (note)
1230                     local_cprop_find_used_regs (&XEXP (note, 0), NULL);
1231
1232                   for (i = 0; i < reg_use_count; i++)
1233                     {
1234                       if (do_local_cprop (reg_use_table[i], insn))
1235                         {
1236                           if (!DEBUG_INSN_P (insn))
1237                             changed = true;
1238                           break;
1239                         }
1240                     }
1241                   if (INSN_DELETED_P (insn))
1242                     break;
1243                 }
1244               while (i < reg_use_count);
1245             }
1246           cselib_process_insn (insn);
1247         }
1248
1249       /* Forget everything at the end of a basic block.  */
1250       cselib_clear_table ();
1251     }
1252
1253   cselib_finish ();
1254
1255   return changed;
1256 }
1257
1258 /* Similar to get_condition, only the resulting condition must be
1259    valid at JUMP, instead of at EARLIEST.
1260
1261    This differs from noce_get_condition in ifcvt.c in that we prefer not to
1262    settle for the condition variable in the jump instruction being integral.
1263    We prefer to be able to record the value of a user variable, rather than
1264    the value of a temporary used in a condition.  This could be solved by
1265    recording the value of *every* register scanned by canonicalize_condition,
1266    but this would require some code reorganization.  */
1267
1268 rtx
1269 fis_get_condition (rtx jump)
1270 {
1271   return get_condition (jump, NULL, false, true);
1272 }
1273
1274 /* Check the comparison COND to see if we can safely form an implicit
1275    set from it.  */
1276
1277 static bool
1278 implicit_set_cond_p (const_rtx cond)
1279 {
1280   enum machine_mode mode;
1281   rtx cst;
1282
1283   /* COND must be either an EQ or NE comparison.  */
1284   if (GET_CODE (cond) != EQ && GET_CODE (cond) != NE)
1285     return false;
1286
1287   /* The first operand of COND must be a pseudo-reg.  */
1288   if (! REG_P (XEXP (cond, 0))
1289       || HARD_REGISTER_P (XEXP (cond, 0)))
1290     return false;
1291
1292   /* The second operand of COND must be a suitable constant.  */
1293   mode = GET_MODE (XEXP (cond, 0));
1294   cst = XEXP (cond, 1);
1295
1296   /* We can't perform this optimization if either operand might be or might
1297      contain a signed zero.  */
1298   if (HONOR_SIGNED_ZEROS (mode))
1299     {
1300       /* It is sufficient to check if CST is or contains a zero.  We must
1301          handle float, complex, and vector.  If any subpart is a zero, then
1302          the optimization can't be performed.  */
1303       /* ??? The complex and vector checks are not implemented yet.  We just
1304          always return zero for them.  */
1305       if (GET_CODE (cst) == CONST_DOUBLE)
1306         {
1307           REAL_VALUE_TYPE d;
1308           REAL_VALUE_FROM_CONST_DOUBLE (d, cst);
1309           if (REAL_VALUES_EQUAL (d, dconst0))
1310             return 0;
1311         }
1312       else
1313         return 0;
1314     }
1315
1316   return cprop_constant_p (cst);
1317 }
1318
1319 /* Find the implicit sets of a function.  An "implicit set" is a constraint
1320    on the value of a variable, implied by a conditional jump.  For example,
1321    following "if (x == 2)", the then branch may be optimized as though the
1322    conditional performed an "explicit set", in this example, "x = 2".  This
1323    function records the set patterns that are implicit at the start of each
1324    basic block.
1325
1326    If an implicit set is found but the set is implicit on a critical edge,
1327    this critical edge is split.
1328
1329    Return true if the CFG was modified, false otherwise.  */
1330
1331 static bool
1332 find_implicit_sets (void)
1333 {
1334   basic_block bb, dest;
1335   rtx cond, new_rtx;
1336   unsigned int count = 0;
1337   bool edges_split = false;
1338   size_t implicit_sets_size = last_basic_block + 10;
1339
1340   implicit_sets = XCNEWVEC (rtx, implicit_sets_size);
1341
1342   FOR_EACH_BB (bb)
1343     {
1344       /* Check for more than one successor.  */
1345       if (EDGE_COUNT (bb->succs) <= 1)
1346         continue;
1347
1348       cond = fis_get_condition (BB_END (bb));
1349
1350       /* If no condition is found or if it isn't of a suitable form,
1351          ignore it.  */
1352       if (! cond || ! implicit_set_cond_p (cond))
1353         continue;
1354
1355       dest = GET_CODE (cond) == EQ
1356         ? BRANCH_EDGE (bb)->dest : FALLTHRU_EDGE (bb)->dest;
1357
1358       /* If DEST doesn't go anywhere, ignore it.  */
1359       if (! dest || dest == EXIT_BLOCK_PTR)
1360         continue;
1361
1362       /* We have found a suitable implicit set.  Try to record it now as
1363          a SET in DEST.  If DEST has more than one predecessor, the edge
1364          between BB and DEST is a critical edge and we must split it,
1365          because we can only record one implicit set per DEST basic block.  */
1366       if (! single_pred_p (dest))
1367         {
1368           dest = split_edge (find_edge (bb, dest));
1369           edges_split = true;
1370         }
1371
1372       if (implicit_sets_size <= (size_t) dest->index)
1373       {
1374         size_t old_implicit_sets_size = implicit_sets_size;
1375         implicit_sets_size *= 2;
1376         implicit_sets = XRESIZEVEC (rtx, implicit_sets, implicit_sets_size);
1377         memset (implicit_sets + old_implicit_sets_size, 0,
1378                 (implicit_sets_size - old_implicit_sets_size) * sizeof (rtx));
1379       }
1380
1381       new_rtx = gen_rtx_SET (VOIDmode, XEXP (cond, 0),
1382                              XEXP (cond, 1));
1383       implicit_sets[dest->index] = new_rtx;
1384       if (dump_file)
1385         {
1386           fprintf(dump_file, "Implicit set of reg %d in ",
1387                   REGNO (XEXP (cond, 0)));
1388           fprintf(dump_file, "basic block %d\n", dest->index);
1389         }
1390       count++;
1391     }
1392
1393   if (dump_file)
1394     fprintf (dump_file, "Found %d implicit sets\n", count);
1395
1396   /* Confess our sins.  */
1397   return edges_split;
1398 }
1399
1400 /* Bypass conditional jumps.  */
1401
1402 /* The value of last_basic_block at the beginning of the jump_bypass
1403    pass.  The use of redirect_edge_and_branch_force may introduce new
1404    basic blocks, but the data flow analysis is only valid for basic
1405    block indices less than bypass_last_basic_block.  */
1406
1407 static int bypass_last_basic_block;
1408
1409 /* Find a set of REGNO to a constant that is available at the end of basic
1410    block BB.  Return NULL if no such set is found.  Based heavily upon
1411    find_avail_set.  */
1412
1413 static struct expr *
1414 find_bypass_set (int regno, int bb)
1415 {
1416   struct expr *result = 0;
1417
1418   for (;;)
1419     {
1420       rtx src;
1421       struct expr *set = lookup_set (regno, &set_hash_table);
1422
1423       while (set)
1424         {
1425           if (TEST_BIT (cprop_avout[bb], set->bitmap_index))
1426             break;
1427           set = next_set (regno, set);
1428         }
1429
1430       if (set == 0)
1431         break;
1432
1433       src = set->src;
1434       if (cprop_constant_p (src))
1435         result = set;
1436
1437       if (! REG_P (src))
1438         break;
1439
1440       regno = REGNO (src);
1441     }
1442   return result;
1443 }
1444
1445 /* Subroutine of bypass_block that checks whether a pseudo is killed by
1446    any of the instructions inserted on an edge.  Jump bypassing places
1447    condition code setters on CFG edges using insert_insn_on_edge.  This
1448    function is required to check that our data flow analysis is still
1449    valid prior to commit_edge_insertions.  */
1450
1451 static bool
1452 reg_killed_on_edge (const_rtx reg, const_edge e)
1453 {
1454   rtx insn;
1455
1456   for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
1457     if (INSN_P (insn) && reg_set_p (reg, insn))
1458       return true;
1459
1460   return false;
1461 }
1462
1463 /* Subroutine of bypass_conditional_jumps that attempts to bypass the given
1464    basic block BB which has more than one predecessor.  If not NULL, SETCC
1465    is the first instruction of BB, which is immediately followed by JUMP_INSN
1466    JUMP.  Otherwise, SETCC is NULL, and JUMP is the first insn of BB.
1467    Returns nonzero if a change was made.
1468
1469    During the jump bypassing pass, we may place copies of SETCC instructions
1470    on CFG edges.  The following routine must be careful to pay attention to
1471    these inserted insns when performing its transformations.  */
1472
1473 static int
1474 bypass_block (basic_block bb, rtx setcc, rtx jump)
1475 {
1476   rtx insn, note;
1477   edge e, edest;
1478   int change;
1479   int may_be_loop_header;
1480   unsigned removed_p;
1481   unsigned i;
1482   edge_iterator ei;
1483
1484   insn = (setcc != NULL) ? setcc : jump;
1485
1486   /* Determine set of register uses in INSN.  */
1487   reg_use_count = 0;
1488   note_uses (&PATTERN (insn), find_used_regs, NULL);
1489   note = find_reg_equal_equiv_note (insn);
1490   if (note)
1491     find_used_regs (&XEXP (note, 0), NULL);
1492
1493   may_be_loop_header = false;
1494   FOR_EACH_EDGE (e, ei, bb->preds)
1495     if (e->flags & EDGE_DFS_BACK)
1496       {
1497         may_be_loop_header = true;
1498         break;
1499       }
1500
1501   change = 0;
1502   for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
1503     {
1504       removed_p = 0;
1505
1506       if (e->flags & EDGE_COMPLEX)
1507         {
1508           ei_next (&ei);
1509           continue;
1510         }
1511
1512       /* We can't redirect edges from new basic blocks.  */
1513       if (e->src->index >= bypass_last_basic_block)
1514         {
1515           ei_next (&ei);
1516           continue;
1517         }
1518
1519       /* The irreducible loops created by redirecting of edges entering the
1520          loop from outside would decrease effectiveness of some of the
1521          following optimizations, so prevent this.  */
1522       if (may_be_loop_header
1523           && !(e->flags & EDGE_DFS_BACK))
1524         {
1525           ei_next (&ei);
1526           continue;
1527         }
1528
1529       for (i = 0; i < reg_use_count; i++)
1530         {
1531           rtx reg_used = reg_use_table[i];
1532           unsigned int regno = REGNO (reg_used);
1533           basic_block dest, old_dest;
1534           struct expr *set;
1535           rtx src, new_rtx;
1536
1537           set = find_bypass_set (regno, e->src->index);
1538
1539           if (! set)
1540             continue;
1541
1542           /* Check the data flow is valid after edge insertions.  */
1543           if (e->insns.r && reg_killed_on_edge (reg_used, e))
1544             continue;
1545
1546           src = SET_SRC (pc_set (jump));
1547
1548           if (setcc != NULL)
1549             src = simplify_replace_rtx (src,
1550                                         SET_DEST (PATTERN (setcc)),
1551                                         SET_SRC (PATTERN (setcc)));
1552
1553           new_rtx = simplify_replace_rtx (src, reg_used, set->src);
1554
1555           /* Jump bypassing may have already placed instructions on
1556              edges of the CFG.  We can't bypass an outgoing edge that
1557              has instructions associated with it, as these insns won't
1558              get executed if the incoming edge is redirected.  */
1559           if (new_rtx == pc_rtx)
1560             {
1561               edest = FALLTHRU_EDGE (bb);
1562               dest = edest->insns.r ? NULL : edest->dest;
1563             }
1564           else if (GET_CODE (new_rtx) == LABEL_REF)
1565             {
1566               dest = BLOCK_FOR_INSN (XEXP (new_rtx, 0));
1567               /* Don't bypass edges containing instructions.  */
1568               edest = find_edge (bb, dest);
1569               if (edest && edest->insns.r)
1570                 dest = NULL;
1571             }
1572           else
1573             dest = NULL;
1574
1575           /* Avoid unification of the edge with other edges from original
1576              branch.  We would end up emitting the instruction on "both"
1577              edges.  */
1578           if (dest && setcc && !CC0_P (SET_DEST (PATTERN (setcc)))
1579               && find_edge (e->src, dest))
1580             dest = NULL;
1581
1582           old_dest = e->dest;
1583           if (dest != NULL
1584               && dest != old_dest
1585               && dest != EXIT_BLOCK_PTR)
1586             {
1587               redirect_edge_and_branch_force (e, dest);
1588
1589               /* Copy the register setter to the redirected edge.
1590                  Don't copy CC0 setters, as CC0 is dead after jump.  */
1591               if (setcc)
1592                 {
1593                   rtx pat = PATTERN (setcc);
1594                   if (!CC0_P (SET_DEST (pat)))
1595                     insert_insn_on_edge (copy_insn (pat), e);
1596                 }
1597
1598               if (dump_file != NULL)
1599                 {
1600                   fprintf (dump_file, "JUMP-BYPASS: Proved reg %d "
1601                                       "in jump_insn %d equals constant ",
1602                            regno, INSN_UID (jump));
1603                   print_rtl (dump_file, set->src);
1604                   fprintf (dump_file, "\nBypass edge from %d->%d to %d\n",
1605                            e->src->index, old_dest->index, dest->index);
1606                 }
1607               change = 1;
1608               removed_p = 1;
1609               break;
1610             }
1611         }
1612       if (!removed_p)
1613         ei_next (&ei);
1614     }
1615   return change;
1616 }
1617
1618 /* Find basic blocks with more than one predecessor that only contain a
1619    single conditional jump.  If the result of the comparison is known at
1620    compile-time from any incoming edge, redirect that edge to the
1621    appropriate target.  Return nonzero if a change was made.
1622
1623    This function is now mis-named, because we also handle indirect jumps.  */
1624
1625 static int
1626 bypass_conditional_jumps (void)
1627 {
1628   basic_block bb;
1629   int changed;
1630   rtx setcc;
1631   rtx insn;
1632   rtx dest;
1633
1634   /* Note we start at block 1.  */
1635   if (ENTRY_BLOCK_PTR->next_bb == EXIT_BLOCK_PTR)
1636     return 0;
1637
1638   bypass_last_basic_block = last_basic_block;
1639   mark_dfs_back_edges ();
1640
1641   changed = 0;
1642   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb,
1643                   EXIT_BLOCK_PTR, next_bb)
1644     {
1645       /* Check for more than one predecessor.  */
1646       if (!single_pred_p (bb))
1647         {
1648           setcc = NULL_RTX;
1649           FOR_BB_INSNS (bb, insn)
1650             if (DEBUG_INSN_P (insn))
1651               continue;
1652             else if (NONJUMP_INSN_P (insn))
1653               {
1654                 if (setcc)
1655                   break;
1656                 if (GET_CODE (PATTERN (insn)) != SET)
1657                   break;
1658
1659                 dest = SET_DEST (PATTERN (insn));
1660                 if (REG_P (dest) || CC0_P (dest))
1661                   setcc = insn;
1662                 else
1663                   break;
1664               }
1665             else if (JUMP_P (insn))
1666               {
1667                 if ((any_condjump_p (insn) || computed_jump_p (insn))
1668                     && onlyjump_p (insn))
1669                   changed |= bypass_block (bb, setcc, insn);
1670                 break;
1671               }
1672             else if (INSN_P (insn))
1673               break;
1674         }
1675     }
1676
1677   /* If we bypassed any register setting insns, we inserted a
1678      copy on the redirected edge.  These need to be committed.  */
1679   if (changed)
1680     commit_edge_insertions ();
1681
1682   return changed;
1683 }
1684 \f
1685 /* Return true if the graph is too expensive to optimize.  PASS is the
1686    optimization about to be performed.  */
1687
1688 static bool
1689 is_too_expensive (const char *pass)
1690 {
1691   /* Trying to perform global optimizations on flow graphs which have
1692      a high connectivity will take a long time and is unlikely to be
1693      particularly useful.
1694
1695      In normal circumstances a cfg should have about twice as many
1696      edges as blocks.  But we do not want to punish small functions
1697      which have a couple switch statements.  Rather than simply
1698      threshold the number of blocks, uses something with a more
1699      graceful degradation.  */
1700   if (n_edges > 20000 + n_basic_blocks * 4)
1701     {
1702       warning (OPT_Wdisabled_optimization,
1703                "%s: %d basic blocks and %d edges/basic block",
1704                pass, n_basic_blocks, n_edges / n_basic_blocks);
1705
1706       return true;
1707     }
1708
1709   /* If allocating memory for the cprop bitmap would take up too much
1710      storage it's better just to disable the optimization.  */
1711   if ((n_basic_blocks
1712        * SBITMAP_SET_SIZE (max_reg_num ())
1713        * sizeof (SBITMAP_ELT_TYPE)) > MAX_GCSE_MEMORY)
1714     {
1715       warning (OPT_Wdisabled_optimization,
1716                "%s: %d basic blocks and %d registers",
1717                pass, n_basic_blocks, max_reg_num ());
1718
1719       return true;
1720     }
1721
1722   return false;
1723 }
1724 \f
1725 /* Main function for the CPROP pass.  */
1726
1727 static int
1728 one_cprop_pass (void)
1729 {
1730   int changed = 0;
1731
1732   /* Return if there's nothing to do, or it is too expensive.  */
1733   if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
1734       || is_too_expensive (_ ("const/copy propagation disabled")))
1735     return 0;
1736
1737   global_const_prop_count = local_const_prop_count = 0;
1738   global_copy_prop_count = local_copy_prop_count = 0;
1739
1740   bytes_used = 0;
1741   gcc_obstack_init (&cprop_obstack);
1742
1743   /* Do a local const/copy propagation pass first.  The global pass
1744      only handles global opportunities.
1745      If the local pass changes something, remove any unreachable blocks
1746      because the CPROP global dataflow analysis may get into infinite
1747      loops for CFGs with unreachable blocks.
1748
1749      FIXME: This local pass should not be necessary after CSE (but for
1750             some reason it still is).  It is also (proven) not necessary
1751             to run the local pass right after FWPWOP.
1752
1753      FIXME: The global analysis would not get into infinite loops if it
1754             would use the DF solver (via df_simple_dataflow) instead of
1755             the solver implemented in this file.  */
1756   changed |= local_cprop_pass ();
1757   if (changed)
1758     delete_unreachable_blocks ();
1759
1760   /* Determine implicit sets.  This may change the CFG (split critical
1761      edges if that exposes an implicit set).
1762      Note that find_implicit_sets() does not rely on up-to-date DF caches
1763      so that we do not have to re-run df_analyze() even if local CPROP
1764      changed something.
1765      ??? This could run earlier so that any uncovered implicit sets
1766          sets could be exploited in local_cprop_pass() also.  Later.  */
1767   changed |= find_implicit_sets ();
1768
1769   /* If local_cprop_pass() or find_implicit_sets() changed something,
1770      run df_analyze() to bring all insn caches up-to-date, and to take
1771      new basic blocks from edge splitting on the DF radar.
1772      NB: This also runs the fast DCE pass, because execute_rtl_cprop
1773      sets DF_LR_RUN_DCE.  */
1774   if (changed)
1775     df_analyze ();
1776
1777   alloc_hash_table (&set_hash_table);
1778   compute_hash_table (&set_hash_table);
1779
1780   /* Free implicit_sets before peak usage.  */
1781   free (implicit_sets);
1782   implicit_sets = NULL;
1783
1784   if (dump_file)
1785     dump_hash_table (dump_file, "SET", &set_hash_table);
1786   if (set_hash_table.n_elems > 0)
1787     {
1788       basic_block bb;
1789       rtx insn;
1790
1791       alloc_cprop_mem (last_basic_block, set_hash_table.n_elems);
1792       compute_cprop_data ();
1793
1794       /* Allocate vars to track sets of regs.  */
1795       reg_set_bitmap = ALLOC_REG_SET (NULL);
1796
1797       FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb, EXIT_BLOCK_PTR,
1798                       next_bb)
1799         {
1800           /* Reset tables used to keep track of what's still valid [since
1801              the start of the block].  */
1802           reset_opr_set_tables ();
1803
1804           FOR_BB_INSNS (bb, insn)
1805             if (INSN_P (insn))
1806               {
1807                 changed |= cprop_insn (insn);
1808
1809                 /* Keep track of everything modified by this insn.  */
1810                 /* ??? Need to be careful w.r.t. mods done to INSN.
1811                        Don't call mark_oprs_set if we turned the
1812                        insn into a NOTE, or deleted the insn.  */
1813                 if (! NOTE_P (insn) && ! INSN_DELETED_P (insn))
1814                   mark_oprs_set (insn);
1815               }
1816         }
1817
1818       changed |= bypass_conditional_jumps ();
1819
1820       FREE_REG_SET (reg_set_bitmap);
1821       free_cprop_mem ();
1822     }
1823
1824   free_hash_table (&set_hash_table);
1825   obstack_free (&cprop_obstack, NULL);
1826
1827   if (dump_file)
1828     {
1829       fprintf (dump_file, "CPROP of %s, %d basic blocks, %d bytes needed, ",
1830                current_function_name (), n_basic_blocks, bytes_used);
1831       fprintf (dump_file, "%d local const props, %d local copy props, ",
1832                local_const_prop_count, local_copy_prop_count);
1833       fprintf (dump_file, "%d global const props, %d global copy props\n\n",
1834                global_const_prop_count, global_copy_prop_count);
1835     }
1836
1837   return changed;
1838 }
1839 \f
1840 /* All the passes implemented in this file.  Each pass has its
1841    own gate and execute function, and at the end of the file a
1842    pass definition for passes.c.
1843
1844    We do not construct an accurate cfg in functions which call
1845    setjmp, so none of these passes runs if the function calls
1846    setjmp.
1847    FIXME: Should just handle setjmp via REG_SETJMP notes.  */
1848
1849 static bool
1850 gate_rtl_cprop (void)
1851 {
1852   return optimize > 0 && flag_gcse
1853     && !cfun->calls_setjmp
1854     && dbg_cnt (cprop);
1855 }
1856
1857 static unsigned int
1858 execute_rtl_cprop (void)
1859 {
1860   int changed;
1861   delete_unreachable_blocks ();
1862   df_set_flags (DF_LR_RUN_DCE);
1863   df_analyze ();
1864   changed = one_cprop_pass ();
1865   flag_rerun_cse_after_global_opts |= changed;
1866   if (changed)
1867     cleanup_cfg (0);
1868   return 0;
1869 }
1870
1871 struct rtl_opt_pass pass_rtl_cprop =
1872 {
1873  {
1874   RTL_PASS,
1875   "cprop",                              /* name */
1876   gate_rtl_cprop,                       /* gate */
1877   execute_rtl_cprop,                    /* execute */
1878   NULL,                                 /* sub */
1879   NULL,                                 /* next */
1880   0,                                    /* static_pass_number */
1881   TV_CPROP,                             /* tv_id */
1882   PROP_cfglayout,                       /* properties_required */
1883   0,                                    /* properties_provided */
1884   0,                                    /* properties_destroyed */
1885   0,                                    /* todo_flags_start */
1886   TODO_df_finish | TODO_verify_rtl_sharing |
1887   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
1888  }
1889 };