OSDN Git Service

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