OSDN Git Service

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