Update change log
[platform/upstream/gcc48.git] / gcc / dse.c
1 /* RTL dead store elimination.
2    Copyright (C) 2005-2013 Free Software Foundation, Inc.
3
4    Contributed by Richard Sandiford <rsandifor@codesourcery.com>
5    and Kenneth Zadeck <zadeck@naturalbridge.com>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #undef BASELINE
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "hash-table.h"
29 #include "tm.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "tm_p.h"
33 #include "regs.h"
34 #include "hard-reg-set.h"
35 #include "regset.h"
36 #include "flags.h"
37 #include "df.h"
38 #include "cselib.h"
39 #include "tree-pass.h"
40 #include "alloc-pool.h"
41 #include "alias.h"
42 #include "insn-config.h"
43 #include "expr.h"
44 #include "recog.h"
45 #include "optabs.h"
46 #include "dbgcnt.h"
47 #include "target.h"
48 #include "params.h"
49 #include "tree-flow.h" /* for may_be_aliased */
50
51 /* This file contains three techniques for performing Dead Store
52    Elimination (dse).
53
54    * The first technique performs dse locally on any base address.  It
55    is based on the cselib which is a local value numbering technique.
56    This technique is local to a basic block but deals with a fairly
57    general addresses.
58
59    * The second technique performs dse globally but is restricted to
60    base addresses that are either constant or are relative to the
61    frame_pointer.
62
63    * The third technique, (which is only done after register allocation)
64    processes the spill spill slots.  This differs from the second
65    technique because it takes advantage of the fact that spilling is
66    completely free from the effects of aliasing.
67
68    Logically, dse is a backwards dataflow problem.  A store can be
69    deleted if it if cannot be reached in the backward direction by any
70    use of the value being stored.  However, the local technique uses a
71    forwards scan of the basic block because cselib requires that the
72    block be processed in that order.
73
74    The pass is logically broken into 7 steps:
75
76    0) Initialization.
77
78    1) The local algorithm, as well as scanning the insns for the two
79    global algorithms.
80
81    2) Analysis to see if the global algs are necessary.  In the case
82    of stores base on a constant address, there must be at least two
83    stores to that address, to make it possible to delete some of the
84    stores.  In the case of stores off of the frame or spill related
85    stores, only one store to an address is necessary because those
86    stores die at the end of the function.
87
88    3) Set up the global dataflow equations based on processing the
89    info parsed in the first step.
90
91    4) Solve the dataflow equations.
92
93    5) Delete the insns that the global analysis has indicated are
94    unnecessary.
95
96    6) Delete insns that store the same value as preceding store
97    where the earlier store couldn't be eliminated.
98
99    7) Cleanup.
100
101    This step uses cselib and canon_rtx to build the largest expression
102    possible for each address.  This pass is a forwards pass through
103    each basic block.  From the point of view of the global technique,
104    the first pass could examine a block in either direction.  The
105    forwards ordering is to accommodate cselib.
106
107    We make a simplifying assumption: addresses fall into four broad
108    categories:
109
110    1) base has rtx_varies_p == false, offset is constant.
111    2) base has rtx_varies_p == false, offset variable.
112    3) base has rtx_varies_p == true, offset constant.
113    4) base has rtx_varies_p == true, offset variable.
114
115    The local passes are able to process all 4 kinds of addresses.  The
116    global pass only handles 1).
117
118    The global problem is formulated as follows:
119
120      A store, S1, to address A, where A is not relative to the stack
121      frame, can be eliminated if all paths from S1 to the end of the
122      function contain another store to A before a read to A.
123
124      If the address A is relative to the stack frame, a store S2 to A
125      can be eliminated if there are no paths from S2 that reach the
126      end of the function that read A before another store to A.  In
127      this case S2 can be deleted if there are paths from S2 to the
128      end of the function that have no reads or writes to A.  This
129      second case allows stores to the stack frame to be deleted that
130      would otherwise die when the function returns.  This cannot be
131      done if stores_off_frame_dead_at_return is not true.  See the doc
132      for that variable for when this variable is false.
133
134      The global problem is formulated as a backwards set union
135      dataflow problem where the stores are the gens and reads are the
136      kills.  Set union problems are rare and require some special
137      handling given our representation of bitmaps.  A straightforward
138      implementation requires a lot of bitmaps filled with 1s.
139      These are expensive and cumbersome in our bitmap formulation so
140      care has been taken to avoid large vectors filled with 1s.  See
141      the comments in bb_info and in the dataflow confluence functions
142      for details.
143
144    There are two places for further enhancements to this algorithm:
145
146    1) The original dse which was embedded in a pass called flow also
147    did local address forwarding.  For example in
148
149    A <- r100
150    ... <- A
151
152    flow would replace the right hand side of the second insn with a
153    reference to r100.  Most of the information is available to add this
154    to this pass.  It has not done it because it is a lot of work in
155    the case that either r100 is assigned to between the first and
156    second insn and/or the second insn is a load of part of the value
157    stored by the first insn.
158
159    insn 5 in gcc.c-torture/compile/990203-1.c simple case.
160    insn 15 in gcc.c-torture/execute/20001017-2.c simple case.
161    insn 25 in gcc.c-torture/execute/20001026-1.c simple case.
162    insn 44 in gcc.c-torture/execute/20010910-1.c simple case.
163
164    2) The cleaning up of spill code is quite profitable.  It currently
165    depends on reading tea leaves and chicken entrails left by reload.
166    This pass depends on reload creating a singleton alias set for each
167    spill slot and telling the next dse pass which of these alias sets
168    are the singletons.  Rather than analyze the addresses of the
169    spills, dse's spill processing just does analysis of the loads and
170    stores that use those alias sets.  There are three cases where this
171    falls short:
172
173      a) Reload sometimes creates the slot for one mode of access, and
174      then inserts loads and/or stores for a smaller mode.  In this
175      case, the current code just punts on the slot.  The proper thing
176      to do is to back out and use one bit vector position for each
177      byte of the entity associated with the slot.  This depends on
178      KNOWING that reload always generates the accesses for each of the
179      bytes in some canonical (read that easy to understand several
180      passes after reload happens) way.
181
182      b) Reload sometimes decides that spill slot it allocated was not
183      large enough for the mode and goes back and allocates more slots
184      with the same mode and alias set.  The backout in this case is a
185      little more graceful than (a).  In this case the slot is unmarked
186      as being a spill slot and if final address comes out to be based
187      off the frame pointer, the global algorithm handles this slot.
188
189      c) For any pass that may prespill, there is currently no
190      mechanism to tell the dse pass that the slot being used has the
191      special properties that reload uses.  It may be that all that is
192      required is to have those passes make the same calls that reload
193      does, assuming that the alias sets can be manipulated in the same
194      way.  */
195
196 /* There are limits to the size of constant offsets we model for the
197    global problem.  There are certainly test cases, that exceed this
198    limit, however, it is unlikely that there are important programs
199    that really have constant offsets this size.  */
200 #define MAX_OFFSET (64 * 1024)
201
202 /* Obstack for the DSE dataflow bitmaps.  We don't want to put these
203    on the default obstack because these bitmaps can grow quite large
204    (~2GB for the small (!) test case of PR54146) and we'll hold on to
205    all that memory until the end of the compiler run.
206    As a bonus, delete_tree_live_info can destroy all the bitmaps by just
207    releasing the whole obstack.  */
208 static bitmap_obstack dse_bitmap_obstack;
209
210 /* Obstack for other data.  As for above: Kinda nice to be able to
211    throw it all away at the end in one big sweep.  */
212 static struct obstack dse_obstack;
213
214 /* Scratch bitmap for cselib's cselib_expand_value_rtx.  */
215 static bitmap scratch = NULL;
216
217 struct insn_info;
218
219 /* This structure holds information about a candidate store.  */
220 struct store_info
221 {
222
223   /* False means this is a clobber.  */
224   bool is_set;
225
226   /* False if a single HOST_WIDE_INT bitmap is used for positions_needed.  */
227   bool is_large;
228
229   /* The id of the mem group of the base address.  If rtx_varies_p is
230      true, this is -1.  Otherwise, it is the index into the group
231      table.  */
232   int group_id;
233
234   /* This is the cselib value.  */
235   cselib_val *cse_base;
236
237   /* This canonized mem.  */
238   rtx mem;
239
240   /* Canonized MEM address for use by canon_true_dependence.  */
241   rtx mem_addr;
242
243   /* If this is non-zero, it is the alias set of a spill location.  */
244   alias_set_type alias_set;
245
246   /* The offset of the first and byte before the last byte associated
247      with the operation.  */
248   HOST_WIDE_INT begin, end;
249
250   union
251     {
252       /* A bitmask as wide as the number of bytes in the word that
253          contains a 1 if the byte may be needed.  The store is unused if
254          all of the bits are 0.  This is used if IS_LARGE is false.  */
255       unsigned HOST_WIDE_INT small_bitmask;
256
257       struct
258         {
259           /* A bitmap with one bit per byte.  Cleared bit means the position
260              is needed.  Used if IS_LARGE is false.  */
261           bitmap bmap;
262
263           /* Number of set bits (i.e. unneeded bytes) in BITMAP.  If it is
264              equal to END - BEGIN, the whole store is unused.  */
265           int count;
266         } large;
267     } positions_needed;
268
269   /* The next store info for this insn.  */
270   struct store_info *next;
271
272   /* The right hand side of the store.  This is used if there is a
273      subsequent reload of the mems address somewhere later in the
274      basic block.  */
275   rtx rhs;
276
277   /* If rhs is or holds a constant, this contains that constant,
278      otherwise NULL.  */
279   rtx const_rhs;
280
281   /* Set if this store stores the same constant value as REDUNDANT_REASON
282      insn stored.  These aren't eliminated early, because doing that
283      might prevent the earlier larger store to be eliminated.  */
284   struct insn_info *redundant_reason;
285 };
286
287 /* Return a bitmask with the first N low bits set.  */
288
289 static unsigned HOST_WIDE_INT
290 lowpart_bitmask (int n)
291 {
292   unsigned HOST_WIDE_INT mask = ~(unsigned HOST_WIDE_INT) 0;
293   return mask >> (HOST_BITS_PER_WIDE_INT - n);
294 }
295
296 typedef struct store_info *store_info_t;
297 static alloc_pool cse_store_info_pool;
298 static alloc_pool rtx_store_info_pool;
299
300 /* This structure holds information about a load.  These are only
301    built for rtx bases.  */
302 struct read_info
303 {
304   /* The id of the mem group of the base address.  */
305   int group_id;
306
307   /* If this is non-zero, it is the alias set of a spill location.  */
308   alias_set_type alias_set;
309
310   /* The offset of the first and byte after the last byte associated
311      with the operation.  If begin == end == 0, the read did not have
312      a constant offset.  */
313   int begin, end;
314
315   /* The mem being read.  */
316   rtx mem;
317
318   /* The next read_info for this insn.  */
319   struct read_info *next;
320 };
321 typedef struct read_info *read_info_t;
322 static alloc_pool read_info_pool;
323
324
325 /* One of these records is created for each insn.  */
326
327 struct insn_info
328 {
329   /* Set true if the insn contains a store but the insn itself cannot
330      be deleted.  This is set if the insn is a parallel and there is
331      more than one non dead output or if the insn is in some way
332      volatile.  */
333   bool cannot_delete;
334
335   /* This field is only used by the global algorithm.  It is set true
336      if the insn contains any read of mem except for a (1).  This is
337      also set if the insn is a call or has a clobber mem.  If the insn
338      contains a wild read, the use_rec will be null.  */
339   bool wild_read;
340
341   /* This is true only for CALL instructions which could potentially read
342      any non-frame memory location. This field is used by the global
343      algorithm.  */
344   bool non_frame_wild_read;
345
346   /* This field is only used for the processing of const functions.
347      These functions cannot read memory, but they can read the stack
348      because that is where they may get their parms.  We need to be
349      this conservative because, like the store motion pass, we don't
350      consider CALL_INSN_FUNCTION_USAGE when processing call insns.
351      Moreover, we need to distinguish two cases:
352      1. Before reload (register elimination), the stores related to
353         outgoing arguments are stack pointer based and thus deemed
354         of non-constant base in this pass.  This requires special
355         handling but also means that the frame pointer based stores
356         need not be killed upon encountering a const function call.
357      2. After reload, the stores related to outgoing arguments can be
358         either stack pointer or hard frame pointer based.  This means
359         that we have no other choice than also killing all the frame
360         pointer based stores upon encountering a const function call.
361      This field is set after reload for const function calls.  Having
362      this set is less severe than a wild read, it just means that all
363      the frame related stores are killed rather than all the stores.  */
364   bool frame_read;
365
366   /* This field is only used for the processing of const functions.
367      It is set if the insn may contain a stack pointer based store.  */
368   bool stack_pointer_based;
369
370   /* This is true if any of the sets within the store contains a
371      cselib base.  Such stores can only be deleted by the local
372      algorithm.  */
373   bool contains_cselib_groups;
374
375   /* The insn. */
376   rtx insn;
377
378   /* The list of mem sets or mem clobbers that are contained in this
379      insn.  If the insn is deletable, it contains only one mem set.
380      But it could also contain clobbers.  Insns that contain more than
381      one mem set are not deletable, but each of those mems are here in
382      order to provide info to delete other insns.  */
383   store_info_t store_rec;
384
385   /* The linked list of mem uses in this insn.  Only the reads from
386      rtx bases are listed here.  The reads to cselib bases are
387      completely processed during the first scan and so are never
388      created.  */
389   read_info_t read_rec;
390
391   /* The live fixed registers.  We assume only fixed registers can
392      cause trouble by being clobbered from an expanded pattern;
393      storing only the live fixed registers (rather than all registers)
394      means less memory needs to be allocated / copied for the individual
395      stores.  */
396   regset fixed_regs_live;
397
398   /* The prev insn in the basic block.  */
399   struct insn_info * prev_insn;
400
401   /* The linked list of insns that are in consideration for removal in
402      the forwards pass through the basic block.  This pointer may be
403      trash as it is not cleared when a wild read occurs.  The only
404      time it is guaranteed to be correct is when the traversal starts
405      at active_local_stores.  */
406   struct insn_info * next_local_store;
407 };
408
409 typedef struct insn_info *insn_info_t;
410 static alloc_pool insn_info_pool;
411
412 /* The linked list of stores that are under consideration in this
413    basic block.  */
414 static insn_info_t active_local_stores;
415 static int active_local_stores_len;
416
417 struct bb_info
418 {
419
420   /* Pointer to the insn info for the last insn in the block.  These
421      are linked so this is how all of the insns are reached.  During
422      scanning this is the current insn being scanned.  */
423   insn_info_t last_insn;
424
425   /* The info for the global dataflow problem.  */
426
427
428   /* This is set if the transfer function should and in the wild_read
429      bitmap before applying the kill and gen sets.  That vector knocks
430      out most of the bits in the bitmap and thus speeds up the
431      operations.  */
432   bool apply_wild_read;
433
434   /* The following 4 bitvectors hold information about which positions
435      of which stores are live or dead.  They are indexed by
436      get_bitmap_index.  */
437
438   /* The set of store positions that exist in this block before a wild read.  */
439   bitmap gen;
440
441   /* The set of load positions that exist in this block above the
442      same position of a store.  */
443   bitmap kill;
444
445   /* The set of stores that reach the top of the block without being
446      killed by a read.
447
448      Do not represent the in if it is all ones.  Note that this is
449      what the bitvector should logically be initialized to for a set
450      intersection problem.  However, like the kill set, this is too
451      expensive.  So initially, the in set will only be created for the
452      exit block and any block that contains a wild read.  */
453   bitmap in;
454
455   /* The set of stores that reach the bottom of the block from it's
456      successors.
457
458      Do not represent the in if it is all ones.  Note that this is
459      what the bitvector should logically be initialized to for a set
460      intersection problem.  However, like the kill and in set, this is
461      too expensive.  So what is done is that the confluence operator
462      just initializes the vector from one of the out sets of the
463      successors of the block.  */
464   bitmap out;
465
466   /* The following bitvector is indexed by the reg number.  It
467      contains the set of regs that are live at the current instruction
468      being processed.  While it contains info for all of the
469      registers, only the hard registers are actually examined.  It is used
470      to assure that shift and/or add sequences that are inserted do not
471      accidentally clobber live hard regs.  */
472   bitmap regs_live;
473 };
474
475 typedef struct bb_info *bb_info_t;
476 static alloc_pool bb_info_pool;
477
478 /* Table to hold all bb_infos.  */
479 static bb_info_t *bb_table;
480
481 /* There is a group_info for each rtx base that is used to reference
482    memory.  There are also not many of the rtx bases because they are
483    very limited in scope.  */
484
485 struct group_info
486 {
487   /* The actual base of the address.  */
488   rtx rtx_base;
489
490   /* The sequential id of the base.  This allows us to have a
491      canonical ordering of these that is not based on addresses.  */
492   int id;
493
494   /* True if there are any positions that are to be processed
495      globally.  */
496   bool process_globally;
497
498   /* True if the base of this group is either the frame_pointer or
499      hard_frame_pointer.  */
500   bool frame_related;
501
502   /* A mem wrapped around the base pointer for the group in order to do
503      read dependency.  It must be given BLKmode in order to encompass all
504      the possible offsets from the base.  */
505   rtx base_mem;
506
507   /* Canonized version of base_mem's address.  */
508   rtx canon_base_addr;
509
510   /* These two sets of two bitmaps are used to keep track of how many
511      stores are actually referencing that position from this base.  We
512      only do this for rtx bases as this will be used to assign
513      positions in the bitmaps for the global problem.  Bit N is set in
514      store1 on the first store for offset N.  Bit N is set in store2
515      for the second store to offset N.  This is all we need since we
516      only care about offsets that have two or more stores for them.
517
518      The "_n" suffix is for offsets less than 0 and the "_p" suffix is
519      for 0 and greater offsets.
520
521      There is one special case here, for stores into the stack frame,
522      we will or store1 into store2 before deciding which stores look
523      at globally.  This is because stores to the stack frame that have
524      no other reads before the end of the function can also be
525      deleted.  */
526   bitmap store1_n, store1_p, store2_n, store2_p;
527
528   /* These bitmaps keep track of offsets in this group escape this function.
529      An offset escapes if it corresponds to a named variable whose
530      addressable flag is set.  */
531   bitmap escaped_n, escaped_p;
532
533   /* The positions in this bitmap have the same assignments as the in,
534      out, gen and kill bitmaps.  This bitmap is all zeros except for
535      the positions that are occupied by stores for this group.  */
536   bitmap group_kill;
537
538   /* The offset_map is used to map the offsets from this base into
539      positions in the global bitmaps.  It is only created after all of
540      the all of stores have been scanned and we know which ones we
541      care about.  */
542   int *offset_map_n, *offset_map_p;
543   int offset_map_size_n, offset_map_size_p;
544 };
545 typedef struct group_info *group_info_t;
546 typedef const struct group_info *const_group_info_t;
547 static alloc_pool rtx_group_info_pool;
548
549 /* Index into the rtx_group_vec.  */
550 static int rtx_group_next_id;
551
552
553 static vec<group_info_t> rtx_group_vec;
554
555
556 /* This structure holds the set of changes that are being deferred
557    when removing read operation.  See replace_read.  */
558 struct deferred_change
559 {
560
561   /* The mem that is being replaced.  */
562   rtx *loc;
563
564   /* The reg it is being replaced with.  */
565   rtx reg;
566
567   struct deferred_change *next;
568 };
569
570 typedef struct deferred_change *deferred_change_t;
571 static alloc_pool deferred_change_pool;
572
573 static deferred_change_t deferred_change_list = NULL;
574
575 /* This are used to hold the alias sets of spill variables.  Since
576    these are never aliased and there may be a lot of them, it makes
577    sense to treat them specially.  This bitvector is only allocated in
578    calls from dse_record_singleton_alias_set which currently is only
579    made during reload1.  So when dse is called before reload this
580    mechanism does nothing.  */
581
582 static bitmap clear_alias_sets = NULL;
583
584 /* The set of clear_alias_sets that have been disqualified because
585    there are loads or stores using a different mode than the alias set
586    was registered with.  */
587 static bitmap disqualified_clear_alias_sets = NULL;
588
589 /* The group that holds all of the clear_alias_sets.  */
590 static group_info_t clear_alias_group;
591
592 /* The modes of the clear_alias_sets.  */
593 static htab_t clear_alias_mode_table;
594
595 /* Hash table element to look up the mode for an alias set.  */
596 struct clear_alias_mode_holder
597 {
598   alias_set_type alias_set;
599   enum machine_mode mode;
600 };
601
602 static alloc_pool clear_alias_mode_pool;
603
604 /* This is true except if cfun->stdarg -- i.e. we cannot do
605    this for vararg functions because they play games with the frame.  */
606 static bool stores_off_frame_dead_at_return;
607
608 /* Counter for stats.  */
609 static int globally_deleted;
610 static int locally_deleted;
611 static int spill_deleted;
612
613 static bitmap all_blocks;
614
615 /* Locations that are killed by calls in the global phase.  */
616 static bitmap kill_on_calls;
617
618 /* The number of bits used in the global bitmaps.  */
619 static unsigned int current_position;
620
621
622 static bool gate_dse1 (void);
623 static bool gate_dse2 (void);
624
625 \f
626 /*----------------------------------------------------------------------------
627    Zeroth step.
628
629    Initialization.
630 ----------------------------------------------------------------------------*/
631
632
633 /* Find the entry associated with ALIAS_SET.  */
634
635 static struct clear_alias_mode_holder *
636 clear_alias_set_lookup (alias_set_type alias_set)
637 {
638   struct clear_alias_mode_holder tmp_holder;
639   void **slot;
640
641   tmp_holder.alias_set = alias_set;
642   slot = htab_find_slot (clear_alias_mode_table, &tmp_holder, NO_INSERT);
643   gcc_assert (*slot);
644
645   return (struct clear_alias_mode_holder *) *slot;
646 }
647
648
649 /* Hashtable callbacks for maintaining the "bases" field of
650    store_group_info, given that the addresses are function invariants.  */
651
652 struct invariant_group_base_hasher : typed_noop_remove <group_info>
653 {
654   typedef group_info value_type;
655   typedef group_info compare_type;
656   static inline hashval_t hash (const value_type *);
657   static inline bool equal (const value_type *, const compare_type *);
658 };
659
660 inline bool
661 invariant_group_base_hasher::equal (const value_type *gi1,
662                                     const compare_type *gi2)
663 {
664   return rtx_equal_p (gi1->rtx_base, gi2->rtx_base);
665 }
666
667 inline hashval_t
668 invariant_group_base_hasher::hash (const value_type *gi)
669 {
670   int do_not_record;
671   return hash_rtx (gi->rtx_base, Pmode, &do_not_record, NULL, false);
672 }
673
674 /* Tables of group_info structures, hashed by base value.  */
675 static hash_table <invariant_group_base_hasher> rtx_group_table;
676
677
678 /* Get the GROUP for BASE.  Add a new group if it is not there.  */
679
680 static group_info_t
681 get_group_info (rtx base)
682 {
683   struct group_info tmp_gi;
684   group_info_t gi;
685   group_info **slot;
686
687   if (base)
688     {
689       /* Find the store_base_info structure for BASE, creating a new one
690          if necessary.  */
691       tmp_gi.rtx_base = base;
692       slot = rtx_group_table.find_slot (&tmp_gi, INSERT);
693       gi = (group_info_t) *slot;
694     }
695   else
696     {
697       if (!clear_alias_group)
698         {
699           clear_alias_group = gi =
700             (group_info_t) pool_alloc (rtx_group_info_pool);
701           memset (gi, 0, sizeof (struct group_info));
702           gi->id = rtx_group_next_id++;
703           gi->store1_n = BITMAP_ALLOC (&dse_bitmap_obstack);
704           gi->store1_p = BITMAP_ALLOC (&dse_bitmap_obstack);
705           gi->store2_n = BITMAP_ALLOC (&dse_bitmap_obstack);
706           gi->store2_p = BITMAP_ALLOC (&dse_bitmap_obstack);
707           gi->escaped_p = BITMAP_ALLOC (&dse_bitmap_obstack);
708           gi->escaped_n = BITMAP_ALLOC (&dse_bitmap_obstack);
709           gi->group_kill = BITMAP_ALLOC (&dse_bitmap_obstack);
710           gi->process_globally = false;
711           gi->offset_map_size_n = 0;
712           gi->offset_map_size_p = 0;
713           gi->offset_map_n = NULL;
714           gi->offset_map_p = NULL;
715           rtx_group_vec.safe_push (gi);
716         }
717       return clear_alias_group;
718     }
719
720   if (gi == NULL)
721     {
722       *slot = gi = (group_info_t) pool_alloc (rtx_group_info_pool);
723       gi->rtx_base = base;
724       gi->id = rtx_group_next_id++;
725       gi->base_mem = gen_rtx_MEM (BLKmode, base);
726       gi->canon_base_addr = canon_rtx (base);
727       gi->store1_n = BITMAP_ALLOC (&dse_bitmap_obstack);
728       gi->store1_p = BITMAP_ALLOC (&dse_bitmap_obstack);
729       gi->store2_n = BITMAP_ALLOC (&dse_bitmap_obstack);
730       gi->store2_p = BITMAP_ALLOC (&dse_bitmap_obstack);
731       gi->escaped_p = BITMAP_ALLOC (&dse_bitmap_obstack);
732       gi->escaped_n = BITMAP_ALLOC (&dse_bitmap_obstack);
733       gi->group_kill = BITMAP_ALLOC (&dse_bitmap_obstack);
734       gi->process_globally = false;
735       gi->frame_related =
736         (base == frame_pointer_rtx) || (base == hard_frame_pointer_rtx);
737       gi->offset_map_size_n = 0;
738       gi->offset_map_size_p = 0;
739       gi->offset_map_n = NULL;
740       gi->offset_map_p = NULL;
741       rtx_group_vec.safe_push (gi);
742     }
743
744   return gi;
745 }
746
747
748 /* Initialization of data structures.  */
749
750 static void
751 dse_step0 (void)
752 {
753   locally_deleted = 0;
754   globally_deleted = 0;
755   spill_deleted = 0;
756
757   bitmap_obstack_initialize (&dse_bitmap_obstack);
758   gcc_obstack_init (&dse_obstack);
759
760   scratch = BITMAP_ALLOC (&reg_obstack);
761   kill_on_calls = BITMAP_ALLOC (&dse_bitmap_obstack);
762
763   rtx_store_info_pool
764     = create_alloc_pool ("rtx_store_info_pool",
765                          sizeof (struct store_info), 100);
766   read_info_pool
767     = create_alloc_pool ("read_info_pool",
768                          sizeof (struct read_info), 100);
769   insn_info_pool
770     = create_alloc_pool ("insn_info_pool",
771                          sizeof (struct insn_info), 100);
772   bb_info_pool
773     = create_alloc_pool ("bb_info_pool",
774                          sizeof (struct bb_info), 100);
775   rtx_group_info_pool
776     = create_alloc_pool ("rtx_group_info_pool",
777                          sizeof (struct group_info), 100);
778   deferred_change_pool
779     = create_alloc_pool ("deferred_change_pool",
780                          sizeof (struct deferred_change), 10);
781
782   rtx_group_table.create (11);
783
784   bb_table = XNEWVEC (bb_info_t, last_basic_block);
785   rtx_group_next_id = 0;
786
787   stores_off_frame_dead_at_return = !cfun->stdarg;
788
789   init_alias_analysis ();
790
791   if (clear_alias_sets)
792     clear_alias_group = get_group_info (NULL);
793   else
794     clear_alias_group = NULL;
795 }
796
797
798 \f
799 /*----------------------------------------------------------------------------
800    First step.
801
802    Scan all of the insns.  Any random ordering of the blocks is fine.
803    Each block is scanned in forward order to accommodate cselib which
804    is used to remove stores with non-constant bases.
805 ----------------------------------------------------------------------------*/
806
807 /* Delete all of the store_info recs from INSN_INFO.  */
808
809 static void
810 free_store_info (insn_info_t insn_info)
811 {
812   store_info_t store_info = insn_info->store_rec;
813   while (store_info)
814     {
815       store_info_t next = store_info->next;
816       if (store_info->is_large)
817         BITMAP_FREE (store_info->positions_needed.large.bmap);
818       if (store_info->cse_base)
819         pool_free (cse_store_info_pool, store_info);
820       else
821         pool_free (rtx_store_info_pool, store_info);
822       store_info = next;
823     }
824
825   insn_info->cannot_delete = true;
826   insn_info->contains_cselib_groups = false;
827   insn_info->store_rec = NULL;
828 }
829
830 typedef struct
831 {
832   rtx first, current;
833   regset fixed_regs_live;
834   bool failure;
835 } note_add_store_info;
836
837 /* Callback for emit_inc_dec_insn_before via note_stores.
838    Check if a register is clobbered which is live afterwards.  */
839
840 static void
841 note_add_store (rtx loc, const_rtx expr ATTRIBUTE_UNUSED, void *data)
842 {
843   rtx insn;
844   note_add_store_info *info = (note_add_store_info *) data;
845   int r, n;
846
847   if (!REG_P (loc))
848     return;
849
850   /* If this register is referenced by the current or an earlier insn,
851      that's OK.  E.g. this applies to the register that is being incremented
852      with this addition.  */
853   for (insn = info->first;
854        insn != NEXT_INSN (info->current);
855        insn = NEXT_INSN (insn))
856     if (reg_referenced_p (loc, PATTERN (insn)))
857       return;
858
859   /* If we come here, we have a clobber of a register that's only OK
860      if that register is not live.  If we don't have liveness information
861      available, fail now.  */
862   if (!info->fixed_regs_live)
863     {
864       info->failure =  true;
865       return;
866     }
867   /* Now check if this is a live fixed register.  */
868   r = REGNO (loc);
869   n = hard_regno_nregs[r][GET_MODE (loc)];
870   while (--n >=  0)
871     if (REGNO_REG_SET_P (info->fixed_regs_live, r+n))
872       info->failure =  true;
873 }
874
875 /* Callback for for_each_inc_dec that emits an INSN that sets DEST to
876    SRC + SRCOFF before insn ARG.  */
877
878 static int
879 emit_inc_dec_insn_before (rtx mem ATTRIBUTE_UNUSED,
880                           rtx op ATTRIBUTE_UNUSED,
881                           rtx dest, rtx src, rtx srcoff, void *arg)
882 {
883   insn_info_t insn_info = (insn_info_t) arg;
884   rtx insn = insn_info->insn, new_insn, cur;
885   note_add_store_info info;
886
887   /* We can reuse all operands without copying, because we are about
888      to delete the insn that contained it.  */
889   if (srcoff)
890     {
891       start_sequence ();
892       emit_insn (gen_add3_insn (dest, src, srcoff));
893       new_insn = get_insns ();
894       end_sequence ();
895     }
896   else
897     new_insn = gen_move_insn (dest, src);
898   info.first = new_insn;
899   info.fixed_regs_live = insn_info->fixed_regs_live;
900   info.failure = false;
901   for (cur = new_insn; cur; cur = NEXT_INSN (cur))
902     {
903       info.current = cur;
904       note_stores (PATTERN (cur), note_add_store, &info);
905     }
906
907   /* If a failure was flagged above, return 1 so that for_each_inc_dec will
908      return it immediately, communicating the failure to its caller.  */
909   if (info.failure)
910     return 1;
911
912   emit_insn_before (new_insn, insn);
913
914   return -1;
915 }
916
917 /* Before we delete INSN_INFO->INSN, make sure that the auto inc/dec, if it
918    is there, is split into a separate insn.
919    Return true on success (or if there was nothing to do), false on failure.  */
920
921 static bool
922 check_for_inc_dec_1 (insn_info_t insn_info)
923 {
924   rtx insn = insn_info->insn;
925   rtx note = find_reg_note (insn, REG_INC, NULL_RTX);
926   if (note)
927     return for_each_inc_dec (&insn, emit_inc_dec_insn_before, insn_info) == 0;
928   return true;
929 }
930
931
932 /* Entry point for postreload.  If you work on reload_cse, or you need this
933    anywhere else, consider if you can provide register liveness information
934    and add a parameter to this function so that it can be passed down in
935    insn_info.fixed_regs_live.  */
936 bool
937 check_for_inc_dec (rtx insn)
938 {
939   struct insn_info insn_info;
940   rtx note;
941
942   insn_info.insn = insn;
943   insn_info.fixed_regs_live = NULL;
944   note = find_reg_note (insn, REG_INC, NULL_RTX);
945   if (note)
946     return for_each_inc_dec (&insn, emit_inc_dec_insn_before, &insn_info) == 0;
947   return true;
948 }
949
950 /* Delete the insn and free all of the fields inside INSN_INFO.  */
951
952 static void
953 delete_dead_store_insn (insn_info_t insn_info)
954 {
955   read_info_t read_info;
956
957   if (!dbg_cnt (dse))
958     return;
959
960   if (!check_for_inc_dec_1 (insn_info))
961     return;
962   if (dump_file && (dump_flags & TDF_DETAILS))
963     {
964       fprintf (dump_file, "Locally deleting insn %d ",
965                INSN_UID (insn_info->insn));
966       if (insn_info->store_rec->alias_set)
967         fprintf (dump_file, "alias set %d\n",
968                  (int) insn_info->store_rec->alias_set);
969       else
970         fprintf (dump_file, "\n");
971     }
972
973   free_store_info (insn_info);
974   read_info = insn_info->read_rec;
975
976   while (read_info)
977     {
978       read_info_t next = read_info->next;
979       pool_free (read_info_pool, read_info);
980       read_info = next;
981     }
982   insn_info->read_rec = NULL;
983
984   delete_insn (insn_info->insn);
985   locally_deleted++;
986   insn_info->insn = NULL;
987
988   insn_info->wild_read = false;
989 }
990
991 /* Return whether DECL, a local variable, can possibly escape the current
992    function scope.  */
993
994 static bool
995 local_variable_can_escape (tree decl)
996 {
997   if (TREE_ADDRESSABLE (decl))
998     return true;
999
1000   /* If this is a partitioned variable, we need to consider all the variables
1001      in the partition.  This is necessary because a store into one of them can
1002      be replaced with a store into another and this may not change the outcome
1003      of the escape analysis.  */
1004   if (cfun->gimple_df->decls_to_pointers != NULL)
1005     {
1006       void *namep
1007         = pointer_map_contains (cfun->gimple_df->decls_to_pointers, decl);
1008       if (namep)
1009         return TREE_ADDRESSABLE (*(tree *)namep);
1010     }
1011
1012   return false;
1013 }
1014
1015 /* Return whether EXPR can possibly escape the current function scope.  */
1016
1017 static bool
1018 can_escape (tree expr)
1019 {
1020   tree base;
1021   if (!expr)
1022     return true;
1023   base = get_base_address (expr);
1024   if (DECL_P (base)
1025       && !may_be_aliased (base)
1026       && !(TREE_CODE (base) == VAR_DECL
1027            && !DECL_EXTERNAL (base)
1028            && !TREE_STATIC (base)
1029            && local_variable_can_escape (base)))
1030     return false;
1031   return true;
1032 }
1033
1034 /* Set the store* bitmaps offset_map_size* fields in GROUP based on
1035    OFFSET and WIDTH.  */
1036
1037 static void
1038 set_usage_bits (group_info_t group, HOST_WIDE_INT offset, HOST_WIDE_INT width,
1039                 tree expr)
1040 {
1041   HOST_WIDE_INT i;
1042   bool expr_escapes = can_escape (expr);
1043   if (offset > -MAX_OFFSET && offset + width < MAX_OFFSET)
1044     for (i=offset; i<offset+width; i++)
1045       {
1046         bitmap store1;
1047         bitmap store2;
1048         bitmap escaped;
1049         int ai;
1050         if (i < 0)
1051           {
1052             store1 = group->store1_n;
1053             store2 = group->store2_n;
1054             escaped = group->escaped_n;
1055             ai = -i;
1056           }
1057         else
1058           {
1059             store1 = group->store1_p;
1060             store2 = group->store2_p;
1061             escaped = group->escaped_p;
1062             ai = i;
1063           }
1064
1065         if (!bitmap_set_bit (store1, ai))
1066           bitmap_set_bit (store2, ai);
1067         else
1068           {
1069             if (i < 0)
1070               {
1071                 if (group->offset_map_size_n < ai)
1072                   group->offset_map_size_n = ai;
1073               }
1074             else
1075               {
1076                 if (group->offset_map_size_p < ai)
1077                   group->offset_map_size_p = ai;
1078               }
1079           }
1080         if (expr_escapes)
1081           bitmap_set_bit (escaped, ai);
1082       }
1083 }
1084
1085 static void
1086 reset_active_stores (void)
1087 {
1088   active_local_stores = NULL;
1089   active_local_stores_len = 0;
1090 }
1091
1092 /* Free all READ_REC of the LAST_INSN of BB_INFO.  */
1093
1094 static void
1095 free_read_records (bb_info_t bb_info)
1096 {
1097   insn_info_t insn_info = bb_info->last_insn;
1098   read_info_t *ptr = &insn_info->read_rec;
1099   while (*ptr)
1100     {
1101       read_info_t next = (*ptr)->next;
1102       if ((*ptr)->alias_set == 0)
1103         {
1104           pool_free (read_info_pool, *ptr);
1105           *ptr = next;
1106         }
1107       else
1108         ptr = &(*ptr)->next;
1109     }
1110 }
1111
1112 /* Set the BB_INFO so that the last insn is marked as a wild read.  */
1113
1114 static void
1115 add_wild_read (bb_info_t bb_info)
1116 {
1117   insn_info_t insn_info = bb_info->last_insn;
1118   insn_info->wild_read = true;
1119   free_read_records (bb_info);
1120   reset_active_stores ();
1121 }
1122
1123 /* Set the BB_INFO so that the last insn is marked as a wild read of
1124    non-frame locations.  */
1125
1126 static void
1127 add_non_frame_wild_read (bb_info_t bb_info)
1128 {
1129   insn_info_t insn_info = bb_info->last_insn;
1130   insn_info->non_frame_wild_read = true;
1131   free_read_records (bb_info);
1132   reset_active_stores ();
1133 }
1134
1135 /* Return true if X is a constant or one of the registers that behave
1136    as a constant over the life of a function.  This is equivalent to
1137    !rtx_varies_p for memory addresses.  */
1138
1139 static bool
1140 const_or_frame_p (rtx x)
1141 {
1142   if (CONSTANT_P (x))
1143     return true;
1144
1145   if (GET_CODE (x) == REG)
1146     {
1147       /* Note that we have to test for the actual rtx used for the frame
1148          and arg pointers and not just the register number in case we have
1149          eliminated the frame and/or arg pointer and are using it
1150          for pseudos.  */
1151       if (x == frame_pointer_rtx || x == hard_frame_pointer_rtx
1152           /* The arg pointer varies if it is not a fixed register.  */
1153           || (x == arg_pointer_rtx && fixed_regs[ARG_POINTER_REGNUM])
1154           || x == pic_offset_table_rtx)
1155         return true;
1156       return false;
1157     }
1158   
1159   return false;
1160 }
1161
1162 /* Take all reasonable action to put the address of MEM into the form
1163    that we can do analysis on.
1164
1165    The gold standard is to get the address into the form: address +
1166    OFFSET where address is something that rtx_varies_p considers a
1167    constant.  When we can get the address in this form, we can do
1168    global analysis on it.  Note that for constant bases, address is
1169    not actually returned, only the group_id.  The address can be
1170    obtained from that.
1171
1172    If that fails, we try cselib to get a value we can at least use
1173    locally.  If that fails we return false.
1174
1175    The GROUP_ID is set to -1 for cselib bases and the index of the
1176    group for non_varying bases.
1177
1178    FOR_READ is true if this is a mem read and false if not.  */
1179
1180 static bool
1181 canon_address (rtx mem,
1182                alias_set_type *alias_set_out,
1183                int *group_id,
1184                HOST_WIDE_INT *offset,
1185                cselib_val **base)
1186 {
1187   enum machine_mode address_mode = get_address_mode (mem);
1188   rtx mem_address = XEXP (mem, 0);
1189   rtx expanded_address, address;
1190   int expanded;
1191
1192   /* Make sure that cselib is has initialized all of the operands of
1193      the address before asking it to do the subst.  */
1194
1195   if (clear_alias_sets)
1196     {
1197       /* If this is a spill, do not do any further processing.  */
1198       alias_set_type alias_set = MEM_ALIAS_SET (mem);
1199       if (dump_file && (dump_flags & TDF_DETAILS))
1200         fprintf (dump_file, "found alias set %d\n", (int) alias_set);
1201       if (bitmap_bit_p (clear_alias_sets, alias_set))
1202         {
1203           struct clear_alias_mode_holder *entry
1204             = clear_alias_set_lookup (alias_set);
1205
1206           /* If the modes do not match, we cannot process this set.  */
1207           if (entry->mode != GET_MODE (mem))
1208             {
1209               if (dump_file && (dump_flags & TDF_DETAILS))
1210                 fprintf (dump_file,
1211                          "disqualifying alias set %d, (%s) != (%s)\n",
1212                          (int) alias_set, GET_MODE_NAME (entry->mode),
1213                          GET_MODE_NAME (GET_MODE (mem)));
1214
1215               bitmap_set_bit (disqualified_clear_alias_sets, alias_set);
1216               return false;
1217             }
1218
1219           *alias_set_out = alias_set;
1220           *group_id = clear_alias_group->id;
1221           return true;
1222         }
1223     }
1224
1225   *alias_set_out = 0;
1226
1227   cselib_lookup (mem_address, address_mode, 1, GET_MODE (mem));
1228
1229   if (dump_file && (dump_flags & TDF_DETAILS))
1230     {
1231       fprintf (dump_file, "  mem: ");
1232       print_inline_rtx (dump_file, mem_address, 0);
1233       fprintf (dump_file, "\n");
1234     }
1235
1236   /* First see if just canon_rtx (mem_address) is const or frame,
1237      if not, try cselib_expand_value_rtx and call canon_rtx on that.  */
1238   address = NULL_RTX;
1239   for (expanded = 0; expanded < 2; expanded++)
1240     {
1241       if (expanded)
1242         {
1243           /* Use cselib to replace all of the reg references with the full
1244              expression.  This will take care of the case where we have
1245
1246              r_x = base + offset;
1247              val = *r_x;
1248
1249              by making it into
1250
1251              val = *(base + offset);  */
1252
1253           expanded_address = cselib_expand_value_rtx (mem_address,
1254                                                       scratch, 5);
1255
1256           /* If this fails, just go with the address from first
1257              iteration.  */
1258           if (!expanded_address)
1259             break;
1260         }
1261       else
1262         expanded_address = mem_address;
1263
1264       /* Split the address into canonical BASE + OFFSET terms.  */
1265       address = canon_rtx (expanded_address);
1266
1267       *offset = 0;
1268
1269       if (dump_file && (dump_flags & TDF_DETAILS))
1270         {
1271           if (expanded)
1272             {
1273               fprintf (dump_file, "\n   after cselib_expand address: ");
1274               print_inline_rtx (dump_file, expanded_address, 0);
1275               fprintf (dump_file, "\n");
1276             }
1277
1278           fprintf (dump_file, "\n   after canon_rtx address: ");
1279           print_inline_rtx (dump_file, address, 0);
1280           fprintf (dump_file, "\n");
1281         }
1282
1283       if (GET_CODE (address) == CONST)
1284         address = XEXP (address, 0);
1285
1286       if (GET_CODE (address) == PLUS
1287           && CONST_INT_P (XEXP (address, 1)))
1288         {
1289           *offset = INTVAL (XEXP (address, 1));
1290           address = XEXP (address, 0);
1291         }
1292
1293       if (ADDR_SPACE_GENERIC_P (MEM_ADDR_SPACE (mem))
1294           && const_or_frame_p (address))
1295         {
1296           group_info_t group = get_group_info (address);
1297
1298           if (dump_file && (dump_flags & TDF_DETAILS))
1299             fprintf (dump_file, "  gid=%d offset=%d \n",
1300                      group->id, (int)*offset);
1301           *base = NULL;
1302           *group_id = group->id;
1303           return true;
1304         }
1305     }
1306
1307   *base = cselib_lookup (address, address_mode, true, GET_MODE (mem));
1308   *group_id = -1;
1309
1310   if (*base == NULL)
1311     {
1312       if (dump_file && (dump_flags & TDF_DETAILS))
1313         fprintf (dump_file, " no cselib val - should be a wild read.\n");
1314       return false;
1315     }
1316   if (dump_file && (dump_flags & TDF_DETAILS))
1317     fprintf (dump_file, "  varying cselib base=%u:%u offset = %d\n",
1318              (*base)->uid, (*base)->hash, (int)*offset);
1319   return true;
1320 }
1321
1322
1323 /* Clear the rhs field from the active_local_stores array.  */
1324
1325 static void
1326 clear_rhs_from_active_local_stores (void)
1327 {
1328   insn_info_t ptr = active_local_stores;
1329
1330   while (ptr)
1331     {
1332       store_info_t store_info = ptr->store_rec;
1333       /* Skip the clobbers.  */
1334       while (!store_info->is_set)
1335         store_info = store_info->next;
1336
1337       store_info->rhs = NULL;
1338       store_info->const_rhs = NULL;
1339
1340       ptr = ptr->next_local_store;
1341     }
1342 }
1343
1344
1345 /* Mark byte POS bytes from the beginning of store S_INFO as unneeded.  */
1346
1347 static inline void
1348 set_position_unneeded (store_info_t s_info, int pos)
1349 {
1350   if (__builtin_expect (s_info->is_large, false))
1351     {
1352       if (bitmap_set_bit (s_info->positions_needed.large.bmap, pos))
1353         s_info->positions_needed.large.count++;
1354     }
1355   else
1356     s_info->positions_needed.small_bitmask
1357       &= ~(((unsigned HOST_WIDE_INT) 1) << pos);
1358 }
1359
1360 /* Mark the whole store S_INFO as unneeded.  */
1361
1362 static inline void
1363 set_all_positions_unneeded (store_info_t s_info)
1364 {
1365   if (__builtin_expect (s_info->is_large, false))
1366     {
1367       int pos, end = s_info->end - s_info->begin;
1368       for (pos = 0; pos < end; pos++)
1369         bitmap_set_bit (s_info->positions_needed.large.bmap, pos);
1370       s_info->positions_needed.large.count = end;
1371     }
1372   else
1373     s_info->positions_needed.small_bitmask = (unsigned HOST_WIDE_INT) 0;
1374 }
1375
1376 /* Return TRUE if any bytes from S_INFO store are needed.  */
1377
1378 static inline bool
1379 any_positions_needed_p (store_info_t s_info)
1380 {
1381   if (__builtin_expect (s_info->is_large, false))
1382     return (s_info->positions_needed.large.count
1383             < s_info->end - s_info->begin);
1384   else
1385     return (s_info->positions_needed.small_bitmask
1386             != (unsigned HOST_WIDE_INT) 0);
1387 }
1388
1389 /* Return TRUE if all bytes START through START+WIDTH-1 from S_INFO
1390    store are needed.  */
1391
1392 static inline bool
1393 all_positions_needed_p (store_info_t s_info, int start, int width)
1394 {
1395   if (__builtin_expect (s_info->is_large, false))
1396     {
1397       int end = start + width;
1398       while (start < end)
1399         if (bitmap_bit_p (s_info->positions_needed.large.bmap, start++))
1400           return false;
1401       return true;
1402     }
1403   else
1404     {
1405       unsigned HOST_WIDE_INT mask = lowpart_bitmask (width) << start;
1406       return (s_info->positions_needed.small_bitmask & mask) == mask;
1407     }
1408 }
1409
1410
1411 static rtx get_stored_val (store_info_t, enum machine_mode, HOST_WIDE_INT,
1412                            HOST_WIDE_INT, basic_block, bool);
1413
1414
1415 /* BODY is an instruction pattern that belongs to INSN.  Return 1 if
1416    there is a candidate store, after adding it to the appropriate
1417    local store group if so.  */
1418
1419 static int
1420 record_store (rtx body, bb_info_t bb_info)
1421 {
1422   rtx mem, rhs, const_rhs, mem_addr;
1423   HOST_WIDE_INT offset = 0;
1424   HOST_WIDE_INT width = 0;
1425   alias_set_type spill_alias_set;
1426   insn_info_t insn_info = bb_info->last_insn;
1427   store_info_t store_info = NULL;
1428   int group_id;
1429   cselib_val *base = NULL;
1430   insn_info_t ptr, last, redundant_reason;
1431   bool store_is_unused;
1432
1433   if (GET_CODE (body) != SET && GET_CODE (body) != CLOBBER)
1434     return 0;
1435
1436   mem = SET_DEST (body);
1437
1438   /* If this is not used, then this cannot be used to keep the insn
1439      from being deleted.  On the other hand, it does provide something
1440      that can be used to prove that another store is dead.  */
1441   store_is_unused
1442     = (find_reg_note (insn_info->insn, REG_UNUSED, mem) != NULL);
1443
1444   /* Check whether that value is a suitable memory location.  */
1445   if (!MEM_P (mem))
1446     {
1447       /* If the set or clobber is unused, then it does not effect our
1448          ability to get rid of the entire insn.  */
1449       if (!store_is_unused)
1450         insn_info->cannot_delete = true;
1451       return 0;
1452     }
1453
1454   /* At this point we know mem is a mem. */
1455   if (GET_MODE (mem) == BLKmode)
1456     {
1457       if (GET_CODE (XEXP (mem, 0)) == SCRATCH)
1458         {
1459           if (dump_file && (dump_flags & TDF_DETAILS))
1460             fprintf (dump_file, " adding wild read for (clobber (mem:BLK (scratch))\n");
1461           add_wild_read (bb_info);
1462           insn_info->cannot_delete = true;
1463           return 0;
1464         }
1465       /* Handle (set (mem:BLK (addr) [... S36 ...]) (const_int 0))
1466          as memset (addr, 0, 36);  */
1467       else if (!MEM_SIZE_KNOWN_P (mem)
1468                || MEM_SIZE (mem) <= 0
1469                || MEM_SIZE (mem) > MAX_OFFSET
1470                || GET_CODE (body) != SET
1471                || !CONST_INT_P (SET_SRC (body)))
1472         {
1473           if (!store_is_unused)
1474             {
1475               /* If the set or clobber is unused, then it does not effect our
1476                  ability to get rid of the entire insn.  */
1477               insn_info->cannot_delete = true;
1478               clear_rhs_from_active_local_stores ();
1479             }
1480           return 0;
1481         }
1482     }
1483
1484   /* We can still process a volatile mem, we just cannot delete it.  */
1485   if (MEM_VOLATILE_P (mem))
1486     insn_info->cannot_delete = true;
1487
1488   if (!canon_address (mem, &spill_alias_set, &group_id, &offset, &base))
1489     {
1490       clear_rhs_from_active_local_stores ();
1491       return 0;
1492     }
1493
1494   if (GET_MODE (mem) == BLKmode)
1495     width = MEM_SIZE (mem);
1496   else
1497     width = GET_MODE_SIZE (GET_MODE (mem));
1498
1499   if (spill_alias_set)
1500     {
1501       bitmap store1 = clear_alias_group->store1_p;
1502       bitmap store2 = clear_alias_group->store2_p;
1503
1504       gcc_assert (GET_MODE (mem) != BLKmode);
1505
1506       if (!bitmap_set_bit (store1, spill_alias_set))
1507         bitmap_set_bit (store2, spill_alias_set);
1508
1509       if (clear_alias_group->offset_map_size_p < spill_alias_set)
1510         clear_alias_group->offset_map_size_p = spill_alias_set;
1511
1512       store_info = (store_info_t) pool_alloc (rtx_store_info_pool);
1513
1514       if (dump_file && (dump_flags & TDF_DETAILS))
1515         fprintf (dump_file, " processing spill store %d(%s)\n",
1516                  (int) spill_alias_set, GET_MODE_NAME (GET_MODE (mem)));
1517     }
1518   else if (group_id >= 0)
1519     {
1520       /* In the restrictive case where the base is a constant or the
1521          frame pointer we can do global analysis.  */
1522
1523       group_info_t group
1524         = rtx_group_vec[group_id];
1525       tree expr = MEM_EXPR (mem);
1526
1527       store_info = (store_info_t) pool_alloc (rtx_store_info_pool);
1528       set_usage_bits (group, offset, width, expr);
1529
1530       if (dump_file && (dump_flags & TDF_DETAILS))
1531         fprintf (dump_file, " processing const base store gid=%d[%d..%d)\n",
1532                  group_id, (int)offset, (int)(offset+width));
1533     }
1534   else
1535     {
1536       if (may_be_sp_based_p (XEXP (mem, 0)))
1537         insn_info->stack_pointer_based = true;
1538       insn_info->contains_cselib_groups = true;
1539
1540       store_info = (store_info_t) pool_alloc (cse_store_info_pool);
1541       group_id = -1;
1542
1543       if (dump_file && (dump_flags & TDF_DETAILS))
1544         fprintf (dump_file, " processing cselib store [%d..%d)\n",
1545                  (int)offset, (int)(offset+width));
1546     }
1547
1548   const_rhs = rhs = NULL_RTX;
1549   if (GET_CODE (body) == SET
1550       /* No place to keep the value after ra.  */
1551       && !reload_completed
1552       && (REG_P (SET_SRC (body))
1553           || GET_CODE (SET_SRC (body)) == SUBREG
1554           || CONSTANT_P (SET_SRC (body)))
1555       && !MEM_VOLATILE_P (mem)
1556       /* Sometimes the store and reload is used for truncation and
1557          rounding.  */
1558       && !(FLOAT_MODE_P (GET_MODE (mem)) && (flag_float_store)))
1559     {
1560       rhs = SET_SRC (body);
1561       if (CONSTANT_P (rhs))
1562         const_rhs = rhs;
1563       else if (body == PATTERN (insn_info->insn))
1564         {
1565           rtx tem = find_reg_note (insn_info->insn, REG_EQUAL, NULL_RTX);
1566           if (tem && CONSTANT_P (XEXP (tem, 0)))
1567             const_rhs = XEXP (tem, 0);
1568         }
1569       if (const_rhs == NULL_RTX && REG_P (rhs))
1570         {
1571           rtx tem = cselib_expand_value_rtx (rhs, scratch, 5);
1572
1573           if (tem && CONSTANT_P (tem))
1574             const_rhs = tem;
1575         }
1576     }
1577
1578   /* Check to see if this stores causes some other stores to be
1579      dead.  */
1580   ptr = active_local_stores;
1581   last = NULL;
1582   redundant_reason = NULL;
1583   mem = canon_rtx (mem);
1584   /* For alias_set != 0 canon_true_dependence should be never called.  */
1585   if (spill_alias_set)
1586     mem_addr = NULL_RTX;
1587   else
1588     {
1589       if (group_id < 0)
1590         mem_addr = base->val_rtx;
1591       else
1592         {
1593           group_info_t group
1594             = rtx_group_vec[group_id];
1595           mem_addr = group->canon_base_addr;
1596         }
1597       if (offset)
1598         mem_addr = plus_constant (get_address_mode (mem), mem_addr, offset);
1599     }
1600
1601   while (ptr)
1602     {
1603       insn_info_t next = ptr->next_local_store;
1604       store_info_t s_info = ptr->store_rec;
1605       bool del = true;
1606
1607       /* Skip the clobbers. We delete the active insn if this insn
1608          shadows the set.  To have been put on the active list, it
1609          has exactly on set. */
1610       while (!s_info->is_set)
1611         s_info = s_info->next;
1612
1613       if (s_info->alias_set != spill_alias_set)
1614         del = false;
1615       else if (s_info->alias_set)
1616         {
1617           struct clear_alias_mode_holder *entry
1618             = clear_alias_set_lookup (s_info->alias_set);
1619           /* Generally, spills cannot be processed if and of the
1620              references to the slot have a different mode.  But if
1621              we are in the same block and mode is exactly the same
1622              between this store and one before in the same block,
1623              we can still delete it.  */
1624           if ((GET_MODE (mem) == GET_MODE (s_info->mem))
1625               && (GET_MODE (mem) == entry->mode))
1626             {
1627               del = true;
1628               set_all_positions_unneeded (s_info);
1629             }
1630           if (dump_file && (dump_flags & TDF_DETAILS))
1631             fprintf (dump_file, "    trying spill store in insn=%d alias_set=%d\n",
1632                      INSN_UID (ptr->insn), (int) s_info->alias_set);
1633         }
1634       else if ((s_info->group_id == group_id)
1635                && (s_info->cse_base == base))
1636         {
1637           HOST_WIDE_INT i;
1638           if (dump_file && (dump_flags & TDF_DETAILS))
1639             fprintf (dump_file, "    trying store in insn=%d gid=%d[%d..%d)\n",
1640                      INSN_UID (ptr->insn), s_info->group_id,
1641                      (int)s_info->begin, (int)s_info->end);
1642
1643           /* Even if PTR won't be eliminated as unneeded, if both
1644              PTR and this insn store the same constant value, we might
1645              eliminate this insn instead.  */
1646           if (s_info->const_rhs
1647               && const_rhs
1648               && offset >= s_info->begin
1649               && offset + width <= s_info->end
1650               && all_positions_needed_p (s_info, offset - s_info->begin,
1651                                          width))
1652             {
1653               if (GET_MODE (mem) == BLKmode)
1654                 {
1655                   if (GET_MODE (s_info->mem) == BLKmode
1656                       && s_info->const_rhs == const_rhs)
1657                     redundant_reason = ptr;
1658                 }
1659               else if (s_info->const_rhs == const0_rtx
1660                        && const_rhs == const0_rtx)
1661                 redundant_reason = ptr;
1662               else
1663                 {
1664                   rtx val;
1665                   start_sequence ();
1666                   val = get_stored_val (s_info, GET_MODE (mem),
1667                                         offset, offset + width,
1668                                         BLOCK_FOR_INSN (insn_info->insn),
1669                                         true);
1670                   if (get_insns () != NULL)
1671                     val = NULL_RTX;
1672                   end_sequence ();
1673                   if (val && rtx_equal_p (val, const_rhs))
1674                     redundant_reason = ptr;
1675                 }
1676             }
1677
1678           for (i = MAX (offset, s_info->begin);
1679                i < offset + width && i < s_info->end;
1680                i++)
1681             set_position_unneeded (s_info, i - s_info->begin);
1682         }
1683       else if (s_info->rhs)
1684         /* Need to see if it is possible for this store to overwrite
1685            the value of store_info.  If it is, set the rhs to NULL to
1686            keep it from being used to remove a load.  */
1687         {
1688           if (canon_true_dependence (s_info->mem,
1689                                      GET_MODE (s_info->mem),
1690                                      s_info->mem_addr,
1691                                      mem, mem_addr))
1692             {
1693               s_info->rhs = NULL;
1694               s_info->const_rhs = NULL;
1695             }
1696         }
1697
1698       /* An insn can be deleted if every position of every one of
1699          its s_infos is zero.  */
1700       if (any_positions_needed_p (s_info))
1701         del = false;
1702
1703       if (del)
1704         {
1705           insn_info_t insn_to_delete = ptr;
1706
1707           active_local_stores_len--;
1708           if (last)
1709             last->next_local_store = ptr->next_local_store;
1710           else
1711             active_local_stores = ptr->next_local_store;
1712
1713           if (!insn_to_delete->cannot_delete)
1714             delete_dead_store_insn (insn_to_delete);
1715         }
1716       else
1717         last = ptr;
1718
1719       ptr = next;
1720     }
1721
1722   /* Finish filling in the store_info.  */
1723   store_info->next = insn_info->store_rec;
1724   insn_info->store_rec = store_info;
1725   store_info->mem = mem;
1726   store_info->alias_set = spill_alias_set;
1727   store_info->mem_addr = mem_addr;
1728   store_info->cse_base = base;
1729   if (width > HOST_BITS_PER_WIDE_INT)
1730     {
1731       store_info->is_large = true;
1732       store_info->positions_needed.large.count = 0;
1733       store_info->positions_needed.large.bmap = BITMAP_ALLOC (&dse_bitmap_obstack);
1734     }
1735   else
1736     {
1737       store_info->is_large = false;
1738       store_info->positions_needed.small_bitmask = lowpart_bitmask (width);
1739     }
1740   store_info->group_id = group_id;
1741   store_info->begin = offset;
1742   store_info->end = offset + width;
1743   store_info->is_set = GET_CODE (body) == SET;
1744   store_info->rhs = rhs;
1745   store_info->const_rhs = const_rhs;
1746   store_info->redundant_reason = redundant_reason;
1747
1748   /* If this is a clobber, we return 0.  We will only be able to
1749      delete this insn if there is only one store USED store, but we
1750      can use the clobber to delete other stores earlier.  */
1751   return store_info->is_set ? 1 : 0;
1752 }
1753
1754
1755 static void
1756 dump_insn_info (const char * start, insn_info_t insn_info)
1757 {
1758   fprintf (dump_file, "%s insn=%d %s\n", start,
1759            INSN_UID (insn_info->insn),
1760            insn_info->store_rec ? "has store" : "naked");
1761 }
1762
1763
1764 /* If the modes are different and the value's source and target do not
1765    line up, we need to extract the value from lower part of the rhs of
1766    the store, shift it, and then put it into a form that can be shoved
1767    into the read_insn.  This function generates a right SHIFT of a
1768    value that is at least ACCESS_SIZE bytes wide of READ_MODE.  The
1769    shift sequence is returned or NULL if we failed to find a
1770    shift.  */
1771
1772 static rtx
1773 find_shift_sequence (int access_size,
1774                      store_info_t store_info,
1775                      enum machine_mode read_mode,
1776                      int shift, bool speed, bool require_cst)
1777 {
1778   enum machine_mode store_mode = GET_MODE (store_info->mem);
1779   enum machine_mode new_mode;
1780   rtx read_reg = NULL;
1781
1782   /* Some machines like the x86 have shift insns for each size of
1783      operand.  Other machines like the ppc or the ia-64 may only have
1784      shift insns that shift values within 32 or 64 bit registers.
1785      This loop tries to find the smallest shift insn that will right
1786      justify the value we want to read but is available in one insn on
1787      the machine.  */
1788
1789   for (new_mode = smallest_mode_for_size (access_size * BITS_PER_UNIT,
1790                                           MODE_INT);
1791        GET_MODE_BITSIZE (new_mode) <= BITS_PER_WORD;
1792        new_mode = GET_MODE_WIDER_MODE (new_mode))
1793     {
1794       rtx target, new_reg, shift_seq, insn, new_lhs;
1795       int cost;
1796
1797       /* If a constant was stored into memory, try to simplify it here,
1798          otherwise the cost of the shift might preclude this optimization
1799          e.g. at -Os, even when no actual shift will be needed.  */
1800       if (store_info->const_rhs)
1801         {
1802           unsigned int byte = subreg_lowpart_offset (new_mode, store_mode);
1803           rtx ret = simplify_subreg (new_mode, store_info->const_rhs,
1804                                      store_mode, byte);
1805           if (ret && CONSTANT_P (ret))
1806             {
1807               ret = simplify_const_binary_operation (LSHIFTRT, new_mode,
1808                                                      ret, GEN_INT (shift));
1809               if (ret && CONSTANT_P (ret))
1810                 {
1811                   byte = subreg_lowpart_offset (read_mode, new_mode);
1812                   ret = simplify_subreg (read_mode, ret, new_mode, byte);
1813                   if (ret && CONSTANT_P (ret)
1814                       && set_src_cost (ret, speed) <= COSTS_N_INSNS (1))
1815                     return ret;
1816                 }
1817             }
1818         }
1819
1820       if (require_cst)
1821         return NULL_RTX;
1822
1823       /* Try a wider mode if truncating the store mode to NEW_MODE
1824          requires a real instruction.  */
1825       if (GET_MODE_BITSIZE (new_mode) < GET_MODE_BITSIZE (store_mode)
1826           && !TRULY_NOOP_TRUNCATION_MODES_P (new_mode, store_mode))
1827         continue;
1828
1829       /* Also try a wider mode if the necessary punning is either not
1830          desirable or not possible.  */
1831       if (!CONSTANT_P (store_info->rhs)
1832           && !MODES_TIEABLE_P (new_mode, store_mode))
1833         continue;
1834
1835       new_reg = gen_reg_rtx (new_mode);
1836
1837       start_sequence ();
1838
1839       /* In theory we could also check for an ashr.  Ian Taylor knows
1840          of one dsp where the cost of these two was not the same.  But
1841          this really is a rare case anyway.  */
1842       target = expand_binop (new_mode, lshr_optab, new_reg,
1843                              GEN_INT (shift), new_reg, 1, OPTAB_DIRECT);
1844
1845       shift_seq = get_insns ();
1846       end_sequence ();
1847
1848       if (target != new_reg || shift_seq == NULL)
1849         continue;
1850
1851       cost = 0;
1852       for (insn = shift_seq; insn != NULL_RTX; insn = NEXT_INSN (insn))
1853         if (INSN_P (insn))
1854           cost += insn_rtx_cost (PATTERN (insn), speed);
1855
1856       /* The computation up to here is essentially independent
1857          of the arguments and could be precomputed.  It may
1858          not be worth doing so.  We could precompute if
1859          worthwhile or at least cache the results.  The result
1860          technically depends on both SHIFT and ACCESS_SIZE,
1861          but in practice the answer will depend only on ACCESS_SIZE.  */
1862
1863       if (cost > COSTS_N_INSNS (1))
1864         continue;
1865
1866       new_lhs = extract_low_bits (new_mode, store_mode,
1867                                   copy_rtx (store_info->rhs));
1868       if (new_lhs == NULL_RTX)
1869         continue;
1870
1871       /* We found an acceptable shift.  Generate a move to
1872          take the value from the store and put it into the
1873          shift pseudo, then shift it, then generate another
1874          move to put in into the target of the read.  */
1875       emit_move_insn (new_reg, new_lhs);
1876       emit_insn (shift_seq);
1877       read_reg = extract_low_bits (read_mode, new_mode, new_reg);
1878       break;
1879     }
1880
1881   return read_reg;
1882 }
1883
1884
1885 /* Call back for note_stores to find the hard regs set or clobbered by
1886    insn.  Data is a bitmap of the hardregs set so far.  */
1887
1888 static void
1889 look_for_hardregs (rtx x, const_rtx pat ATTRIBUTE_UNUSED, void *data)
1890 {
1891   bitmap regs_set = (bitmap) data;
1892
1893   if (REG_P (x)
1894       && HARD_REGISTER_P (x))
1895     {
1896       unsigned int regno = REGNO (x);
1897       bitmap_set_range (regs_set, regno,
1898                         hard_regno_nregs[regno][GET_MODE (x)]);
1899     }
1900 }
1901
1902 /* Helper function for replace_read and record_store.
1903    Attempt to return a value stored in STORE_INFO, from READ_BEGIN
1904    to one before READ_END bytes read in READ_MODE.  Return NULL
1905    if not successful.  If REQUIRE_CST is true, return always constant.  */
1906
1907 static rtx
1908 get_stored_val (store_info_t store_info, enum machine_mode read_mode,
1909                 HOST_WIDE_INT read_begin, HOST_WIDE_INT read_end,
1910                 basic_block bb, bool require_cst)
1911 {
1912   enum machine_mode store_mode = GET_MODE (store_info->mem);
1913   int shift;
1914   int access_size; /* In bytes.  */
1915   rtx read_reg;
1916
1917   /* To get here the read is within the boundaries of the write so
1918      shift will never be negative.  Start out with the shift being in
1919      bytes.  */
1920   if (store_mode == BLKmode)
1921     shift = 0;
1922   else if (BYTES_BIG_ENDIAN)
1923     shift = store_info->end - read_end;
1924   else
1925     shift = read_begin - store_info->begin;
1926
1927   access_size = shift + GET_MODE_SIZE (read_mode);
1928
1929   /* From now on it is bits.  */
1930   shift *= BITS_PER_UNIT;
1931
1932   if (shift)
1933     read_reg = find_shift_sequence (access_size, store_info, read_mode, shift,
1934                                     optimize_bb_for_speed_p (bb),
1935                                     require_cst);
1936   else if (store_mode == BLKmode)
1937     {
1938       /* The store is a memset (addr, const_val, const_size).  */
1939       gcc_assert (CONST_INT_P (store_info->rhs));
1940       store_mode = int_mode_for_mode (read_mode);
1941       if (store_mode == BLKmode)
1942         read_reg = NULL_RTX;
1943       else if (store_info->rhs == const0_rtx)
1944         read_reg = extract_low_bits (read_mode, store_mode, const0_rtx);
1945       else if (GET_MODE_BITSIZE (store_mode) > HOST_BITS_PER_WIDE_INT
1946                || BITS_PER_UNIT >= HOST_BITS_PER_WIDE_INT)
1947         read_reg = NULL_RTX;
1948       else
1949         {
1950           unsigned HOST_WIDE_INT c
1951             = INTVAL (store_info->rhs)
1952               & (((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
1953           int shift = BITS_PER_UNIT;
1954           while (shift < HOST_BITS_PER_WIDE_INT)
1955             {
1956               c |= (c << shift);
1957               shift <<= 1;
1958             }
1959           read_reg = gen_int_mode (c, store_mode);
1960           read_reg = extract_low_bits (read_mode, store_mode, read_reg);
1961         }
1962     }
1963   else if (store_info->const_rhs
1964            && (require_cst
1965                || GET_MODE_CLASS (read_mode) != GET_MODE_CLASS (store_mode)))
1966     read_reg = extract_low_bits (read_mode, store_mode,
1967                                  copy_rtx (store_info->const_rhs));
1968   else
1969     read_reg = extract_low_bits (read_mode, store_mode,
1970                                  copy_rtx (store_info->rhs));
1971   if (require_cst && read_reg && !CONSTANT_P (read_reg))
1972     read_reg = NULL_RTX;
1973   return read_reg;
1974 }
1975
1976 /* Take a sequence of:
1977      A <- r1
1978      ...
1979      ... <- A
1980
1981    and change it into
1982    r2 <- r1
1983    A <- r1
1984    ...
1985    ... <- r2
1986
1987    or
1988
1989    r3 <- extract (r1)
1990    r3 <- r3 >> shift
1991    r2 <- extract (r3)
1992    ... <- r2
1993
1994    or
1995
1996    r2 <- extract (r1)
1997    ... <- r2
1998
1999    Depending on the alignment and the mode of the store and
2000    subsequent load.
2001
2002
2003    The STORE_INFO and STORE_INSN are for the store and READ_INFO
2004    and READ_INSN are for the read.  Return true if the replacement
2005    went ok.  */
2006
2007 static bool
2008 replace_read (store_info_t store_info, insn_info_t store_insn,
2009               read_info_t read_info, insn_info_t read_insn, rtx *loc,
2010               bitmap regs_live)
2011 {
2012   enum machine_mode store_mode = GET_MODE (store_info->mem);
2013   enum machine_mode read_mode = GET_MODE (read_info->mem);
2014   rtx insns, this_insn, read_reg;
2015   basic_block bb;
2016
2017   if (!dbg_cnt (dse))
2018     return false;
2019
2020   /* Create a sequence of instructions to set up the read register.
2021      This sequence goes immediately before the store and its result
2022      is read by the load.
2023
2024      We need to keep this in perspective.  We are replacing a read
2025      with a sequence of insns, but the read will almost certainly be
2026      in cache, so it is not going to be an expensive one.  Thus, we
2027      are not willing to do a multi insn shift or worse a subroutine
2028      call to get rid of the read.  */
2029   if (dump_file && (dump_flags & TDF_DETAILS))
2030     fprintf (dump_file, "trying to replace %smode load in insn %d"
2031              " from %smode store in insn %d\n",
2032              GET_MODE_NAME (read_mode), INSN_UID (read_insn->insn),
2033              GET_MODE_NAME (store_mode), INSN_UID (store_insn->insn));
2034   start_sequence ();
2035   bb = BLOCK_FOR_INSN (read_insn->insn);
2036   read_reg = get_stored_val (store_info,
2037                              read_mode, read_info->begin, read_info->end,
2038                              bb, false);
2039   if (read_reg == NULL_RTX)
2040     {
2041       end_sequence ();
2042       if (dump_file && (dump_flags & TDF_DETAILS))
2043         fprintf (dump_file, " -- could not extract bits of stored value\n");
2044       return false;
2045     }
2046   /* Force the value into a new register so that it won't be clobbered
2047      between the store and the load.  */
2048   read_reg = copy_to_mode_reg (read_mode, read_reg);
2049   insns = get_insns ();
2050   end_sequence ();
2051
2052   if (insns != NULL_RTX)
2053     {
2054       /* Now we have to scan the set of new instructions to see if the
2055          sequence contains and sets of hardregs that happened to be
2056          live at this point.  For instance, this can happen if one of
2057          the insns sets the CC and the CC happened to be live at that
2058          point.  This does occasionally happen, see PR 37922.  */
2059       bitmap regs_set = BITMAP_ALLOC (&reg_obstack);
2060
2061       for (this_insn = insns; this_insn != NULL_RTX; this_insn = NEXT_INSN (this_insn))
2062         note_stores (PATTERN (this_insn), look_for_hardregs, regs_set);
2063
2064       bitmap_and_into (regs_set, regs_live);
2065       if (!bitmap_empty_p (regs_set))
2066         {
2067           if (dump_file && (dump_flags & TDF_DETAILS))
2068             {
2069               fprintf (dump_file,
2070                        "abandoning replacement because sequence clobbers live hardregs:");
2071               df_print_regset (dump_file, regs_set);
2072             }
2073
2074           BITMAP_FREE (regs_set);
2075           return false;
2076         }
2077       BITMAP_FREE (regs_set);
2078     }
2079
2080   if (validate_change (read_insn->insn, loc, read_reg, 0))
2081     {
2082       deferred_change_t deferred_change =
2083         (deferred_change_t) pool_alloc (deferred_change_pool);
2084
2085       /* Insert this right before the store insn where it will be safe
2086          from later insns that might change it before the read.  */
2087       emit_insn_before (insns, store_insn->insn);
2088
2089       /* And now for the kludge part: cselib croaks if you just
2090          return at this point.  There are two reasons for this:
2091
2092          1) Cselib has an idea of how many pseudos there are and
2093          that does not include the new ones we just added.
2094
2095          2) Cselib does not know about the move insn we added
2096          above the store_info, and there is no way to tell it
2097          about it, because it has "moved on".
2098
2099          Problem (1) is fixable with a certain amount of engineering.
2100          Problem (2) is requires starting the bb from scratch.  This
2101          could be expensive.
2102
2103          So we are just going to have to lie.  The move/extraction
2104          insns are not really an issue, cselib did not see them.  But
2105          the use of the new pseudo read_insn is a real problem because
2106          cselib has not scanned this insn.  The way that we solve this
2107          problem is that we are just going to put the mem back for now
2108          and when we are finished with the block, we undo this.  We
2109          keep a table of mems to get rid of.  At the end of the basic
2110          block we can put them back.  */
2111
2112       *loc = read_info->mem;
2113       deferred_change->next = deferred_change_list;
2114       deferred_change_list = deferred_change;
2115       deferred_change->loc = loc;
2116       deferred_change->reg = read_reg;
2117
2118       /* Get rid of the read_info, from the point of view of the
2119          rest of dse, play like this read never happened.  */
2120       read_insn->read_rec = read_info->next;
2121       pool_free (read_info_pool, read_info);
2122       if (dump_file && (dump_flags & TDF_DETAILS))
2123         {
2124           fprintf (dump_file, " -- replaced the loaded MEM with ");
2125           print_simple_rtl (dump_file, read_reg);
2126           fprintf (dump_file, "\n");
2127         }
2128       return true;
2129     }
2130   else
2131     {
2132       if (dump_file && (dump_flags & TDF_DETAILS))
2133         {
2134           fprintf (dump_file, " -- replacing the loaded MEM with ");
2135           print_simple_rtl (dump_file, read_reg);
2136           fprintf (dump_file, " led to an invalid instruction\n");
2137         }
2138       return false;
2139     }
2140 }
2141
2142 /* A for_each_rtx callback in which DATA is the bb_info.  Check to see
2143    if LOC is a mem and if it is look at the address and kill any
2144    appropriate stores that may be active.  */
2145
2146 static int
2147 check_mem_read_rtx (rtx *loc, void *data)
2148 {
2149   rtx mem = *loc, mem_addr;
2150   bb_info_t bb_info;
2151   insn_info_t insn_info;
2152   HOST_WIDE_INT offset = 0;
2153   HOST_WIDE_INT width = 0;
2154   alias_set_type spill_alias_set = 0;
2155   cselib_val *base = NULL;
2156   int group_id;
2157   read_info_t read_info;
2158
2159   if (!mem || !MEM_P (mem))
2160     return 0;
2161
2162   bb_info = (bb_info_t) data;
2163   insn_info = bb_info->last_insn;
2164
2165   if ((MEM_ALIAS_SET (mem) == ALIAS_SET_MEMORY_BARRIER)
2166       || (MEM_VOLATILE_P (mem)))
2167     {
2168       if (dump_file && (dump_flags & TDF_DETAILS))
2169         fprintf (dump_file, " adding wild read, volatile or barrier.\n");
2170       add_wild_read (bb_info);
2171       insn_info->cannot_delete = true;
2172       return 0;
2173     }
2174
2175   /* If it is reading readonly mem, then there can be no conflict with
2176      another write. */
2177   if (MEM_READONLY_P (mem))
2178     return 0;
2179
2180   if (!canon_address (mem, &spill_alias_set, &group_id, &offset, &base))
2181     {
2182       if (dump_file && (dump_flags & TDF_DETAILS))
2183         fprintf (dump_file, " adding wild read, canon_address failure.\n");
2184       add_wild_read (bb_info);
2185       return 0;
2186     }
2187
2188   if (GET_MODE (mem) == BLKmode)
2189     width = -1;
2190   else
2191     width = GET_MODE_SIZE (GET_MODE (mem));
2192
2193   read_info = (read_info_t) pool_alloc (read_info_pool);
2194   read_info->group_id = group_id;
2195   read_info->mem = mem;
2196   read_info->alias_set = spill_alias_set;
2197   read_info->begin = offset;
2198   read_info->end = offset + width;
2199   read_info->next = insn_info->read_rec;
2200   insn_info->read_rec = read_info;
2201   /* For alias_set != 0 canon_true_dependence should be never called.  */
2202   if (spill_alias_set)
2203     mem_addr = NULL_RTX;
2204   else
2205     {
2206       if (group_id < 0)
2207         mem_addr = base->val_rtx;
2208       else
2209         {
2210           group_info_t group
2211             = rtx_group_vec[group_id];
2212           mem_addr = group->canon_base_addr;
2213         }
2214       if (offset)
2215         mem_addr = plus_constant (get_address_mode (mem), mem_addr, offset);
2216     }
2217
2218   /* We ignore the clobbers in store_info.  The is mildly aggressive,
2219      but there really should not be a clobber followed by a read.  */
2220
2221   if (spill_alias_set)
2222     {
2223       insn_info_t i_ptr = active_local_stores;
2224       insn_info_t last = NULL;
2225
2226       if (dump_file && (dump_flags & TDF_DETAILS))
2227         fprintf (dump_file, " processing spill load %d\n",
2228                  (int) spill_alias_set);
2229
2230       while (i_ptr)
2231         {
2232           store_info_t store_info = i_ptr->store_rec;
2233
2234           /* Skip the clobbers.  */
2235           while (!store_info->is_set)
2236             store_info = store_info->next;
2237
2238           if (store_info->alias_set == spill_alias_set)
2239             {
2240               if (dump_file && (dump_flags & TDF_DETAILS))
2241                 dump_insn_info ("removing from active", i_ptr);
2242
2243               active_local_stores_len--;
2244               if (last)
2245                 last->next_local_store = i_ptr->next_local_store;
2246               else
2247                 active_local_stores = i_ptr->next_local_store;
2248             }
2249           else
2250             last = i_ptr;
2251           i_ptr = i_ptr->next_local_store;
2252         }
2253     }
2254   else if (group_id >= 0)
2255     {
2256       /* This is the restricted case where the base is a constant or
2257          the frame pointer and offset is a constant.  */
2258       insn_info_t i_ptr = active_local_stores;
2259       insn_info_t last = NULL;
2260
2261       if (dump_file && (dump_flags & TDF_DETAILS))
2262         {
2263           if (width == -1)
2264             fprintf (dump_file, " processing const load gid=%d[BLK]\n",
2265                      group_id);
2266           else
2267             fprintf (dump_file, " processing const load gid=%d[%d..%d)\n",
2268                      group_id, (int)offset, (int)(offset+width));
2269         }
2270
2271       while (i_ptr)
2272         {
2273           bool remove = false;
2274           store_info_t store_info = i_ptr->store_rec;
2275
2276           /* Skip the clobbers.  */
2277           while (!store_info->is_set)
2278             store_info = store_info->next;
2279
2280           /* There are three cases here.  */
2281           if (store_info->group_id < 0)
2282             /* We have a cselib store followed by a read from a
2283                const base. */
2284             remove
2285               = canon_true_dependence (store_info->mem,
2286                                        GET_MODE (store_info->mem),
2287                                        store_info->mem_addr,
2288                                        mem, mem_addr);
2289
2290           else if (group_id == store_info->group_id)
2291             {
2292               /* This is a block mode load.  We may get lucky and
2293                  canon_true_dependence may save the day.  */
2294               if (width == -1)
2295                 remove
2296                   = canon_true_dependence (store_info->mem,
2297                                            GET_MODE (store_info->mem),
2298                                            store_info->mem_addr,
2299                                            mem, mem_addr);
2300
2301               /* If this read is just reading back something that we just
2302                  stored, rewrite the read.  */
2303               else
2304                 {
2305                   if (store_info->rhs
2306                       && offset >= store_info->begin
2307                       && offset + width <= store_info->end
2308                       && all_positions_needed_p (store_info,
2309                                                  offset - store_info->begin,
2310                                                  width)
2311                       && replace_read (store_info, i_ptr, read_info,
2312                                        insn_info, loc, bb_info->regs_live))
2313                     return 0;
2314
2315                   /* The bases are the same, just see if the offsets
2316                      overlap.  */
2317                   if ((offset < store_info->end)
2318                       && (offset + width > store_info->begin))
2319                     remove = true;
2320                 }
2321             }
2322
2323           /* else
2324              The else case that is missing here is that the
2325              bases are constant but different.  There is nothing
2326              to do here because there is no overlap.  */
2327
2328           if (remove)
2329             {
2330               if (dump_file && (dump_flags & TDF_DETAILS))
2331                 dump_insn_info ("removing from active", i_ptr);
2332
2333               active_local_stores_len--;
2334               if (last)
2335                 last->next_local_store = i_ptr->next_local_store;
2336               else
2337                 active_local_stores = i_ptr->next_local_store;
2338             }
2339           else
2340             last = i_ptr;
2341           i_ptr = i_ptr->next_local_store;
2342         }
2343     }
2344   else
2345     {
2346       insn_info_t i_ptr = active_local_stores;
2347       insn_info_t last = NULL;
2348       if (dump_file && (dump_flags & TDF_DETAILS))
2349         {
2350           fprintf (dump_file, " processing cselib load mem:");
2351           print_inline_rtx (dump_file, mem, 0);
2352           fprintf (dump_file, "\n");
2353         }
2354
2355       while (i_ptr)
2356         {
2357           bool remove = false;
2358           store_info_t store_info = i_ptr->store_rec;
2359
2360           if (dump_file && (dump_flags & TDF_DETAILS))
2361             fprintf (dump_file, " processing cselib load against insn %d\n",
2362                      INSN_UID (i_ptr->insn));
2363
2364           /* Skip the clobbers.  */
2365           while (!store_info->is_set)
2366             store_info = store_info->next;
2367
2368           /* If this read is just reading back something that we just
2369              stored, rewrite the read.  */
2370           if (store_info->rhs
2371               && store_info->group_id == -1
2372               && store_info->cse_base == base
2373               && width != -1
2374               && offset >= store_info->begin
2375               && offset + width <= store_info->end
2376               && all_positions_needed_p (store_info,
2377                                          offset - store_info->begin, width)
2378               && replace_read (store_info, i_ptr,  read_info, insn_info, loc,
2379                                bb_info->regs_live))
2380             return 0;
2381
2382           if (!store_info->alias_set)
2383             remove = canon_true_dependence (store_info->mem,
2384                                             GET_MODE (store_info->mem),
2385                                             store_info->mem_addr,
2386                                             mem, mem_addr);
2387
2388           if (remove)
2389             {
2390               if (dump_file && (dump_flags & TDF_DETAILS))
2391                 dump_insn_info ("removing from active", i_ptr);
2392
2393               active_local_stores_len--;
2394               if (last)
2395                 last->next_local_store = i_ptr->next_local_store;
2396               else
2397                 active_local_stores = i_ptr->next_local_store;
2398             }
2399           else
2400             last = i_ptr;
2401           i_ptr = i_ptr->next_local_store;
2402         }
2403     }
2404   return 0;
2405 }
2406
2407 /* A for_each_rtx callback in which DATA points the INSN_INFO for
2408    as check_mem_read_rtx.  Nullify the pointer if i_m_r_m_r returns
2409    true for any part of *LOC.  */
2410
2411 static void
2412 check_mem_read_use (rtx *loc, void *data)
2413 {
2414   for_each_rtx (loc, check_mem_read_rtx, data);
2415 }
2416
2417
2418 /* Get arguments passed to CALL_INSN.  Return TRUE if successful.
2419    So far it only handles arguments passed in registers.  */
2420
2421 static bool
2422 get_call_args (rtx call_insn, tree fn, rtx *args, int nargs)
2423 {
2424   CUMULATIVE_ARGS args_so_far_v;
2425   cumulative_args_t args_so_far;
2426   tree arg;
2427   int idx;
2428
2429   INIT_CUMULATIVE_ARGS (args_so_far_v, TREE_TYPE (fn), NULL_RTX, 0, 3);
2430   args_so_far = pack_cumulative_args (&args_so_far_v);
2431
2432   arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
2433   for (idx = 0;
2434        arg != void_list_node && idx < nargs;
2435        arg = TREE_CHAIN (arg), idx++)
2436     {
2437       enum machine_mode mode = TYPE_MODE (TREE_VALUE (arg));
2438       rtx reg, link, tmp;
2439       reg = targetm.calls.function_arg (args_so_far, mode, NULL_TREE, true);
2440       if (!reg || !REG_P (reg) || GET_MODE (reg) != mode
2441           || GET_MODE_CLASS (mode) != MODE_INT)
2442         return false;
2443
2444       for (link = CALL_INSN_FUNCTION_USAGE (call_insn);
2445            link;
2446            link = XEXP (link, 1))
2447         if (GET_CODE (XEXP (link, 0)) == USE)
2448           {
2449             args[idx] = XEXP (XEXP (link, 0), 0);
2450             if (REG_P (args[idx])
2451                 && REGNO (args[idx]) == REGNO (reg)
2452                 && (GET_MODE (args[idx]) == mode
2453                     || (GET_MODE_CLASS (GET_MODE (args[idx])) == MODE_INT
2454                         && (GET_MODE_SIZE (GET_MODE (args[idx]))
2455                             <= UNITS_PER_WORD)
2456                         && (GET_MODE_SIZE (GET_MODE (args[idx]))
2457                             > GET_MODE_SIZE (mode)))))
2458               break;
2459           }
2460       if (!link)
2461         return false;
2462
2463       tmp = cselib_expand_value_rtx (args[idx], scratch, 5);
2464       if (GET_MODE (args[idx]) != mode)
2465         {
2466           if (!tmp || !CONST_INT_P (tmp))
2467             return false;
2468           tmp = gen_int_mode (INTVAL (tmp), mode);
2469         }
2470       if (tmp)
2471         args[idx] = tmp;
2472
2473       targetm.calls.function_arg_advance (args_so_far, mode, NULL_TREE, true);
2474     }
2475   if (arg != void_list_node || idx != nargs)
2476     return false;
2477   return true;
2478 }
2479
2480 /* Return a bitmap of the fixed registers contained in IN.  */
2481
2482 static bitmap
2483 copy_fixed_regs (const_bitmap in)
2484 {
2485   bitmap ret;
2486
2487   ret = ALLOC_REG_SET (NULL);
2488   bitmap_and (ret, in, fixed_reg_set_regset);
2489   return ret;
2490 }
2491
2492 /* Apply record_store to all candidate stores in INSN.  Mark INSN
2493    if some part of it is not a candidate store and assigns to a
2494    non-register target.  */
2495
2496 static void
2497 scan_insn (bb_info_t bb_info, rtx insn)
2498 {
2499   rtx body;
2500   insn_info_t insn_info = (insn_info_t) pool_alloc (insn_info_pool);
2501   int mems_found = 0;
2502   memset (insn_info, 0, sizeof (struct insn_info));
2503
2504   if (dump_file && (dump_flags & TDF_DETAILS))
2505     fprintf (dump_file, "\n**scanning insn=%d\n",
2506              INSN_UID (insn));
2507
2508   insn_info->prev_insn = bb_info->last_insn;
2509   insn_info->insn = insn;
2510   bb_info->last_insn = insn_info;
2511
2512   if (DEBUG_INSN_P (insn))
2513     {
2514       insn_info->cannot_delete = true;
2515       return;
2516     }
2517
2518   /* Cselib clears the table for this case, so we have to essentially
2519      do the same.  */
2520   if (NONJUMP_INSN_P (insn)
2521       && volatile_insn_p (PATTERN (insn)))
2522     {
2523       add_wild_read (bb_info);
2524       insn_info->cannot_delete = true;
2525       return;
2526     }
2527
2528   /* Look at all of the uses in the insn.  */
2529   note_uses (&PATTERN (insn), check_mem_read_use, bb_info);
2530
2531   if (CALL_P (insn))
2532     {
2533       bool const_call;
2534       tree memset_call = NULL_TREE;
2535
2536       insn_info->cannot_delete = true;
2537
2538       /* Const functions cannot do anything bad i.e. read memory,
2539          however, they can read their parameters which may have
2540          been pushed onto the stack.
2541          memset and bzero don't read memory either.  */
2542       const_call = RTL_CONST_CALL_P (insn);
2543       if (!const_call)
2544         {
2545           rtx call = get_call_rtx_from (insn);
2546           if (call && GET_CODE (XEXP (XEXP (call, 0), 0)) == SYMBOL_REF)
2547             {
2548               rtx symbol = XEXP (XEXP (call, 0), 0);
2549               if (SYMBOL_REF_DECL (symbol)
2550                   && TREE_CODE (SYMBOL_REF_DECL (symbol)) == FUNCTION_DECL)
2551                 {
2552                   if ((DECL_BUILT_IN_CLASS (SYMBOL_REF_DECL (symbol))
2553                        == BUILT_IN_NORMAL
2554                        && (DECL_FUNCTION_CODE (SYMBOL_REF_DECL (symbol))
2555                            == BUILT_IN_MEMSET))
2556                       || SYMBOL_REF_DECL (symbol) == block_clear_fn)
2557                     memset_call = SYMBOL_REF_DECL (symbol);
2558                 }
2559             }
2560         }
2561       if (const_call || memset_call)
2562         {
2563           insn_info_t i_ptr = active_local_stores;
2564           insn_info_t last = NULL;
2565
2566           if (dump_file && (dump_flags & TDF_DETAILS))
2567             fprintf (dump_file, "%s call %d\n",
2568                      const_call ? "const" : "memset", INSN_UID (insn));
2569
2570           /* See the head comment of the frame_read field.  */
2571           if (reload_completed)
2572             insn_info->frame_read = true;
2573
2574           /* Loop over the active stores and remove those which are
2575              killed by the const function call.  */
2576           while (i_ptr)
2577             {
2578               bool remove_store = false;
2579
2580               /* The stack pointer based stores are always killed.  */
2581               if (i_ptr->stack_pointer_based)
2582                 remove_store = true;
2583
2584               /* If the frame is read, the frame related stores are killed.  */
2585               else if (insn_info->frame_read)
2586                 {
2587                   store_info_t store_info = i_ptr->store_rec;
2588
2589                   /* Skip the clobbers.  */
2590                   while (!store_info->is_set)
2591                     store_info = store_info->next;
2592
2593                   if (store_info->group_id >= 0
2594                       && rtx_group_vec[store_info->group_id]->frame_related)
2595                     remove_store = true;
2596                 }
2597
2598               if (remove_store)
2599                 {
2600                   if (dump_file && (dump_flags & TDF_DETAILS))
2601                     dump_insn_info ("removing from active", i_ptr);
2602
2603                   active_local_stores_len--;
2604                   if (last)
2605                     last->next_local_store = i_ptr->next_local_store;
2606                   else
2607                     active_local_stores = i_ptr->next_local_store;
2608                 }
2609               else
2610                 last = i_ptr;
2611
2612               i_ptr = i_ptr->next_local_store;
2613             }
2614
2615           if (memset_call)
2616             {
2617               rtx args[3];
2618               if (get_call_args (insn, memset_call, args, 3)
2619                   && CONST_INT_P (args[1])
2620                   && CONST_INT_P (args[2])
2621                   && INTVAL (args[2]) > 0)
2622                 {
2623                   rtx mem = gen_rtx_MEM (BLKmode, args[0]);
2624                   set_mem_size (mem, INTVAL (args[2]));
2625                   body = gen_rtx_SET (VOIDmode, mem, args[1]);
2626                   mems_found += record_store (body, bb_info);
2627                   if (dump_file && (dump_flags & TDF_DETAILS))
2628                     fprintf (dump_file, "handling memset as BLKmode store\n");
2629                   if (mems_found == 1)
2630                     {
2631                       if (active_local_stores_len++
2632                           >= PARAM_VALUE (PARAM_MAX_DSE_ACTIVE_LOCAL_STORES))
2633                         {
2634                           active_local_stores_len = 1;
2635                           active_local_stores = NULL;
2636                         }
2637                       insn_info->fixed_regs_live
2638                         = copy_fixed_regs (bb_info->regs_live);
2639                       insn_info->next_local_store = active_local_stores;
2640                       active_local_stores = insn_info;
2641                     }
2642                 }
2643             }
2644         }
2645
2646       else
2647         /* Every other call, including pure functions, may read any memory
2648            that is not relative to the frame.  */
2649         add_non_frame_wild_read (bb_info);
2650
2651       return;
2652     }
2653
2654   /* Assuming that there are sets in these insns, we cannot delete
2655      them.  */
2656   if ((GET_CODE (PATTERN (insn)) == CLOBBER)
2657       || volatile_refs_p (PATTERN (insn))
2658       || (!cfun->can_delete_dead_exceptions && !insn_nothrow_p (insn))
2659       || (RTX_FRAME_RELATED_P (insn))
2660       || find_reg_note (insn, REG_FRAME_RELATED_EXPR, NULL_RTX))
2661     insn_info->cannot_delete = true;
2662
2663   body = PATTERN (insn);
2664   if (GET_CODE (body) == PARALLEL)
2665     {
2666       int i;
2667       for (i = 0; i < XVECLEN (body, 0); i++)
2668         mems_found += record_store (XVECEXP (body, 0, i), bb_info);
2669     }
2670   else
2671     mems_found += record_store (body, bb_info);
2672
2673   if (dump_file && (dump_flags & TDF_DETAILS))
2674     fprintf (dump_file, "mems_found = %d, cannot_delete = %s\n",
2675              mems_found, insn_info->cannot_delete ? "true" : "false");
2676
2677   /* If we found some sets of mems, add it into the active_local_stores so
2678      that it can be locally deleted if found dead or used for
2679      replace_read and redundant constant store elimination.  Otherwise mark
2680      it as cannot delete.  This simplifies the processing later.  */
2681   if (mems_found == 1)
2682     {
2683       if (active_local_stores_len++
2684           >= PARAM_VALUE (PARAM_MAX_DSE_ACTIVE_LOCAL_STORES))
2685         {
2686           active_local_stores_len = 1;
2687           active_local_stores = NULL;
2688         }
2689       insn_info->fixed_regs_live = copy_fixed_regs (bb_info->regs_live);
2690       insn_info->next_local_store = active_local_stores;
2691       active_local_stores = insn_info;
2692     }
2693   else
2694     insn_info->cannot_delete = true;
2695 }
2696
2697
2698 /* Remove BASE from the set of active_local_stores.  This is a
2699    callback from cselib that is used to get rid of the stores in
2700    active_local_stores.  */
2701
2702 static void
2703 remove_useless_values (cselib_val *base)
2704 {
2705   insn_info_t insn_info = active_local_stores;
2706   insn_info_t last = NULL;
2707
2708   while (insn_info)
2709     {
2710       store_info_t store_info = insn_info->store_rec;
2711       bool del = false;
2712
2713       /* If ANY of the store_infos match the cselib group that is
2714          being deleted, then the insn can not be deleted.  */
2715       while (store_info)
2716         {
2717           if ((store_info->group_id == -1)
2718               && (store_info->cse_base == base))
2719             {
2720               del = true;
2721               break;
2722             }
2723           store_info = store_info->next;
2724         }
2725
2726       if (del)
2727         {
2728           active_local_stores_len--;
2729           if (last)
2730             last->next_local_store = insn_info->next_local_store;
2731           else
2732             active_local_stores = insn_info->next_local_store;
2733           free_store_info (insn_info);
2734         }
2735       else
2736         last = insn_info;
2737
2738       insn_info = insn_info->next_local_store;
2739     }
2740 }
2741
2742
2743 /* Do all of step 1.  */
2744
2745 static void
2746 dse_step1 (void)
2747 {
2748   basic_block bb;
2749   bitmap regs_live = BITMAP_ALLOC (&reg_obstack);
2750
2751   cselib_init (0);
2752   all_blocks = BITMAP_ALLOC (NULL);
2753   bitmap_set_bit (all_blocks, ENTRY_BLOCK);
2754   bitmap_set_bit (all_blocks, EXIT_BLOCK);
2755
2756   FOR_ALL_BB (bb)
2757     {
2758       insn_info_t ptr;
2759       bb_info_t bb_info = (bb_info_t) pool_alloc (bb_info_pool);
2760
2761       memset (bb_info, 0, sizeof (struct bb_info));
2762       bitmap_set_bit (all_blocks, bb->index);
2763       bb_info->regs_live = regs_live;
2764
2765       bitmap_copy (regs_live, DF_LR_IN (bb));
2766       df_simulate_initialize_forwards (bb, regs_live);
2767
2768       bb_table[bb->index] = bb_info;
2769       cselib_discard_hook = remove_useless_values;
2770
2771       if (bb->index >= NUM_FIXED_BLOCKS)
2772         {
2773           rtx insn;
2774
2775           cse_store_info_pool
2776             = create_alloc_pool ("cse_store_info_pool",
2777                                  sizeof (struct store_info), 100);
2778           active_local_stores = NULL;
2779           active_local_stores_len = 0;
2780           cselib_clear_table ();
2781
2782           /* Scan the insns.  */
2783           FOR_BB_INSNS (bb, insn)
2784             {
2785               if (INSN_P (insn))
2786                 scan_insn (bb_info, insn);
2787               cselib_process_insn (insn);
2788               if (INSN_P (insn))
2789                 df_simulate_one_insn_forwards (bb, insn, regs_live);
2790             }
2791
2792           /* This is something of a hack, because the global algorithm
2793              is supposed to take care of the case where stores go dead
2794              at the end of the function.  However, the global
2795              algorithm must take a more conservative view of block
2796              mode reads than the local alg does.  So to get the case
2797              where you have a store to the frame followed by a non
2798              overlapping block more read, we look at the active local
2799              stores at the end of the function and delete all of the
2800              frame and spill based ones.  */
2801           if (stores_off_frame_dead_at_return
2802               && (EDGE_COUNT (bb->succs) == 0
2803                   || (single_succ_p (bb)
2804                       && single_succ (bb) == EXIT_BLOCK_PTR
2805                       && ! crtl->calls_eh_return)))
2806             {
2807               insn_info_t i_ptr = active_local_stores;
2808               while (i_ptr)
2809                 {
2810                   store_info_t store_info = i_ptr->store_rec;
2811
2812                   /* Skip the clobbers.  */
2813                   while (!store_info->is_set)
2814                     store_info = store_info->next;
2815                   if (store_info->alias_set && !i_ptr->cannot_delete)
2816                     delete_dead_store_insn (i_ptr);
2817                   else
2818                     if (store_info->group_id >= 0)
2819                       {
2820                         group_info_t group
2821                           = rtx_group_vec[store_info->group_id];
2822                         if (group->frame_related && !i_ptr->cannot_delete)
2823                           delete_dead_store_insn (i_ptr);
2824                       }
2825
2826                   i_ptr = i_ptr->next_local_store;
2827                 }
2828             }
2829
2830           /* Get rid of the loads that were discovered in
2831              replace_read.  Cselib is finished with this block.  */
2832           while (deferred_change_list)
2833             {
2834               deferred_change_t next = deferred_change_list->next;
2835
2836               /* There is no reason to validate this change.  That was
2837                  done earlier.  */
2838               *deferred_change_list->loc = deferred_change_list->reg;
2839               pool_free (deferred_change_pool, deferred_change_list);
2840               deferred_change_list = next;
2841             }
2842
2843           /* Get rid of all of the cselib based store_infos in this
2844              block and mark the containing insns as not being
2845              deletable.  */
2846           ptr = bb_info->last_insn;
2847           while (ptr)
2848             {
2849               if (ptr->contains_cselib_groups)
2850                 {
2851                   store_info_t s_info = ptr->store_rec;
2852                   while (s_info && !s_info->is_set)
2853                     s_info = s_info->next;
2854                   if (s_info
2855                       && s_info->redundant_reason
2856                       && s_info->redundant_reason->insn
2857                       && !ptr->cannot_delete)
2858                     {
2859                       if (dump_file && (dump_flags & TDF_DETAILS))
2860                         fprintf (dump_file, "Locally deleting insn %d "
2861                                             "because insn %d stores the "
2862                                             "same value and couldn't be "
2863                                             "eliminated\n",
2864                                  INSN_UID (ptr->insn),
2865                                  INSN_UID (s_info->redundant_reason->insn));
2866                       delete_dead_store_insn (ptr);
2867                     }
2868                   free_store_info (ptr);
2869                 }
2870               else
2871                 {
2872                   store_info_t s_info;
2873
2874                   /* Free at least positions_needed bitmaps.  */
2875                   for (s_info = ptr->store_rec; s_info; s_info = s_info->next)
2876                     if (s_info->is_large)
2877                       {
2878                         BITMAP_FREE (s_info->positions_needed.large.bmap);
2879                         s_info->is_large = false;
2880                       }
2881                 }
2882               ptr = ptr->prev_insn;
2883             }
2884
2885           free_alloc_pool (cse_store_info_pool);
2886         }
2887       bb_info->regs_live = NULL;
2888     }
2889
2890   BITMAP_FREE (regs_live);
2891   cselib_finish ();
2892   rtx_group_table.empty ();
2893 }
2894
2895 \f
2896 /*----------------------------------------------------------------------------
2897    Second step.
2898
2899    Assign each byte position in the stores that we are going to
2900    analyze globally to a position in the bitmaps.  Returns true if
2901    there are any bit positions assigned.
2902 ----------------------------------------------------------------------------*/
2903
2904 static void
2905 dse_step2_init (void)
2906 {
2907   unsigned int i;
2908   group_info_t group;
2909
2910   FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
2911     {
2912       /* For all non stack related bases, we only consider a store to
2913          be deletable if there are two or more stores for that
2914          position.  This is because it takes one store to make the
2915          other store redundant.  However, for the stores that are
2916          stack related, we consider them if there is only one store
2917          for the position.  We do this because the stack related
2918          stores can be deleted if their is no read between them and
2919          the end of the function.
2920
2921          To make this work in the current framework, we take the stack
2922          related bases add all of the bits from store1 into store2.
2923          This has the effect of making the eligible even if there is
2924          only one store.   */
2925
2926       if (stores_off_frame_dead_at_return && group->frame_related)
2927         {
2928           bitmap_ior_into (group->store2_n, group->store1_n);
2929           bitmap_ior_into (group->store2_p, group->store1_p);
2930           if (dump_file && (dump_flags & TDF_DETAILS))
2931             fprintf (dump_file, "group %d is frame related ", i);
2932         }
2933
2934       group->offset_map_size_n++;
2935       group->offset_map_n = XOBNEWVEC (&dse_obstack, int,
2936                                        group->offset_map_size_n);
2937       group->offset_map_size_p++;
2938       group->offset_map_p = XOBNEWVEC (&dse_obstack, int,
2939                                        group->offset_map_size_p);
2940       group->process_globally = false;
2941       if (dump_file && (dump_flags & TDF_DETAILS))
2942         {
2943           fprintf (dump_file, "group %d(%d+%d): ", i,
2944                    (int)bitmap_count_bits (group->store2_n),
2945                    (int)bitmap_count_bits (group->store2_p));
2946           bitmap_print (dump_file, group->store2_n, "n ", " ");
2947           bitmap_print (dump_file, group->store2_p, "p ", "\n");
2948         }
2949     }
2950 }
2951
2952
2953 /* Init the offset tables for the normal case.  */
2954
2955 static bool
2956 dse_step2_nospill (void)
2957 {
2958   unsigned int i;
2959   group_info_t group;
2960   /* Position 0 is unused because 0 is used in the maps to mean
2961      unused.  */
2962   current_position = 1;
2963   FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
2964     {
2965       bitmap_iterator bi;
2966       unsigned int j;
2967
2968       if (group == clear_alias_group)
2969         continue;
2970
2971       memset (group->offset_map_n, 0, sizeof(int) * group->offset_map_size_n);
2972       memset (group->offset_map_p, 0, sizeof(int) * group->offset_map_size_p);
2973       bitmap_clear (group->group_kill);
2974
2975       EXECUTE_IF_SET_IN_BITMAP (group->store2_n, 0, j, bi)
2976         {
2977           bitmap_set_bit (group->group_kill, current_position);
2978           if (bitmap_bit_p (group->escaped_n, j))
2979             bitmap_set_bit (kill_on_calls, current_position);
2980           group->offset_map_n[j] = current_position++;
2981           group->process_globally = true;
2982         }
2983       EXECUTE_IF_SET_IN_BITMAP (group->store2_p, 0, j, bi)
2984         {
2985           bitmap_set_bit (group->group_kill, current_position);
2986           if (bitmap_bit_p (group->escaped_p, j))
2987             bitmap_set_bit (kill_on_calls, current_position);
2988           group->offset_map_p[j] = current_position++;
2989           group->process_globally = true;
2990         }
2991     }
2992   return current_position != 1;
2993 }
2994
2995
2996 /* Init the offset tables for the spill case.  */
2997
2998 static bool
2999 dse_step2_spill (void)
3000 {
3001   unsigned int j;
3002   group_info_t group = clear_alias_group;
3003   bitmap_iterator bi;
3004
3005   /* Position 0 is unused because 0 is used in the maps to mean
3006      unused.  */
3007   current_position = 1;
3008
3009   if (dump_file && (dump_flags & TDF_DETAILS))
3010     {
3011       bitmap_print (dump_file, clear_alias_sets,
3012                     "clear alias sets              ", "\n");
3013       bitmap_print (dump_file, disqualified_clear_alias_sets,
3014                     "disqualified clear alias sets ", "\n");
3015     }
3016
3017   memset (group->offset_map_n, 0, sizeof(int) * group->offset_map_size_n);
3018   memset (group->offset_map_p, 0, sizeof(int) * group->offset_map_size_p);
3019   bitmap_clear (group->group_kill);
3020
3021   /* Remove the disqualified positions from the store2_p set.  */
3022   bitmap_and_compl_into (group->store2_p, disqualified_clear_alias_sets);
3023
3024   /* We do not need to process the store2_n set because
3025      alias_sets are always positive.  */
3026   EXECUTE_IF_SET_IN_BITMAP (group->store2_p, 0, j, bi)
3027     {
3028       bitmap_set_bit (group->group_kill, current_position);
3029       group->offset_map_p[j] = current_position++;
3030       group->process_globally = true;
3031     }
3032
3033   return current_position != 1;
3034 }
3035
3036
3037 \f
3038 /*----------------------------------------------------------------------------
3039   Third step.
3040
3041   Build the bit vectors for the transfer functions.
3042 ----------------------------------------------------------------------------*/
3043
3044
3045 /* Look up the bitmap index for OFFSET in GROUP_INFO.  If it is not
3046    there, return 0.  */
3047
3048 static int
3049 get_bitmap_index (group_info_t group_info, HOST_WIDE_INT offset)
3050 {
3051   if (offset < 0)
3052     {
3053       HOST_WIDE_INT offset_p = -offset;
3054       if (offset_p >= group_info->offset_map_size_n)
3055         return 0;
3056       return group_info->offset_map_n[offset_p];
3057     }
3058   else
3059     {
3060       if (offset >= group_info->offset_map_size_p)
3061         return 0;
3062       return group_info->offset_map_p[offset];
3063     }
3064 }
3065
3066
3067 /* Process the STORE_INFOs into the bitmaps into GEN and KILL.  KILL
3068    may be NULL. */
3069
3070 static void
3071 scan_stores_nospill (store_info_t store_info, bitmap gen, bitmap kill)
3072 {
3073   while (store_info)
3074     {
3075       HOST_WIDE_INT i;
3076       group_info_t group_info
3077         = rtx_group_vec[store_info->group_id];
3078       if (group_info->process_globally)
3079         for (i = store_info->begin; i < store_info->end; i++)
3080           {
3081             int index = get_bitmap_index (group_info, i);
3082             if (index != 0)
3083               {
3084                 bitmap_set_bit (gen, index);
3085                 if (kill)
3086                   bitmap_clear_bit (kill, index);
3087               }
3088           }
3089       store_info = store_info->next;
3090     }
3091 }
3092
3093
3094 /* Process the STORE_INFOs into the bitmaps into GEN and KILL.  KILL
3095    may be NULL. */
3096
3097 static void
3098 scan_stores_spill (store_info_t store_info, bitmap gen, bitmap kill)
3099 {
3100   while (store_info)
3101     {
3102       if (store_info->alias_set)
3103         {
3104           int index = get_bitmap_index (clear_alias_group,
3105                                         store_info->alias_set);
3106           if (index != 0)
3107             {
3108               bitmap_set_bit (gen, index);
3109               if (kill)
3110                 bitmap_clear_bit (kill, index);
3111             }
3112         }
3113       store_info = store_info->next;
3114     }
3115 }
3116
3117
3118 /* Process the READ_INFOs into the bitmaps into GEN and KILL.  KILL
3119    may be NULL.  */
3120
3121 static void
3122 scan_reads_nospill (insn_info_t insn_info, bitmap gen, bitmap kill)
3123 {
3124   read_info_t read_info = insn_info->read_rec;
3125   int i;
3126   group_info_t group;
3127
3128   /* If this insn reads the frame, kill all the frame related stores.  */
3129   if (insn_info->frame_read)
3130     {
3131       FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
3132         if (group->process_globally && group->frame_related)
3133           {
3134             if (kill)
3135               bitmap_ior_into (kill, group->group_kill);
3136             bitmap_and_compl_into (gen, group->group_kill);
3137           }
3138     }
3139   if (insn_info->non_frame_wild_read)
3140     {
3141       /* Kill all non-frame related stores.  Kill all stores of variables that
3142          escape.  */
3143       if (kill)
3144         bitmap_ior_into (kill, kill_on_calls);
3145       bitmap_and_compl_into (gen, kill_on_calls);
3146       FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
3147         if (group->process_globally && !group->frame_related)
3148           {
3149             if (kill)
3150               bitmap_ior_into (kill, group->group_kill);
3151             bitmap_and_compl_into (gen, group->group_kill);
3152           }
3153     }
3154   while (read_info)
3155     {
3156       FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
3157         {
3158           if (group->process_globally)
3159             {
3160               if (i == read_info->group_id)
3161                 {
3162                   if (read_info->begin > read_info->end)
3163                     {
3164                       /* Begin > end for block mode reads.  */
3165                       if (kill)
3166                         bitmap_ior_into (kill, group->group_kill);
3167                       bitmap_and_compl_into (gen, group->group_kill);
3168                     }
3169                   else
3170                     {
3171                       /* The groups are the same, just process the
3172                          offsets.  */
3173                       HOST_WIDE_INT j;
3174                       for (j = read_info->begin; j < read_info->end; j++)
3175                         {
3176                           int index = get_bitmap_index (group, j);
3177                           if (index != 0)
3178                             {
3179                               if (kill)
3180                                 bitmap_set_bit (kill, index);
3181                               bitmap_clear_bit (gen, index);
3182                             }
3183                         }
3184                     }
3185                 }
3186               else
3187                 {
3188                   /* The groups are different, if the alias sets
3189                      conflict, clear the entire group.  We only need
3190                      to apply this test if the read_info is a cselib
3191                      read.  Anything with a constant base cannot alias
3192                      something else with a different constant
3193                      base.  */
3194                   if ((read_info->group_id < 0)
3195                       && canon_true_dependence (group->base_mem,
3196                                                 GET_MODE (group->base_mem),
3197                                                 group->canon_base_addr,
3198                                                 read_info->mem, NULL_RTX))
3199                     {
3200                       if (kill)
3201                         bitmap_ior_into (kill, group->group_kill);
3202                       bitmap_and_compl_into (gen, group->group_kill);
3203                     }
3204                 }
3205             }
3206         }
3207
3208       read_info = read_info->next;
3209     }
3210 }
3211
3212 /* Process the READ_INFOs into the bitmaps into GEN and KILL.  KILL
3213    may be NULL.  */
3214
3215 static void
3216 scan_reads_spill (read_info_t read_info, bitmap gen, bitmap kill)
3217 {
3218   while (read_info)
3219     {
3220       if (read_info->alias_set)
3221         {
3222           int index = get_bitmap_index (clear_alias_group,
3223                                         read_info->alias_set);
3224           if (index != 0)
3225             {
3226               if (kill)
3227                 bitmap_set_bit (kill, index);
3228               bitmap_clear_bit (gen, index);
3229             }
3230         }
3231
3232       read_info = read_info->next;
3233     }
3234 }
3235
3236
3237 /* Return the insn in BB_INFO before the first wild read or if there
3238    are no wild reads in the block, return the last insn.  */
3239
3240 static insn_info_t
3241 find_insn_before_first_wild_read (bb_info_t bb_info)
3242 {
3243   insn_info_t insn_info = bb_info->last_insn;
3244   insn_info_t last_wild_read = NULL;
3245
3246   while (insn_info)
3247     {
3248       if (insn_info->wild_read)
3249         {
3250           last_wild_read = insn_info->prev_insn;
3251           /* Block starts with wild read.  */
3252           if (!last_wild_read)
3253             return NULL;
3254         }
3255
3256       insn_info = insn_info->prev_insn;
3257     }
3258
3259   if (last_wild_read)
3260     return last_wild_read;
3261   else
3262     return bb_info->last_insn;
3263 }
3264
3265
3266 /* Scan the insns in BB_INFO starting at PTR and going to the top of
3267    the block in order to build the gen and kill sets for the block.
3268    We start at ptr which may be the last insn in the block or may be
3269    the first insn with a wild read.  In the latter case we are able to
3270    skip the rest of the block because it just does not matter:
3271    anything that happens is hidden by the wild read.  */
3272
3273 static void
3274 dse_step3_scan (bool for_spills, basic_block bb)
3275 {
3276   bb_info_t bb_info = bb_table[bb->index];
3277   insn_info_t insn_info;
3278
3279   if (for_spills)
3280     /* There are no wild reads in the spill case.  */
3281     insn_info = bb_info->last_insn;
3282   else
3283     insn_info = find_insn_before_first_wild_read (bb_info);
3284
3285   /* In the spill case or in the no_spill case if there is no wild
3286      read in the block, we will need a kill set.  */
3287   if (insn_info == bb_info->last_insn)
3288     {
3289       if (bb_info->kill)
3290         bitmap_clear (bb_info->kill);
3291       else
3292         bb_info->kill = BITMAP_ALLOC (&dse_bitmap_obstack);
3293     }
3294   else
3295     if (bb_info->kill)
3296       BITMAP_FREE (bb_info->kill);
3297
3298   while (insn_info)
3299     {
3300       /* There may have been code deleted by the dce pass run before
3301          this phase.  */
3302       if (insn_info->insn && INSN_P (insn_info->insn))
3303         {
3304           /* Process the read(s) last.  */
3305           if (for_spills)
3306             {
3307               scan_stores_spill (insn_info->store_rec, bb_info->gen, bb_info->kill);
3308               scan_reads_spill (insn_info->read_rec, bb_info->gen, bb_info->kill);
3309             }
3310           else
3311             {
3312               scan_stores_nospill (insn_info->store_rec, bb_info->gen, bb_info->kill);
3313               scan_reads_nospill (insn_info, bb_info->gen, bb_info->kill);
3314             }
3315         }
3316
3317       insn_info = insn_info->prev_insn;
3318     }
3319 }
3320
3321
3322 /* Set the gen set of the exit block, and also any block with no
3323    successors that does not have a wild read.  */
3324
3325 static void
3326 dse_step3_exit_block_scan (bb_info_t bb_info)
3327 {
3328   /* The gen set is all 0's for the exit block except for the
3329      frame_pointer_group.  */
3330
3331   if (stores_off_frame_dead_at_return)
3332     {
3333       unsigned int i;
3334       group_info_t group;
3335
3336       FOR_EACH_VEC_ELT (rtx_group_vec, i, group)
3337         {
3338           if (group->process_globally && group->frame_related)
3339             bitmap_ior_into (bb_info->gen, group->group_kill);
3340         }
3341     }
3342 }
3343
3344
3345 /* Find all of the blocks that are not backwards reachable from the
3346    exit block or any block with no successors (BB).  These are the
3347    infinite loops or infinite self loops.  These blocks will still
3348    have their bits set in UNREACHABLE_BLOCKS.  */
3349
3350 static void
3351 mark_reachable_blocks (sbitmap unreachable_blocks, basic_block bb)
3352 {
3353   edge e;
3354   edge_iterator ei;
3355
3356   if (bitmap_bit_p (unreachable_blocks, bb->index))
3357     {
3358       bitmap_clear_bit (unreachable_blocks, bb->index);
3359       FOR_EACH_EDGE (e, ei, bb->preds)
3360         {
3361           mark_reachable_blocks (unreachable_blocks, e->src);
3362         }
3363     }
3364 }
3365
3366 /* Build the transfer functions for the function.  */
3367
3368 static void
3369 dse_step3 (bool for_spills)
3370 {
3371   basic_block bb;
3372   sbitmap unreachable_blocks = sbitmap_alloc (last_basic_block);
3373   sbitmap_iterator sbi;
3374   bitmap all_ones = NULL;
3375   unsigned int i;
3376
3377   bitmap_ones (unreachable_blocks);
3378
3379   FOR_ALL_BB (bb)
3380     {
3381       bb_info_t bb_info = bb_table[bb->index];
3382       if (bb_info->gen)
3383         bitmap_clear (bb_info->gen);
3384       else
3385         bb_info->gen = BITMAP_ALLOC (&dse_bitmap_obstack);
3386
3387       if (bb->index == ENTRY_BLOCK)
3388         ;
3389       else if (bb->index == EXIT_BLOCK)
3390         dse_step3_exit_block_scan (bb_info);
3391       else
3392         dse_step3_scan (for_spills, bb);
3393       if (EDGE_COUNT (bb->succs) == 0)
3394         mark_reachable_blocks (unreachable_blocks, bb);
3395
3396       /* If this is the second time dataflow is run, delete the old
3397          sets.  */
3398       if (bb_info->in)
3399         BITMAP_FREE (bb_info->in);
3400       if (bb_info->out)
3401         BITMAP_FREE (bb_info->out);
3402     }
3403
3404   /* For any block in an infinite loop, we must initialize the out set
3405      to all ones.  This could be expensive, but almost never occurs in
3406      practice. However, it is common in regression tests.  */
3407   EXECUTE_IF_SET_IN_BITMAP (unreachable_blocks, 0, i, sbi)
3408     {
3409       if (bitmap_bit_p (all_blocks, i))
3410         {
3411           bb_info_t bb_info = bb_table[i];
3412           if (!all_ones)
3413             {
3414               unsigned int j;
3415               group_info_t group;
3416
3417               all_ones = BITMAP_ALLOC (&dse_bitmap_obstack);
3418               FOR_EACH_VEC_ELT (rtx_group_vec, j, group)
3419                 bitmap_ior_into (all_ones, group->group_kill);
3420             }
3421           if (!bb_info->out)
3422             {
3423               bb_info->out = BITMAP_ALLOC (&dse_bitmap_obstack);
3424               bitmap_copy (bb_info->out, all_ones);
3425             }
3426         }
3427     }
3428
3429   if (all_ones)
3430     BITMAP_FREE (all_ones);
3431   sbitmap_free (unreachable_blocks);
3432 }
3433
3434
3435 \f
3436 /*----------------------------------------------------------------------------
3437    Fourth step.
3438
3439    Solve the bitvector equations.
3440 ----------------------------------------------------------------------------*/
3441
3442
3443 /* Confluence function for blocks with no successors.  Create an out
3444    set from the gen set of the exit block.  This block logically has
3445    the exit block as a successor.  */
3446
3447
3448
3449 static void
3450 dse_confluence_0 (basic_block bb)
3451 {
3452   bb_info_t bb_info = bb_table[bb->index];
3453
3454   if (bb->index == EXIT_BLOCK)
3455     return;
3456
3457   if (!bb_info->out)
3458     {
3459       bb_info->out = BITMAP_ALLOC (&dse_bitmap_obstack);
3460       bitmap_copy (bb_info->out, bb_table[EXIT_BLOCK]->gen);
3461     }
3462 }
3463
3464 /* Propagate the information from the in set of the dest of E to the
3465    out set of the src of E.  If the various in or out sets are not
3466    there, that means they are all ones.  */
3467
3468 static bool
3469 dse_confluence_n (edge e)
3470 {
3471   bb_info_t src_info = bb_table[e->src->index];
3472   bb_info_t dest_info = bb_table[e->dest->index];
3473
3474   if (dest_info->in)
3475     {
3476       if (src_info->out)
3477         bitmap_and_into (src_info->out, dest_info->in);
3478       else
3479         {
3480           src_info->out = BITMAP_ALLOC (&dse_bitmap_obstack);
3481           bitmap_copy (src_info->out, dest_info->in);
3482         }
3483     }
3484   return true;
3485 }
3486
3487
3488 /* Propagate the info from the out to the in set of BB_INDEX's basic
3489    block.  There are three cases:
3490
3491    1) The block has no kill set.  In this case the kill set is all
3492    ones.  It does not matter what the out set of the block is, none of
3493    the info can reach the top.  The only thing that reaches the top is
3494    the gen set and we just copy the set.
3495
3496    2) There is a kill set but no out set and bb has successors.  In
3497    this case we just return. Eventually an out set will be created and
3498    it is better to wait than to create a set of ones.
3499
3500    3) There is both a kill and out set.  We apply the obvious transfer
3501    function.
3502 */
3503
3504 static bool
3505 dse_transfer_function (int bb_index)
3506 {
3507   bb_info_t bb_info = bb_table[bb_index];
3508
3509   if (bb_info->kill)
3510     {
3511       if (bb_info->out)
3512         {
3513           /* Case 3 above.  */
3514           if (bb_info->in)
3515             return bitmap_ior_and_compl (bb_info->in, bb_info->gen,
3516                                          bb_info->out, bb_info->kill);
3517           else
3518             {
3519               bb_info->in = BITMAP_ALLOC (&dse_bitmap_obstack);
3520               bitmap_ior_and_compl (bb_info->in, bb_info->gen,
3521                                     bb_info->out, bb_info->kill);
3522               return true;
3523             }
3524         }
3525       else
3526         /* Case 2 above.  */
3527         return false;
3528     }
3529   else
3530     {
3531       /* Case 1 above.  If there is already an in set, nothing
3532          happens.  */
3533       if (bb_info->in)
3534         return false;
3535       else
3536         {
3537           bb_info->in = BITMAP_ALLOC (&dse_bitmap_obstack);
3538           bitmap_copy (bb_info->in, bb_info->gen);
3539           return true;
3540         }
3541     }
3542 }
3543
3544 /* Solve the dataflow equations.  */
3545
3546 static void
3547 dse_step4 (void)
3548 {
3549   df_simple_dataflow (DF_BACKWARD, NULL, dse_confluence_0,
3550                       dse_confluence_n, dse_transfer_function,
3551                       all_blocks, df_get_postorder (DF_BACKWARD),
3552                       df_get_n_blocks (DF_BACKWARD));
3553   if (dump_file && (dump_flags & TDF_DETAILS))
3554     {
3555       basic_block bb;
3556
3557       fprintf (dump_file, "\n\n*** Global dataflow info after analysis.\n");
3558       FOR_ALL_BB (bb)
3559         {
3560           bb_info_t bb_info = bb_table[bb->index];
3561
3562           df_print_bb_index (bb, dump_file);
3563           if (bb_info->in)
3564             bitmap_print (dump_file, bb_info->in, "  in:   ", "\n");
3565           else
3566             fprintf (dump_file, "  in:   *MISSING*\n");
3567           if (bb_info->gen)
3568             bitmap_print (dump_file, bb_info->gen, "  gen:  ", "\n");
3569           else
3570             fprintf (dump_file, "  gen:  *MISSING*\n");
3571           if (bb_info->kill)
3572             bitmap_print (dump_file, bb_info->kill, "  kill: ", "\n");
3573           else
3574             fprintf (dump_file, "  kill: *MISSING*\n");
3575           if (bb_info->out)
3576             bitmap_print (dump_file, bb_info->out, "  out:  ", "\n");
3577           else
3578             fprintf (dump_file, "  out:  *MISSING*\n\n");
3579         }
3580     }
3581 }
3582
3583
3584 \f
3585 /*----------------------------------------------------------------------------
3586    Fifth step.
3587
3588    Delete the stores that can only be deleted using the global information.
3589 ----------------------------------------------------------------------------*/
3590
3591
3592 static void
3593 dse_step5_nospill (void)
3594 {
3595   basic_block bb;
3596   FOR_EACH_BB (bb)
3597     {
3598       bb_info_t bb_info = bb_table[bb->index];
3599       insn_info_t insn_info = bb_info->last_insn;
3600       bitmap v = bb_info->out;
3601
3602       while (insn_info)
3603         {
3604           bool deleted = false;
3605           if (dump_file && insn_info->insn)
3606             {
3607               fprintf (dump_file, "starting to process insn %d\n",
3608                        INSN_UID (insn_info->insn));
3609               bitmap_print (dump_file, v, "  v:  ", "\n");
3610             }
3611
3612           /* There may have been code deleted by the dce pass run before
3613              this phase.  */
3614           if (insn_info->insn
3615               && INSN_P (insn_info->insn)
3616               && (!insn_info->cannot_delete)
3617               && (!bitmap_empty_p (v)))
3618             {
3619               store_info_t store_info = insn_info->store_rec;
3620
3621               /* Try to delete the current insn.  */
3622               deleted = true;
3623
3624               /* Skip the clobbers.  */
3625               while (!store_info->is_set)
3626                 store_info = store_info->next;
3627
3628               if (store_info->alias_set)
3629                 deleted = false;
3630               else
3631                 {
3632                   HOST_WIDE_INT i;
3633                   group_info_t group_info
3634                     = rtx_group_vec[store_info->group_id];
3635
3636                   for (i = store_info->begin; i < store_info->end; i++)
3637                     {
3638                       int index = get_bitmap_index (group_info, i);
3639
3640                       if (dump_file && (dump_flags & TDF_DETAILS))
3641                         fprintf (dump_file, "i = %d, index = %d\n", (int)i, index);
3642                       if (index == 0 || !bitmap_bit_p (v, index))
3643                         {
3644                           if (dump_file && (dump_flags & TDF_DETAILS))
3645                             fprintf (dump_file, "failing at i = %d\n", (int)i);
3646                           deleted = false;
3647                           break;
3648                         }
3649                     }
3650                 }
3651               if (deleted)
3652                 {
3653                   if (dbg_cnt (dse)
3654                       && check_for_inc_dec_1 (insn_info))
3655                     {
3656                       delete_insn (insn_info->insn);
3657                       insn_info->insn = NULL;
3658                       globally_deleted++;
3659                     }
3660                 }
3661             }
3662           /* We do want to process the local info if the insn was
3663              deleted.  For instance, if the insn did a wild read, we
3664              no longer need to trash the info.  */
3665           if (insn_info->insn
3666               && INSN_P (insn_info->insn)
3667               && (!deleted))
3668             {
3669               scan_stores_nospill (insn_info->store_rec, v, NULL);
3670               if (insn_info->wild_read)
3671                 {
3672                   if (dump_file && (dump_flags & TDF_DETAILS))
3673                     fprintf (dump_file, "wild read\n");
3674                   bitmap_clear (v);
3675                 }
3676               else if (insn_info->read_rec
3677                        || insn_info->non_frame_wild_read)
3678                 {
3679                   if (dump_file && !insn_info->non_frame_wild_read)
3680                     fprintf (dump_file, "regular read\n");
3681                   else if (dump_file && (dump_flags & TDF_DETAILS))
3682                     fprintf (dump_file, "non-frame wild read\n");
3683                   scan_reads_nospill (insn_info, v, NULL);
3684                 }
3685             }
3686
3687           insn_info = insn_info->prev_insn;
3688         }
3689     }
3690 }
3691
3692
3693 static void
3694 dse_step5_spill (void)
3695 {
3696   basic_block bb;
3697   FOR_EACH_BB (bb)
3698     {
3699       bb_info_t bb_info = bb_table[bb->index];
3700       insn_info_t insn_info = bb_info->last_insn;
3701       bitmap v = bb_info->out;
3702
3703       while (insn_info)
3704         {
3705           bool deleted = false;
3706           /* There may have been code deleted by the dce pass run before
3707              this phase.  */
3708           if (insn_info->insn
3709               && INSN_P (insn_info->insn)
3710               && (!insn_info->cannot_delete)
3711               && (!bitmap_empty_p (v)))
3712             {
3713               /* Try to delete the current insn.  */
3714               store_info_t store_info = insn_info->store_rec;
3715               deleted = true;
3716
3717               while (store_info)
3718                 {
3719                   if (store_info->alias_set)
3720                     {
3721                       int index = get_bitmap_index (clear_alias_group,
3722                                                     store_info->alias_set);
3723                       if (index == 0 || !bitmap_bit_p (v, index))
3724                         {
3725                           deleted = false;
3726                           break;
3727                         }
3728                     }
3729                   else
3730                     deleted = false;
3731                   store_info = store_info->next;
3732                 }
3733               if (deleted && dbg_cnt (dse)
3734                   && check_for_inc_dec_1 (insn_info))
3735                 {
3736                   if (dump_file && (dump_flags & TDF_DETAILS))
3737                     fprintf (dump_file, "Spill deleting insn %d\n",
3738                              INSN_UID (insn_info->insn));
3739                   delete_insn (insn_info->insn);
3740                   spill_deleted++;
3741                   insn_info->insn = NULL;
3742                 }
3743             }
3744
3745           if (insn_info->insn
3746               && INSN_P (insn_info->insn)
3747               && (!deleted))
3748             {
3749               scan_stores_spill (insn_info->store_rec, v, NULL);
3750               scan_reads_spill (insn_info->read_rec, v, NULL);
3751             }
3752
3753           insn_info = insn_info->prev_insn;
3754         }
3755     }
3756 }
3757
3758
3759 \f
3760 /*----------------------------------------------------------------------------
3761    Sixth step.
3762
3763    Delete stores made redundant by earlier stores (which store the same
3764    value) that couldn't be eliminated.
3765 ----------------------------------------------------------------------------*/
3766
3767 static void
3768 dse_step6 (void)
3769 {
3770   basic_block bb;
3771
3772   FOR_ALL_BB (bb)
3773     {
3774       bb_info_t bb_info = bb_table[bb->index];
3775       insn_info_t insn_info = bb_info->last_insn;
3776
3777       while (insn_info)
3778         {
3779           /* There may have been code deleted by the dce pass run before
3780              this phase.  */
3781           if (insn_info->insn
3782               && INSN_P (insn_info->insn)
3783               && !insn_info->cannot_delete)
3784             {
3785               store_info_t s_info = insn_info->store_rec;
3786
3787               while (s_info && !s_info->is_set)
3788                 s_info = s_info->next;
3789               if (s_info
3790                   && s_info->redundant_reason
3791                   && s_info->redundant_reason->insn
3792                   && INSN_P (s_info->redundant_reason->insn))
3793                 {
3794                   rtx rinsn = s_info->redundant_reason->insn;
3795                   if (dump_file && (dump_flags & TDF_DETAILS))
3796                     fprintf (dump_file, "Locally deleting insn %d "
3797                                         "because insn %d stores the "
3798                                         "same value and couldn't be "
3799                                         "eliminated\n",
3800                                         INSN_UID (insn_info->insn),
3801                                         INSN_UID (rinsn));
3802                   delete_dead_store_insn (insn_info);
3803                 }
3804             }
3805           insn_info = insn_info->prev_insn;
3806         }
3807     }
3808 }
3809 \f
3810 /*----------------------------------------------------------------------------
3811    Seventh step.
3812
3813    Destroy everything left standing.
3814 ----------------------------------------------------------------------------*/
3815
3816 static void
3817 dse_step7 (void)
3818 {
3819   bitmap_obstack_release (&dse_bitmap_obstack);
3820   obstack_free (&dse_obstack, NULL);
3821
3822   if (clear_alias_sets)
3823     {
3824       BITMAP_FREE (clear_alias_sets);
3825       BITMAP_FREE (disqualified_clear_alias_sets);
3826       free_alloc_pool (clear_alias_mode_pool);
3827       htab_delete (clear_alias_mode_table);
3828     }
3829
3830   end_alias_analysis ();
3831   free (bb_table);
3832   rtx_group_table.dispose ();
3833   rtx_group_vec.release ();
3834   BITMAP_FREE (all_blocks);
3835   BITMAP_FREE (scratch);
3836
3837   free_alloc_pool (rtx_store_info_pool);
3838   free_alloc_pool (read_info_pool);
3839   free_alloc_pool (insn_info_pool);
3840   free_alloc_pool (bb_info_pool);
3841   free_alloc_pool (rtx_group_info_pool);
3842   free_alloc_pool (deferred_change_pool);
3843 }
3844
3845
3846 /* -------------------------------------------------------------------------
3847    DSE
3848    ------------------------------------------------------------------------- */
3849
3850 /* Callback for running pass_rtl_dse.  */
3851
3852 static unsigned int
3853 rest_of_handle_dse (void)
3854 {
3855   bool did_global = false;
3856
3857   df_set_flags (DF_DEFER_INSN_RESCAN);
3858
3859   /* Need the notes since we must track live hardregs in the forwards
3860      direction.  */
3861   df_note_add_problem ();
3862   df_analyze ();
3863
3864   dse_step0 ();
3865   dse_step1 ();
3866   dse_step2_init ();
3867   if (dse_step2_nospill ())
3868     {
3869       df_set_flags (DF_LR_RUN_DCE);
3870       df_analyze ();
3871       did_global = true;
3872       if (dump_file && (dump_flags & TDF_DETAILS))
3873         fprintf (dump_file, "doing global processing\n");
3874       dse_step3 (false);
3875       dse_step4 ();
3876       dse_step5_nospill ();
3877     }
3878
3879   /* For the instance of dse that runs after reload, we make a special
3880      pass to process the spills.  These are special in that they are
3881      totally transparent, i.e, there is no aliasing issues that need
3882      to be considered.  This means that the wild reads that kill
3883      everything else do not apply here.  */
3884   if (clear_alias_sets && dse_step2_spill ())
3885     {
3886       if (!did_global)
3887         {
3888           df_set_flags (DF_LR_RUN_DCE);
3889           df_analyze ();
3890         }
3891       did_global = true;
3892       if (dump_file && (dump_flags & TDF_DETAILS))
3893         fprintf (dump_file, "doing global spill processing\n");
3894       dse_step3 (true);
3895       dse_step4 ();
3896       dse_step5_spill ();
3897     }
3898
3899   dse_step6 ();
3900   dse_step7 ();
3901
3902   if (dump_file)
3903     fprintf (dump_file, "dse: local deletions = %d, global deletions = %d, spill deletions = %d\n",
3904              locally_deleted, globally_deleted, spill_deleted);
3905   return 0;
3906 }
3907
3908 static bool
3909 gate_dse1 (void)
3910 {
3911   return optimize > 0 && flag_dse
3912     && dbg_cnt (dse1);
3913 }
3914
3915 static bool
3916 gate_dse2 (void)
3917 {
3918   return optimize > 0 && flag_dse
3919     && dbg_cnt (dse2);
3920 }
3921
3922 struct rtl_opt_pass pass_rtl_dse1 =
3923 {
3924  {
3925   RTL_PASS,
3926   "dse1",                               /* name */
3927   OPTGROUP_NONE,                        /* optinfo_flags */
3928   gate_dse1,                            /* gate */
3929   rest_of_handle_dse,                   /* execute */
3930   NULL,                                 /* sub */
3931   NULL,                                 /* next */
3932   0,                                    /* static_pass_number */
3933   TV_DSE1,                              /* tv_id */
3934   0,                                    /* properties_required */
3935   0,                                    /* properties_provided */
3936   0,                                    /* properties_destroyed */
3937   0,                                    /* todo_flags_start */
3938   TODO_df_finish | TODO_verify_rtl_sharing |
3939   TODO_ggc_collect                      /* todo_flags_finish */
3940  }
3941 };
3942
3943 struct rtl_opt_pass pass_rtl_dse2 =
3944 {
3945  {
3946   RTL_PASS,
3947   "dse2",                               /* name */
3948   OPTGROUP_NONE,                        /* optinfo_flags */
3949   gate_dse2,                            /* gate */
3950   rest_of_handle_dse,                   /* execute */
3951   NULL,                                 /* sub */
3952   NULL,                                 /* next */
3953   0,                                    /* static_pass_number */
3954   TV_DSE2,                              /* tv_id */
3955   0,                                    /* properties_required */
3956   0,                                    /* properties_provided */
3957   0,                                    /* properties_destroyed */
3958   0,                                    /* todo_flags_start */
3959   TODO_df_finish | TODO_verify_rtl_sharing |
3960   TODO_ggc_collect                      /* todo_flags_finish */
3961  }
3962 };