OSDN Git Service

2005-07-05 Paolo Bonzini <bonzini@gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Perform various loop optimizations, including strength reduction.
2    Copyright (C) 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995,
3    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
4    Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.  */
22
23 /* This is the loop optimization pass of the compiler.
24    It finds invariant computations within loops and moves them
25    to the beginning of the loop.  Then it identifies basic and
26    general induction variables.
27
28    Basic induction variables (BIVs) are a pseudo registers which are set within
29    a loop only by incrementing or decrementing its value.  General induction
30    variables (GIVs) are pseudo registers with a value which is a linear function
31    of a basic induction variable.  BIVs are recognized by `basic_induction_var';
32    GIVs by `general_induction_var'.
33
34    Once induction variables are identified, strength reduction is applied to the
35    general induction variables, and induction variable elimination is applied to
36    the basic induction variables.
37
38    It also finds cases where
39    a register is set within the loop by zero-extending a narrower value
40    and changes these to zero the entire register once before the loop
41    and merely copy the low part within the loop.
42
43    Most of the complexity is in heuristics to decide when it is worth
44    while to do these things.  */
45
46 #include "config.h"
47 #include "system.h"
48 #include "coretypes.h"
49 #include "tm.h"
50 #include "rtl.h"
51 #include "tm_p.h"
52 #include "function.h"
53 #include "expr.h"
54 #include "hard-reg-set.h"
55 #include "basic-block.h"
56 #include "insn-config.h"
57 #include "regs.h"
58 #include "recog.h"
59 #include "flags.h"
60 #include "real.h"
61 #include "cselib.h"
62 #include "except.h"
63 #include "toplev.h"
64 #include "predict.h"
65 #include "insn-flags.h"
66 #include "optabs.h"
67 #include "cfgloop.h"
68 #include "ggc.h"
69 #include "timevar.h"
70 #include "tree-pass.h"
71
72 /* Get the loop info pointer of a loop.  */
73 #define LOOP_INFO(LOOP) ((struct loop_info *) (LOOP)->aux)
74
75 /* Get a pointer to the loop movables structure.  */
76 #define LOOP_MOVABLES(LOOP) (&LOOP_INFO (LOOP)->movables)
77
78 /* Get a pointer to the loop registers structure.  */
79 #define LOOP_REGS(LOOP) (&LOOP_INFO (LOOP)->regs)
80
81 /* Get a pointer to the loop induction variables structure.  */
82 #define LOOP_IVS(LOOP) (&LOOP_INFO (LOOP)->ivs)
83
84 /* Get the luid of an insn.  Catch the error of trying to reference the LUID
85    of an insn added during loop, since these don't have LUIDs.  */
86
87 #define INSN_LUID(INSN)                 \
88   (gcc_assert (INSN_UID (INSN) < max_uid_for_loop), uid_luid[INSN_UID (INSN)])
89
90 #define REGNO_FIRST_LUID(REGNO)                 \
91   (REGNO_FIRST_UID (REGNO) < max_uid_for_loop   \
92         ? uid_luid[REGNO_FIRST_UID (REGNO)]     \
93         : 0)
94 #define REGNO_LAST_LUID(REGNO)                  \
95   (REGNO_LAST_UID (REGNO) < max_uid_for_loop    \
96         ? uid_luid[REGNO_LAST_UID (REGNO)]      \
97         : INT_MAX)
98
99 /* A "basic induction variable" or biv is a pseudo reg that is set
100    (within this loop) only by incrementing or decrementing it.  */
101 /* A "general induction variable" or giv is a pseudo reg whose
102    value is a linear function of a biv.  */
103
104 /* Bivs are recognized by `basic_induction_var';
105    Givs by `general_induction_var'.  */
106
107 /* An enum for the two different types of givs, those that are used
108    as memory addresses and those that are calculated into registers.  */
109 enum g_types
110 {
111   DEST_ADDR,
112   DEST_REG
113 };
114
115
116 /* A `struct induction' is created for every instruction that sets
117    an induction variable (either a biv or a giv).  */
118
119 struct induction
120 {
121   rtx insn;                     /* The insn that sets a biv or giv */
122   rtx new_reg;                  /* New register, containing strength reduced
123                                    version of this giv.  */
124   rtx src_reg;                  /* Biv from which this giv is computed.
125                                    (If this is a biv, then this is the biv.) */
126   enum g_types giv_type;        /* Indicate whether DEST_ADDR or DEST_REG */
127   rtx dest_reg;                 /* Destination register for insn: this is the
128                                    register which was the biv or giv.
129                                    For a biv, this equals src_reg.
130                                    For a DEST_ADDR type giv, this is 0.  */
131   rtx *location;                /* Place in the insn where this giv occurs.
132                                    If GIV_TYPE is DEST_REG, this is 0.  */
133                                 /* For a biv, this is the place where add_val
134                                    was found.  */
135   enum machine_mode mode;       /* The mode of this biv or giv */
136   rtx mem;                      /* For DEST_ADDR, the memory object.  */
137   rtx mult_val;                 /* Multiplicative factor for src_reg.  */
138   rtx add_val;                  /* Additive constant for that product.  */
139   int benefit;                  /* Gain from eliminating this insn.  */
140   rtx final_value;              /* If the giv is used outside the loop, and its
141                                    final value could be calculated, it is put
142                                    here, and the giv is made replaceable.  Set
143                                    the giv to this value before the loop.  */
144   unsigned combined_with;       /* The number of givs this giv has been
145                                    combined with.  If nonzero, this giv
146                                    cannot combine with any other giv.  */
147   unsigned replaceable : 1;     /* 1 if we can substitute the strength-reduced
148                                    variable for the original variable.
149                                    0 means they must be kept separate and the
150                                    new one must be copied into the old pseudo
151                                    reg each time the old one is set.  */
152   unsigned not_replaceable : 1; /* Used to prevent duplicating work.  This is
153                                    1 if we know that the giv definitely can
154                                    not be made replaceable, in which case we
155                                    don't bother checking the variable again
156                                    even if further info is available.
157                                    Both this and the above can be zero.  */
158   unsigned ignore : 1;          /* 1 prohibits further processing of giv */
159   unsigned always_computable : 1;/* 1 if this value is computable every
160                                     iteration.  */
161   unsigned always_executed : 1; /* 1 if this set occurs each iteration.  */
162   unsigned maybe_multiple : 1;  /* Only used for a biv and  1 if this biv
163                                    update may be done multiple times per
164                                    iteration.  */
165   unsigned cant_derive : 1;     /* For giv's, 1 if this giv cannot derive
166                                    another giv.  This occurs in many cases
167                                    where a giv's lifetime spans an update to
168                                    a biv.  */
169   unsigned maybe_dead : 1;      /* 1 if this giv might be dead.  In that case,
170                                    we won't use it to eliminate a biv, it
171                                    would probably lose.  */
172   unsigned auto_inc_opt : 1;    /* 1 if this giv had its increment output next
173                                    to it to try to form an auto-inc address.  */
174   unsigned shared : 1;
175   unsigned no_const_addval : 1; /* 1 if add_val does not contain a const.  */
176   int lifetime;                 /* Length of life of this giv */
177   rtx derive_adjustment;        /* If nonzero, is an adjustment to be
178                                    subtracted from add_val when this giv
179                                    derives another.  This occurs when the
180                                    giv spans a biv update by incrementation.  */
181   rtx ext_dependent;            /* If nonzero, is a sign or zero extension
182                                    if a biv on which this giv is dependent.  */
183   struct induction *next_iv;    /* For givs, links together all givs that are
184                                    based on the same biv.  For bivs, links
185                                    together all biv entries that refer to the
186                                    same biv register.  */
187   struct induction *same;       /* For givs, if the giv has been combined with
188                                    another giv, this points to the base giv.
189                                    The base giv will have COMBINED_WITH nonzero.
190                                    For bivs, if the biv has the same LOCATION
191                                    than another biv, this points to the base
192                                    biv.  */
193   struct induction *same_insn;  /* If there are multiple identical givs in
194                                    the same insn, then all but one have this
195                                    field set, and they all point to the giv
196                                    that doesn't have this field set.  */
197   rtx last_use;                 /* For a giv made from a biv increment, this is
198                                    a substitute for the lifetime information.  */
199 };
200
201
202 /* A `struct iv_class' is created for each biv.  */
203
204 struct iv_class
205 {
206   unsigned int regno;           /* Pseudo reg which is the biv.  */
207   int biv_count;                /* Number of insns setting this reg.  */
208   struct induction *biv;        /* List of all insns that set this reg.  */
209   int giv_count;                /* Number of DEST_REG givs computed from this
210                                    biv.  The resulting count is only used in
211                                    check_dbra_loop.  */
212   struct induction *giv;        /* List of all insns that compute a giv
213                                    from this reg.  */
214   int total_benefit;            /* Sum of BENEFITs of all those givs.  */
215   rtx initial_value;            /* Value of reg at loop start.  */
216   rtx initial_test;             /* Test performed on BIV before loop.  */
217   rtx final_value;              /* Value of reg at loop end, if known.  */
218   struct iv_class *next;        /* Links all class structures together.  */
219   rtx init_insn;                /* insn which initializes biv, 0 if none.  */
220   rtx init_set;                 /* SET of INIT_INSN, if any.  */
221   unsigned incremented : 1;     /* 1 if somewhere incremented/decremented */
222   unsigned eliminable : 1;      /* 1 if plausible candidate for
223                                    elimination.  */
224   unsigned nonneg : 1;          /* 1 if we added a REG_NONNEG note for
225                                    this.  */
226   unsigned reversed : 1;        /* 1 if we reversed the loop that this
227                                    biv controls.  */
228   unsigned all_reduced : 1;     /* 1 if all givs using this biv have
229                                    been reduced.  */
230 };
231
232
233 /* Definitions used by the basic induction variable discovery code.  */
234 enum iv_mode
235 {
236   UNKNOWN_INDUCT,
237   BASIC_INDUCT,
238   NOT_BASIC_INDUCT,
239   GENERAL_INDUCT
240 };
241
242
243 /* A `struct iv' is created for every register.  */
244
245 struct iv
246 {
247   enum iv_mode type;
248   union
249   {
250     struct iv_class *class;
251     struct induction *info;
252   } iv;
253 };
254
255
256 #define REG_IV_TYPE(ivs, n) ivs->regs[n].type
257 #define REG_IV_INFO(ivs, n) ivs->regs[n].iv.info
258 #define REG_IV_CLASS(ivs, n) ivs->regs[n].iv.class
259
260
261 struct loop_ivs
262 {
263   /* Indexed by register number, contains pointer to `struct
264      iv' if register is an induction variable.  */
265   struct iv *regs;
266
267   /* Size of regs array.  */
268   unsigned int n_regs;
269
270   /* The head of a list which links together (via the next field)
271      every iv class for the current loop.  */
272   struct iv_class *list;
273 };
274
275
276 typedef struct loop_mem_info
277 {
278   rtx mem;      /* The MEM itself.  */
279   rtx reg;      /* Corresponding pseudo, if any.  */
280   int optimize; /* Nonzero if we can optimize access to this MEM.  */
281 } loop_mem_info;
282
283
284
285 struct loop_reg
286 {
287   /* Number of times the reg is set during the loop being scanned.
288      During code motion, a negative value indicates a reg that has
289      been made a candidate; in particular -2 means that it is an
290      candidate that we know is equal to a constant and -1 means that
291      it is a candidate not known equal to a constant.  After code
292      motion, regs moved have 0 (which is accurate now) while the
293      failed candidates have the original number of times set.
294
295      Therefore, at all times, == 0 indicates an invariant register;
296      < 0 a conditionally invariant one.  */
297   int set_in_loop;
298
299   /* Original value of set_in_loop; same except that this value
300      is not set negative for a reg whose sets have been made candidates
301      and not set to 0 for a reg that is moved.  */
302   int n_times_set;
303
304   /* Contains the insn in which a register was used if it was used
305      exactly once; contains const0_rtx if it was used more than once.  */
306   rtx single_usage;
307
308   /* Nonzero indicates that the register cannot be moved or strength
309      reduced.  */
310   char may_not_optimize;
311
312   /* Nonzero means reg N has already been moved out of one loop.
313      This reduces the desire to move it out of another.  */
314   char moved_once;
315 };
316
317
318 struct loop_regs
319 {
320   int num;                      /* Number of regs used in table.  */
321   int size;                     /* Size of table.  */
322   struct loop_reg *array;       /* Register usage info. array.  */
323   int multiple_uses;            /* Nonzero if a reg has multiple uses.  */
324 };
325
326
327
328 struct loop_movables
329 {
330   /* Head of movable chain.  */
331   struct movable *head;
332   /* Last movable in chain.  */
333   struct movable *last;
334 };
335
336
337 /* Information pertaining to a loop.  */
338
339 struct loop_info
340 {
341   /* Nonzero if there is a subroutine call in the current loop.  */
342   int has_call;
343   /* Nonzero if there is a libcall in the current loop.  */
344   int has_libcall;
345   /* Nonzero if there is a non constant call in the current loop.  */
346   int has_nonconst_call;
347   /* Nonzero if there is a prefetch instruction in the current loop.  */
348   int has_prefetch;
349   /* Nonzero if there is a volatile memory reference in the current
350      loop.  */
351   int has_volatile;
352   /* Nonzero if there is a tablejump in the current loop.  */
353   int has_tablejump;
354   /* Nonzero if there are ways to leave the loop other than falling
355      off the end.  */
356   int has_multiple_exit_targets;
357   /* Nonzero if there is an indirect jump in the current function.  */
358   int has_indirect_jump;
359   /* Register or constant initial loop value.  */
360   rtx initial_value;
361   /* Register or constant value used for comparison test.  */
362   rtx comparison_value;
363   /* Register or constant approximate final value.  */
364   rtx final_value;
365   /* Register or constant initial loop value with term common to
366      final_value removed.  */
367   rtx initial_equiv_value;
368   /* Register or constant final loop value with term common to
369      initial_value removed.  */
370   rtx final_equiv_value;
371   /* Register corresponding to iteration variable.  */
372   rtx iteration_var;
373   /* Constant loop increment.  */
374   rtx increment;
375   enum rtx_code comparison_code;
376   /* Holds the number of loop iterations.  It is zero if the number
377      could not be calculated.  Must be unsigned since the number of
378      iterations can be as high as 2^wordsize - 1.  For loops with a
379      wider iterator, this number will be zero if the number of loop
380      iterations is too large for an unsigned integer to hold.  */
381   unsigned HOST_WIDE_INT n_iterations;
382   int used_count_register;
383   /* The loop iterator induction variable.  */
384   struct iv_class *iv;
385   /* List of MEMs that are stored in this loop.  */
386   rtx store_mems;
387   /* Array of MEMs that are used (read or written) in this loop, but
388      cannot be aliased by anything in this loop, except perhaps
389      themselves.  In other words, if mems[i] is altered during
390      the loop, it is altered by an expression that is rtx_equal_p to
391      it.  */
392   loop_mem_info *mems;
393   /* The index of the next available slot in MEMS.  */
394   int mems_idx;
395   /* The number of elements allocated in MEMS.  */
396   int mems_allocated;
397   /* Nonzero if we don't know what MEMs were changed in the current
398      loop.  This happens if the loop contains a call (in which case
399      `has_call' will also be set) or if we store into more than
400      NUM_STORES MEMs.  */
401   int unknown_address_altered;
402   /* The above doesn't count any readonly memory locations that are
403      stored.  This does.  */
404   int unknown_constant_address_altered;
405   /* Count of memory write instructions discovered in the loop.  */
406   int num_mem_sets;
407   /* The insn where the first of these was found.  */
408   rtx first_loop_store_insn;
409   /* The chain of movable insns in loop.  */
410   struct loop_movables movables;
411   /* The registers used the in loop.  */
412   struct loop_regs regs;
413   /* The induction variable information in loop.  */
414   struct loop_ivs ivs;
415   /* Nonzero if call is in pre_header extended basic block.  */
416   int pre_header_has_call;
417 };
418
419 /* Not really meaningful values, but at least something.  */
420 #ifndef SIMULTANEOUS_PREFETCHES
421 #define SIMULTANEOUS_PREFETCHES 3
422 #endif
423 #ifndef PREFETCH_BLOCK
424 #define PREFETCH_BLOCK 32
425 #endif
426 #ifndef HAVE_prefetch
427 #define HAVE_prefetch 0
428 #define CODE_FOR_prefetch 0
429 #define gen_prefetch(a,b,c) (gcc_unreachable (), NULL_RTX)
430 #endif
431
432 /* Give up the prefetch optimizations once we exceed a given threshold.
433    It is unlikely that we would be able to optimize something in a loop
434    with so many detected prefetches.  */
435 #define MAX_PREFETCHES 100
436 /* The number of prefetch blocks that are beneficial to fetch at once before
437    a loop with a known (and low) iteration count.  */
438 #define PREFETCH_BLOCKS_BEFORE_LOOP_MAX  6
439 /* For very tiny loops it is not worthwhile to prefetch even before the loop,
440    since it is likely that the data are already in the cache.  */
441 #define PREFETCH_BLOCKS_BEFORE_LOOP_MIN  2
442
443 /* Parameterize some prefetch heuristics so they can be turned on and off
444    easily for performance testing on new architectures.  These can be
445    defined in target-dependent files.  */
446
447 /* Prefetch is worthwhile only when loads/stores are dense.  */
448 #ifndef PREFETCH_ONLY_DENSE_MEM
449 #define PREFETCH_ONLY_DENSE_MEM 1
450 #endif
451
452 /* Define what we mean by "dense" loads and stores; This value divided by 256
453    is the minimum percentage of memory references that worth prefetching.  */
454 #ifndef PREFETCH_DENSE_MEM
455 #define PREFETCH_DENSE_MEM 220
456 #endif
457
458 /* Do not prefetch for a loop whose iteration count is known to be low.  */
459 #ifndef PREFETCH_NO_LOW_LOOPCNT
460 #define PREFETCH_NO_LOW_LOOPCNT 1
461 #endif
462
463 /* Define what we mean by a "low" iteration count.  */
464 #ifndef PREFETCH_LOW_LOOPCNT
465 #define PREFETCH_LOW_LOOPCNT 32
466 #endif
467
468 /* Do not prefetch for a loop that contains a function call; such a loop is
469    probably not an internal loop.  */
470 #ifndef PREFETCH_NO_CALL
471 #define PREFETCH_NO_CALL 1
472 #endif
473
474 /* Do not prefetch accesses with an extreme stride.  */
475 #ifndef PREFETCH_NO_EXTREME_STRIDE
476 #define PREFETCH_NO_EXTREME_STRIDE 1
477 #endif
478
479 /* Define what we mean by an "extreme" stride.  */
480 #ifndef PREFETCH_EXTREME_STRIDE
481 #define PREFETCH_EXTREME_STRIDE 4096
482 #endif
483
484 /* Define a limit to how far apart indices can be and still be merged
485    into a single prefetch.  */
486 #ifndef PREFETCH_EXTREME_DIFFERENCE
487 #define PREFETCH_EXTREME_DIFFERENCE 4096
488 #endif
489
490 /* Issue prefetch instructions before the loop to fetch data to be used
491    in the first few loop iterations.  */
492 #ifndef PREFETCH_BEFORE_LOOP
493 #define PREFETCH_BEFORE_LOOP 1
494 #endif
495
496 /* Do not handle reversed order prefetches (negative stride).  */
497 #ifndef PREFETCH_NO_REVERSE_ORDER
498 #define PREFETCH_NO_REVERSE_ORDER 1
499 #endif
500
501 /* Prefetch even if the GIV is in conditional code.  */
502 #ifndef PREFETCH_CONDITIONAL
503 #define PREFETCH_CONDITIONAL 1
504 #endif
505
506 #define LOOP_REG_LIFETIME(LOOP, REGNO) \
507 ((REGNO_LAST_LUID (REGNO) - REGNO_FIRST_LUID (REGNO)))
508
509 #define LOOP_REG_GLOBAL_P(LOOP, REGNO) \
510 ((REGNO_LAST_LUID (REGNO) > INSN_LUID ((LOOP)->end) \
511  || REGNO_FIRST_LUID (REGNO) < INSN_LUID ((LOOP)->start)))
512
513 #define LOOP_REGNO_NREGS(REGNO, SET_DEST) \
514 ((REGNO) < FIRST_PSEUDO_REGISTER \
515  ? (int) hard_regno_nregs[(REGNO)][GET_MODE (SET_DEST)] : 1)
516
517
518 /* Vector mapping INSN_UIDs to luids.
519    The luids are like uids but increase monotonically always.
520    We use them to see whether a jump comes from outside a given loop.  */
521
522 static int *uid_luid;
523
524 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
525    number the insn is contained in.  */
526
527 static struct loop **uid_loop;
528
529 /* 1 + largest uid of any insn.  */
530
531 static int max_uid_for_loop;
532
533 /* Number of loops detected in current function.  Used as index to the
534    next few tables.  */
535
536 static int max_loop_num;
537
538 /* Bound on pseudo register number before loop optimization.
539    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
540 static unsigned int max_reg_before_loop;
541
542 /* The value to pass to the next call of reg_scan_update.  */
543 static int loop_max_reg;
544 \f
545 /* During the analysis of a loop, a chain of `struct movable's
546    is made to record all the movable insns found.
547    Then the entire chain can be scanned to decide which to move.  */
548
549 struct movable
550 {
551   rtx insn;                     /* A movable insn */
552   rtx set_src;                  /* The expression this reg is set from.  */
553   rtx set_dest;                 /* The destination of this SET.  */
554   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
555                                    of any registers used within the LIBCALL.  */
556   int consec;                   /* Number of consecutive following insns
557                                    that must be moved with this one.  */
558   unsigned int regno;           /* The register it sets */
559   short lifetime;               /* lifetime of that register;
560                                    may be adjusted when matching movables
561                                    that load the same value are found.  */
562   short savings;                /* Number of insns we can move for this reg,
563                                    including other movables that force this
564                                    or match this one.  */
565   ENUM_BITFIELD(machine_mode) savemode : 8;   /* Nonzero means it is a mode for
566                                    a low part that we should avoid changing when
567                                    clearing the rest of the reg.  */
568   unsigned int cond : 1;        /* 1 if only conditionally movable */
569   unsigned int force : 1;       /* 1 means MUST move this insn */
570   unsigned int global : 1;      /* 1 means reg is live outside this loop */
571                 /* If PARTIAL is 1, GLOBAL means something different:
572                    that the reg is live outside the range from where it is set
573                    to the following label.  */
574   unsigned int done : 1;        /* 1 inhibits further processing of this */
575
576   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
577                                    In particular, moving it does not make it
578                                    invariant.  */
579   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
580                                    load SRC, rather than copying INSN.  */
581   unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
582                                     first insn of a consecutive sets group.  */
583   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN.  */
584   unsigned int insert_temp : 1;  /* 1 means we copy to a new pseudo and replace
585                                     the original insn with a copy from that
586                                     pseudo, rather than deleting it.  */
587   struct movable *match;        /* First entry for same value */
588   struct movable *forces;       /* An insn that must be moved if this is */
589   struct movable *next;
590 };
591
592
593 static FILE *loop_dump_stream;
594
595 /* Forward declarations.  */
596
597 static void invalidate_loops_containing_label (rtx);
598 static void find_and_verify_loops (rtx, struct loops *);
599 static void mark_loop_jump (rtx, struct loop *);
600 static void prescan_loop (struct loop *);
601 static int reg_in_basic_block_p (rtx, rtx);
602 static int consec_sets_invariant_p (const struct loop *, rtx, int, rtx);
603 static int labels_in_range_p (rtx, int);
604 static void count_one_set (struct loop_regs *, rtx, rtx, rtx *);
605 static void note_addr_stored (rtx, rtx, void *);
606 static void note_set_pseudo_multiple_uses (rtx, rtx, void *);
607 static int loop_reg_used_before_p (const struct loop *, rtx, rtx);
608 static rtx find_regs_nested (rtx, rtx);
609 static void scan_loop (struct loop*, int);
610 #if 0
611 static void replace_call_address (rtx, rtx, rtx);
612 #endif
613 static rtx skip_consec_insns (rtx, int);
614 static int libcall_benefit (rtx);
615 static rtx libcall_other_reg (rtx, rtx);
616 static void record_excess_regs (rtx, rtx, rtx *);
617 static void ignore_some_movables (struct loop_movables *);
618 static void force_movables (struct loop_movables *);
619 static void combine_movables (struct loop_movables *, struct loop_regs *);
620 static int num_unmoved_movables (const struct loop *);
621 static int regs_match_p (rtx, rtx, struct loop_movables *);
622 static int rtx_equal_for_loop_p (rtx, rtx, struct loop_movables *,
623                                  struct loop_regs *);
624 static void add_label_notes (rtx, rtx);
625 static void move_movables (struct loop *loop, struct loop_movables *, int,
626                            int);
627 static void loop_movables_add (struct loop_movables *, struct movable *);
628 static void loop_movables_free (struct loop_movables *);
629 static int count_nonfixed_reads (const struct loop *, rtx);
630 static void loop_bivs_find (struct loop *);
631 static void loop_bivs_init_find (struct loop *);
632 static void loop_bivs_check (struct loop *);
633 static void loop_givs_find (struct loop *);
634 static void loop_givs_check (struct loop *);
635 static int loop_biv_eliminable_p (struct loop *, struct iv_class *, int, int);
636 static int loop_giv_reduce_benefit (struct loop *, struct iv_class *,
637                                     struct induction *, rtx);
638 static void loop_givs_dead_check (struct loop *, struct iv_class *);
639 static void loop_givs_reduce (struct loop *, struct iv_class *);
640 static void loop_givs_rescan (struct loop *, struct iv_class *, rtx *);
641 static void loop_ivs_free (struct loop *);
642 static void strength_reduce (struct loop *, int);
643 static void find_single_use_in_loop (struct loop_regs *, rtx, rtx);
644 static int valid_initial_value_p (rtx, rtx, int, rtx);
645 static void find_mem_givs (const struct loop *, rtx, rtx, int, int);
646 static void record_biv (struct loop *, struct induction *, rtx, rtx, rtx,
647                         rtx, rtx *, int, int);
648 static void check_final_value (const struct loop *, struct induction *);
649 static void loop_ivs_dump (const struct loop *, FILE *, int);
650 static void loop_iv_class_dump (const struct iv_class *, FILE *, int);
651 static void loop_biv_dump (const struct induction *, FILE *, int);
652 static void loop_giv_dump (const struct induction *, FILE *, int);
653 static void record_giv (const struct loop *, struct induction *, rtx, rtx,
654                         rtx, rtx, rtx, rtx, int, enum g_types, int, int,
655                         rtx *);
656 static void update_giv_derive (const struct loop *, rtx);
657 static HOST_WIDE_INT get_monotonic_increment (struct iv_class *);
658 static bool biased_biv_fits_mode_p (const struct loop *, struct iv_class *,
659                                     HOST_WIDE_INT, enum machine_mode,
660                                     unsigned HOST_WIDE_INT);
661 static bool biv_fits_mode_p (const struct loop *, struct iv_class *,
662                              HOST_WIDE_INT, enum machine_mode, bool);
663 static bool extension_within_bounds_p (const struct loop *, struct iv_class *,
664                                        HOST_WIDE_INT, rtx);
665 static void check_ext_dependent_givs (const struct loop *, struct iv_class *);
666 static int basic_induction_var (const struct loop *, rtx, enum machine_mode,
667                                 rtx, rtx, rtx *, rtx *, rtx **);
668 static rtx simplify_giv_expr (const struct loop *, rtx, rtx *, int *);
669 static int general_induction_var (const struct loop *loop, rtx, rtx *, rtx *,
670                                   rtx *, rtx *, int, int *, enum machine_mode);
671 static int consec_sets_giv (const struct loop *, int, rtx, rtx, rtx, rtx *,
672                             rtx *, rtx *, rtx *);
673 static int check_dbra_loop (struct loop *, int);
674 static rtx express_from_1 (rtx, rtx, rtx);
675 static rtx combine_givs_p (struct induction *, struct induction *);
676 static int cmp_combine_givs_stats (const void *, const void *);
677 static void combine_givs (struct loop_regs *, struct iv_class *);
678 static int product_cheap_p (rtx, rtx);
679 static int maybe_eliminate_biv (const struct loop *, struct iv_class *, int,
680                                 int, int);
681 static int maybe_eliminate_biv_1 (const struct loop *, rtx, rtx,
682                                   struct iv_class *, int, basic_block, rtx);
683 static int last_use_this_basic_block (rtx, rtx);
684 static void record_initial (rtx, rtx, void *);
685 static void update_reg_last_use (rtx, rtx);
686 static rtx next_insn_in_loop (const struct loop *, rtx);
687 static void loop_regs_scan (const struct loop *, int);
688 static int count_insns_in_loop (const struct loop *);
689 static int find_mem_in_note_1 (rtx *, void *);
690 static rtx find_mem_in_note (rtx);
691 static void load_mems (const struct loop *);
692 static int insert_loop_mem (rtx *, void *);
693 static int replace_loop_mem (rtx *, void *);
694 static void replace_loop_mems (rtx, rtx, rtx, int);
695 static int replace_loop_reg (rtx *, void *);
696 static void replace_loop_regs (rtx insn, rtx, rtx);
697 static void note_reg_stored (rtx, rtx, void *);
698 static void try_copy_prop (const struct loop *, rtx, unsigned int);
699 static void try_swap_copy_prop (const struct loop *, rtx, unsigned int);
700 static rtx check_insn_for_givs (struct loop *, rtx, int, int);
701 static rtx check_insn_for_bivs (struct loop *, rtx, int, int);
702 static rtx gen_add_mult (rtx, rtx, rtx, rtx);
703 static void loop_regs_update (const struct loop *, rtx);
704 static int iv_add_mult_cost (rtx, rtx, rtx, rtx);
705 static int loop_invariant_p (const struct loop *, rtx);
706 static rtx loop_insn_hoist (const struct loop *, rtx);
707 static void loop_iv_add_mult_emit_before (const struct loop *, rtx, rtx, rtx,
708                                           rtx, basic_block, rtx);
709 static rtx loop_insn_emit_before (const struct loop *, basic_block,
710                                   rtx, rtx);
711 static int loop_insn_first_p (rtx, rtx);
712 static rtx get_condition_for_loop (const struct loop *, rtx);
713 static void loop_iv_add_mult_sink (const struct loop *, rtx, rtx, rtx, rtx);
714 static void loop_iv_add_mult_hoist (const struct loop *, rtx, rtx, rtx, rtx);
715 static rtx extend_value_for_giv (struct induction *, rtx);
716 static rtx loop_insn_sink (const struct loop *, rtx);
717
718 static rtx loop_insn_emit_after (const struct loop *, basic_block, rtx, rtx);
719 static rtx loop_call_insn_emit_before (const struct loop *, basic_block,
720                                        rtx, rtx);
721 static rtx loop_call_insn_hoist (const struct loop *, rtx);
722 static rtx loop_insn_sink_or_swim (const struct loop *, rtx);
723
724 static void loop_dump_aux (const struct loop *, FILE *, int);
725 static void loop_delete_insns (rtx, rtx);
726 static HOST_WIDE_INT remove_constant_addition (rtx *);
727 static rtx gen_load_of_final_value (rtx, rtx);
728 void debug_ivs (const struct loop *);
729 void debug_iv_class (const struct iv_class *);
730 void debug_biv (const struct induction *);
731 void debug_giv (const struct induction *);
732 void debug_loop (const struct loop *);
733 void debug_loops (const struct loops *);
734
735 typedef struct loop_replace_args
736 {
737   rtx match;
738   rtx replacement;
739   rtx insn;
740 } loop_replace_args;
741
742 /* Nonzero iff INSN is between START and END, inclusive.  */
743 #define INSN_IN_RANGE_P(INSN, START, END)       \
744   (INSN_UID (INSN) < max_uid_for_loop           \
745    && INSN_LUID (INSN) >= INSN_LUID (START)     \
746    && INSN_LUID (INSN) <= INSN_LUID (END))
747
748 /* Indirect_jump_in_function is computed once per function.  */
749 static int indirect_jump_in_function;
750 static int indirect_jump_in_function_p (rtx);
751
752 static int compute_luids (rtx, rtx, int);
753
754 static int biv_elimination_giv_has_0_offset (struct induction *,
755                                              struct induction *, rtx);
756 \f
757 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
758    copy the value of the strength reduced giv to its original register.  */
759 static int copy_cost;
760
761 /* Cost of using a register, to normalize the benefits of a giv.  */
762 static int reg_address_cost;
763
764 void
765 init_loop (void)
766 {
767   rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
768
769   reg_address_cost = address_cost (reg, SImode);
770
771   copy_cost = COSTS_N_INSNS (1);
772 }
773 \f
774 /* Compute the mapping from uids to luids.
775    LUIDs are numbers assigned to insns, like uids,
776    except that luids increase monotonically through the code.
777    Start at insn START and stop just before END.  Assign LUIDs
778    starting with PREV_LUID + 1.  Return the last assigned LUID + 1.  */
779 static int
780 compute_luids (rtx start, rtx end, int prev_luid)
781 {
782   int i;
783   rtx insn;
784
785   for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
786     {
787       if (INSN_UID (insn) >= max_uid_for_loop)
788         continue;
789       /* Don't assign luids to line-number NOTEs, so that the distance in
790          luids between two insns is not affected by -g.  */
791       if (!NOTE_P (insn)
792           || NOTE_LINE_NUMBER (insn) <= 0)
793         uid_luid[INSN_UID (insn)] = ++i;
794       else
795         /* Give a line number note the same luid as preceding insn.  */
796         uid_luid[INSN_UID (insn)] = i;
797     }
798   return i + 1;
799 }
800 \f
801 /* Entry point of this file.  Perform loop optimization
802    on the current function.  F is the first insn of the function
803    and DUMPFILE is a stream for output of a trace of actions taken
804    (or 0 if none should be output).  */
805
806 void
807 loop_optimize (rtx f, FILE *dumpfile, int flags)
808 {
809   rtx insn;
810   int i;
811   struct loops loops_data;
812   struct loops *loops = &loops_data;
813   struct loop_info *loops_info;
814
815   loop_dump_stream = dumpfile;
816
817   init_recog_no_volatile ();
818
819   max_reg_before_loop = max_reg_num ();
820   loop_max_reg = max_reg_before_loop;
821
822   regs_may_share = 0;
823
824   /* Count the number of loops.  */
825
826   max_loop_num = 0;
827   for (insn = f; insn; insn = NEXT_INSN (insn))
828     {
829       if (NOTE_P (insn)
830           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
831         max_loop_num++;
832     }
833
834   /* Don't waste time if no loops.  */
835   if (max_loop_num == 0)
836     return;
837
838   loops->num = max_loop_num;
839
840   /* Get size to use for tables indexed by uids.
841      Leave some space for labels allocated by find_and_verify_loops.  */
842   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
843
844   uid_luid = xcalloc (max_uid_for_loop, sizeof (int));
845   uid_loop = xcalloc (max_uid_for_loop, sizeof (struct loop *));
846
847   /* Allocate storage for array of loops.  */
848   loops->array = xcalloc (loops->num, sizeof (struct loop));
849
850   /* Find and process each loop.
851      First, find them, and record them in order of their beginnings.  */
852   find_and_verify_loops (f, loops);
853
854   /* Allocate and initialize auxiliary loop information.  */
855   loops_info = xcalloc (loops->num, sizeof (struct loop_info));
856   for (i = 0; i < (int) loops->num; i++)
857     loops->array[i].aux = loops_info + i;
858
859   /* Now find all register lifetimes.  This must be done after
860      find_and_verify_loops, because it might reorder the insns in the
861      function.  */
862   reg_scan (f, max_reg_before_loop);
863
864   /* This must occur after reg_scan so that registers created by gcse
865      will have entries in the register tables.
866
867      We could have added a call to reg_scan after gcse_main in toplev.c,
868      but moving this call to init_alias_analysis is more efficient.  */
869   init_alias_analysis ();
870
871   /* See if we went too far.  Note that get_max_uid already returns
872      one more that the maximum uid of all insn.  */
873   gcc_assert (get_max_uid () <= max_uid_for_loop);
874   /* Now reset it to the actual size we need.  See above.  */
875   max_uid_for_loop = get_max_uid ();
876
877   /* find_and_verify_loops has already called compute_luids, but it
878      might have rearranged code afterwards, so we need to recompute
879      the luids now.  */
880   compute_luids (f, NULL_RTX, 0);
881
882   /* Don't leave gaps in uid_luid for insns that have been
883      deleted.  It is possible that the first or last insn
884      using some register has been deleted by cross-jumping.
885      Make sure that uid_luid for that former insn's uid
886      points to the general area where that insn used to be.  */
887   for (i = 0; i < max_uid_for_loop; i++)
888     {
889       uid_luid[0] = uid_luid[i];
890       if (uid_luid[0] != 0)
891         break;
892     }
893   for (i = 0; i < max_uid_for_loop; i++)
894     if (uid_luid[i] == 0)
895       uid_luid[i] = uid_luid[i - 1];
896
897   /* Determine if the function has indirect jump.  On some systems
898      this prevents low overhead loop instructions from being used.  */
899   indirect_jump_in_function = indirect_jump_in_function_p (f);
900
901   /* Now scan the loops, last ones first, since this means inner ones are done
902      before outer ones.  */
903   for (i = max_loop_num - 1; i >= 0; i--)
904     {
905       struct loop *loop = &loops->array[i];
906
907       if (! loop->invalid && loop->end)
908         {
909           scan_loop (loop, flags);
910           ggc_collect ();
911         }
912     }
913
914   end_alias_analysis ();
915
916   /* Clean up.  */
917   for (i = 0; i < (int) loops->num; i++)
918     free (loops_info[i].mems);
919   
920   free (uid_luid);
921   free (uid_loop);
922   free (loops_info);
923   free (loops->array);
924 }
925 \f
926 /* Returns the next insn, in execution order, after INSN.  START and
927    END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
928    respectively.  LOOP->TOP, if non-NULL, is the top of the loop in the
929    insn-stream; it is used with loops that are entered near the
930    bottom.  */
931
932 static rtx
933 next_insn_in_loop (const struct loop *loop, rtx insn)
934 {
935   insn = NEXT_INSN (insn);
936
937   if (insn == loop->end)
938     {
939       if (loop->top)
940         /* Go to the top of the loop, and continue there.  */
941         insn = loop->top;
942       else
943         /* We're done.  */
944         insn = NULL_RTX;
945     }
946
947   if (insn == loop->scan_start)
948     /* We're done.  */
949     insn = NULL_RTX;
950
951   return insn;
952 }
953
954 /* Find any register references hidden inside X and add them to
955    the dependency list DEPS.  This is used to look inside CLOBBER (MEM
956    when checking whether a PARALLEL can be pulled out of a loop.  */
957
958 static rtx
959 find_regs_nested (rtx deps, rtx x)
960 {
961   enum rtx_code code = GET_CODE (x);
962   if (code == REG)
963     deps = gen_rtx_EXPR_LIST (VOIDmode, x, deps);
964   else
965     {
966       const char *fmt = GET_RTX_FORMAT (code);
967       int i, j;
968       for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
969         {
970           if (fmt[i] == 'e')
971             deps = find_regs_nested (deps, XEXP (x, i));
972           else if (fmt[i] == 'E')
973             for (j = 0; j < XVECLEN (x, i); j++)
974               deps = find_regs_nested (deps, XVECEXP (x, i, j));
975         }
976     }
977   return deps;
978 }
979
980 /* Optimize one loop described by LOOP.  */
981
982 /* ??? Could also move memory writes out of loops if the destination address
983    is invariant, the source is invariant, the memory write is not volatile,
984    and if we can prove that no read inside the loop can read this address
985    before the write occurs.  If there is a read of this address after the
986    write, then we can also mark the memory read as invariant.  */
987
988 static void
989 scan_loop (struct loop *loop, int flags)
990 {
991   struct loop_info *loop_info = LOOP_INFO (loop);
992   struct loop_regs *regs = LOOP_REGS (loop);
993   int i;
994   rtx loop_start = loop->start;
995   rtx loop_end = loop->end;
996   rtx p;
997   /* 1 if we are scanning insns that could be executed zero times.  */
998   int maybe_never = 0;
999   /* 1 if we are scanning insns that might never be executed
1000      due to a subroutine call which might exit before they are reached.  */
1001   int call_passed = 0;
1002   /* Number of insns in the loop.  */
1003   int insn_count;
1004   int tem;
1005   rtx temp, update_start, update_end;
1006   /* The SET from an insn, if it is the only SET in the insn.  */
1007   rtx set, set1;
1008   /* Chain describing insns movable in current loop.  */
1009   struct loop_movables *movables = LOOP_MOVABLES (loop);
1010   /* Ratio of extra register life span we can justify
1011      for saving an instruction.  More if loop doesn't call subroutines
1012      since in that case saving an insn makes more difference
1013      and more registers are available.  */
1014   int threshold;
1015   int in_libcall;
1016
1017   loop->top = 0;
1018
1019   movables->head = 0;
1020   movables->last = 0;
1021
1022   /* Determine whether this loop starts with a jump down to a test at
1023      the end.  This will occur for a small number of loops with a test
1024      that is too complex to duplicate in front of the loop.
1025
1026      We search for the first insn or label in the loop, skipping NOTEs.
1027      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
1028      (because we might have a loop executed only once that contains a
1029      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
1030      (in case we have a degenerate loop).
1031
1032      Note that if we mistakenly think that a loop is entered at the top
1033      when, in fact, it is entered at the exit test, the only effect will be
1034      slightly poorer optimization.  Making the opposite error can generate
1035      incorrect code.  Since very few loops now start with a jump to the
1036      exit test, the code here to detect that case is very conservative.  */
1037
1038   for (p = NEXT_INSN (loop_start);
1039        p != loop_end
1040          && !LABEL_P (p) && ! INSN_P (p)
1041          && (!NOTE_P (p)
1042              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
1043                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
1044        p = NEXT_INSN (p))
1045     ;
1046
1047   loop->scan_start = p;
1048
1049   /* If loop end is the end of the current function, then emit a
1050      NOTE_INSN_DELETED after loop_end and set loop->sink to the dummy
1051      note insn.  This is the position we use when sinking insns out of
1052      the loop.  */
1053   if (NEXT_INSN (loop->end) != 0)
1054     loop->sink = NEXT_INSN (loop->end);
1055   else
1056     loop->sink = emit_note_after (NOTE_INSN_DELETED, loop->end);
1057
1058   /* Set up variables describing this loop.  */
1059   prescan_loop (loop);
1060   threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
1061
1062   /* If loop has a jump before the first label,
1063      the true entry is the target of that jump.
1064      Start scan from there.
1065      But record in LOOP->TOP the place where the end-test jumps
1066      back to so we can scan that after the end of the loop.  */
1067   if (JUMP_P (p)
1068       /* Loop entry must be unconditional jump (and not a RETURN)  */
1069       && any_uncondjump_p (p)
1070       && JUMP_LABEL (p) != 0
1071       /* Check to see whether the jump actually
1072          jumps out of the loop (meaning it's no loop).
1073          This case can happen for things like
1074          do {..} while (0).  If this label was generated previously
1075          by loop, we can't tell anything about it and have to reject
1076          the loop.  */
1077       && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, loop_end))
1078     {
1079       loop->top = next_label (loop->scan_start);
1080       loop->scan_start = JUMP_LABEL (p);
1081     }
1082
1083   /* If LOOP->SCAN_START was an insn created by loop, we don't know its luid
1084      as required by loop_reg_used_before_p.  So skip such loops.  (This
1085      test may never be true, but it's best to play it safe.)
1086
1087      Also, skip loops where we do not start scanning at a label.  This
1088      test also rejects loops starting with a JUMP_INSN that failed the
1089      test above.  */
1090
1091   if (INSN_UID (loop->scan_start) >= max_uid_for_loop
1092       || !LABEL_P (loop->scan_start))
1093     {
1094       if (loop_dump_stream)
1095         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
1096                  INSN_UID (loop_start), INSN_UID (loop_end));
1097       return;
1098     }
1099
1100   /* Allocate extra space for REGs that might be created by load_mems.
1101      We allocate a little extra slop as well, in the hopes that we
1102      won't have to reallocate the regs array.  */
1103   loop_regs_scan (loop, loop_info->mems_idx + 16);
1104   insn_count = count_insns_in_loop (loop);
1105
1106   if (loop_dump_stream)
1107     fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
1108              INSN_UID (loop_start), INSN_UID (loop_end), insn_count);
1109
1110   /* Scan through the loop finding insns that are safe to move.
1111      Set REGS->ARRAY[I].SET_IN_LOOP negative for the reg I being set, so that
1112      this reg will be considered invariant for subsequent insns.
1113      We consider whether subsequent insns use the reg
1114      in deciding whether it is worth actually moving.
1115
1116      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
1117      and therefore it is possible that the insns we are scanning
1118      would never be executed.  At such times, we must make sure
1119      that it is safe to execute the insn once instead of zero times.
1120      When MAYBE_NEVER is 0, all insns will be executed at least once
1121      so that is not a problem.  */
1122
1123   for (in_libcall = 0, p = next_insn_in_loop (loop, loop->scan_start);
1124        p != NULL_RTX;
1125        p = next_insn_in_loop (loop, p))
1126     {
1127       if (in_libcall && INSN_P (p) && find_reg_note (p, REG_RETVAL, NULL_RTX))
1128         in_libcall--;
1129       if (NONJUMP_INSN_P (p))
1130         {
1131           /* Do not scan past an optimization barrier.  */
1132           if (GET_CODE (PATTERN (p)) == ASM_INPUT)
1133             break;
1134           temp = find_reg_note (p, REG_LIBCALL, NULL_RTX);
1135           if (temp)
1136             in_libcall++;
1137           if (! in_libcall
1138               && (set = single_set (p))
1139               && REG_P (SET_DEST (set))
1140               && SET_DEST (set) != frame_pointer_rtx
1141 #ifdef PIC_OFFSET_TABLE_REG_CALL_CLOBBERED
1142               && SET_DEST (set) != pic_offset_table_rtx
1143 #endif
1144               && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
1145             {
1146               int tem1 = 0;
1147               int tem2 = 0;
1148               int move_insn = 0;
1149               int insert_temp = 0;
1150               rtx src = SET_SRC (set);
1151               rtx dependencies = 0;
1152
1153               /* Figure out what to use as a source of this insn.  If a
1154                  REG_EQUIV note is given or if a REG_EQUAL note with a
1155                  constant operand is specified, use it as the source and
1156                  mark that we should move this insn by calling
1157                  emit_move_insn rather that duplicating the insn.
1158
1159                  Otherwise, only use the REG_EQUAL contents if a REG_RETVAL
1160                  note is present.  */
1161               temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
1162               if (temp)
1163                 src = XEXP (temp, 0), move_insn = 1;
1164               else
1165                 {
1166                   temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
1167                   if (temp && CONSTANT_P (XEXP (temp, 0)))
1168                     src = XEXP (temp, 0), move_insn = 1;
1169                   if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
1170                     {
1171                       src = XEXP (temp, 0);
1172                       /* A libcall block can use regs that don't appear in
1173                          the equivalent expression.  To move the libcall,
1174                          we must move those regs too.  */
1175                       dependencies = libcall_other_reg (p, src);
1176                     }
1177                 }
1178
1179               /* For parallels, add any possible uses to the dependencies, as
1180                  we can't move the insn without resolving them first.
1181                  MEMs inside CLOBBERs may also reference registers; these
1182                  count as implicit uses.  */
1183               if (GET_CODE (PATTERN (p)) == PARALLEL)
1184                 {
1185                   for (i = 0; i < XVECLEN (PATTERN (p), 0); i++)
1186                     {
1187                       rtx x = XVECEXP (PATTERN (p), 0, i);
1188                       if (GET_CODE (x) == USE)
1189                         dependencies
1190                           = gen_rtx_EXPR_LIST (VOIDmode, XEXP (x, 0),
1191                                                dependencies);
1192                       else if (GET_CODE (x) == CLOBBER 
1193                                && MEM_P (XEXP (x, 0)))
1194                         dependencies = find_regs_nested (dependencies, 
1195                                                   XEXP (XEXP (x, 0), 0));
1196                     }
1197                 }
1198
1199               if (/* The register is used in basic blocks other
1200                       than the one where it is set (meaning that
1201                       something after this point in the loop might
1202                       depend on its value before the set).  */
1203                    ! reg_in_basic_block_p (p, SET_DEST (set))
1204                    /* And the set is not guaranteed to be executed once
1205                       the loop starts, or the value before the set is
1206                       needed before the set occurs...
1207
1208                       ??? Note we have quadratic behavior here, mitigated
1209                       by the fact that the previous test will often fail for
1210                       large loops.  Rather than re-scanning the entire loop
1211                       each time for register usage, we should build tables
1212                       of the register usage and use them here instead.  */
1213                    && (maybe_never
1214                        || loop_reg_used_before_p (loop, set, p)))
1215                 /* It is unsafe to move the set.  However, it may be OK to
1216                    move the source into a new pseudo, and substitute a
1217                    reg-to-reg copy for the original insn.
1218
1219                    This code used to consider it OK to move a set of a variable
1220                    which was not created by the user and not used in an exit
1221                    test.
1222                    That behavior is incorrect and was removed.  */
1223                 insert_temp = 1;
1224
1225               /* Don't try to optimize a MODE_CC set with a constant
1226                  source.  It probably will be combined with a conditional
1227                  jump.  */
1228               if (GET_MODE_CLASS (GET_MODE (SET_DEST (set))) == MODE_CC
1229                   && CONSTANT_P (src))
1230                 ;
1231               /* Don't try to optimize a register that was made
1232                  by loop-optimization for an inner loop.
1233                  We don't know its life-span, so we can't compute
1234                  the benefit.  */
1235               else if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
1236                 ;
1237               /* Don't move the source and add a reg-to-reg copy:
1238                  - with -Os (this certainly increases size),
1239                  - if the mode doesn't support copy operations (obviously),
1240                  - if the source is already a reg (the motion will gain nothing),
1241                  - if the source is a legitimate constant (likewise).  */
1242               else if (insert_temp
1243                        && (optimize_size
1244                            || ! can_copy_p (GET_MODE (SET_SRC (set)))
1245                            || REG_P (SET_SRC (set))
1246                            || (CONSTANT_P (SET_SRC (set))
1247                                && LEGITIMATE_CONSTANT_P (SET_SRC (set)))))
1248                 ;
1249               else if ((tem = loop_invariant_p (loop, src))
1250                        && (dependencies == 0
1251                            || (tem2
1252                                = loop_invariant_p (loop, dependencies)) != 0)
1253                        && (regs->array[REGNO (SET_DEST (set))].set_in_loop == 1
1254                            || (tem1
1255                                = consec_sets_invariant_p
1256                                (loop, SET_DEST (set),
1257                                 regs->array[REGNO (SET_DEST (set))].set_in_loop,
1258                                 p)))
1259                        /* If the insn can cause a trap (such as divide by zero),
1260                           can't move it unless it's guaranteed to be executed
1261                           once loop is entered.  Even a function call might
1262                           prevent the trap insn from being reached
1263                           (since it might exit!)  */
1264                        && ! ((maybe_never || call_passed)
1265                              && may_trap_p (src)))
1266                 {
1267                   struct movable *m;
1268                   int regno = REGNO (SET_DEST (set));
1269
1270                   /* A potential lossage is where we have a case where two insns
1271                      can be combined as long as they are both in the loop, but
1272                      we move one of them outside the loop.  For large loops,
1273                      this can lose.  The most common case of this is the address
1274                      of a function being called.
1275
1276                      Therefore, if this register is marked as being used
1277                      exactly once if we are in a loop with calls
1278                      (a "large loop"), see if we can replace the usage of
1279                      this register with the source of this SET.  If we can,
1280                      delete this insn.
1281
1282                      Don't do this if P has a REG_RETVAL note or if we have
1283                      SMALL_REGISTER_CLASSES and SET_SRC is a hard register.  */
1284
1285                   if (loop_info->has_call
1286                       && regs->array[regno].single_usage != 0
1287                       && regs->array[regno].single_usage != const0_rtx
1288                       && REGNO_FIRST_UID (regno) == INSN_UID (p)
1289                       && (REGNO_LAST_UID (regno)
1290                           == INSN_UID (regs->array[regno].single_usage))
1291                       && regs->array[regno].set_in_loop == 1
1292                       && GET_CODE (SET_SRC (set)) != ASM_OPERANDS
1293                       && ! side_effects_p (SET_SRC (set))
1294                       && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
1295                       && (! SMALL_REGISTER_CLASSES
1296                           || (! (REG_P (SET_SRC (set))
1297                                  && (REGNO (SET_SRC (set))
1298                                      < FIRST_PSEUDO_REGISTER))))
1299                       && regno >= FIRST_PSEUDO_REGISTER 
1300                       /* This test is not redundant; SET_SRC (set) might be
1301                          a call-clobbered register and the life of REGNO
1302                          might span a call.  */
1303                       && ! modified_between_p (SET_SRC (set), p,
1304                                                regs->array[regno].single_usage)
1305                       && no_labels_between_p (p,
1306                                               regs->array[regno].single_usage)
1307                       && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
1308                                                regs->array[regno].single_usage))
1309                     {
1310                       /* Replace any usage in a REG_EQUAL note.  Must copy
1311                          the new source, so that we don't get rtx sharing
1312                          between the SET_SOURCE and REG_NOTES of insn p.  */
1313                       REG_NOTES (regs->array[regno].single_usage)
1314                         = (replace_rtx
1315                            (REG_NOTES (regs->array[regno].single_usage),
1316                             SET_DEST (set), copy_rtx (SET_SRC (set))));
1317
1318                       delete_insn (p);
1319                       for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
1320                            i++)
1321                         regs->array[regno+i].set_in_loop = 0;
1322                       continue;
1323                     }
1324
1325                   m = xmalloc (sizeof (struct movable));
1326                   m->next = 0;
1327                   m->insn = p;
1328                   m->set_src = src;
1329                   m->dependencies = dependencies;
1330                   m->set_dest = SET_DEST (set);
1331                   m->force = 0;
1332                   m->consec
1333                     = regs->array[REGNO (SET_DEST (set))].set_in_loop - 1;
1334                   m->done = 0;
1335                   m->forces = 0;
1336                   m->partial = 0;
1337                   m->move_insn = move_insn;
1338                   m->move_insn_first = 0;
1339                   m->insert_temp = insert_temp;
1340                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1341                   m->savemode = VOIDmode;
1342                   m->regno = regno;
1343                   /* Set M->cond if either loop_invariant_p
1344                      or consec_sets_invariant_p returned 2
1345                      (only conditionally invariant).  */
1346                   m->cond = ((tem | tem1 | tem2) > 1);
1347                   m->global =  LOOP_REG_GLOBAL_P (loop, regno);
1348                   m->match = 0;
1349                   m->lifetime = LOOP_REG_LIFETIME (loop, regno);
1350                   m->savings = regs->array[regno].n_times_set;
1351                   if (find_reg_note (p, REG_RETVAL, NULL_RTX))
1352                     m->savings += libcall_benefit (p);
1353                   for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set)); i++)
1354                     regs->array[regno+i].set_in_loop = move_insn ? -2 : -1;
1355                   /* Add M to the end of the chain MOVABLES.  */
1356                   loop_movables_add (movables, m);
1357
1358                   if (m->consec > 0)
1359                     {
1360                       /* It is possible for the first instruction to have a
1361                          REG_EQUAL note but a non-invariant SET_SRC, so we must
1362                          remember the status of the first instruction in case
1363                          the last instruction doesn't have a REG_EQUAL note.  */
1364                       m->move_insn_first = m->move_insn;
1365
1366                       /* Skip this insn, not checking REG_LIBCALL notes.  */
1367                       p = next_nonnote_insn (p);
1368                       /* Skip the consecutive insns, if there are any.  */
1369                       p = skip_consec_insns (p, m->consec);
1370                       /* Back up to the last insn of the consecutive group.  */
1371                       p = prev_nonnote_insn (p);
1372
1373                       /* We must now reset m->move_insn, m->is_equiv, and
1374                          possibly m->set_src to correspond to the effects of
1375                          all the insns.  */
1376                       temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
1377                       if (temp)
1378                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
1379                       else
1380                         {
1381                           temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
1382                           if (temp && CONSTANT_P (XEXP (temp, 0)))
1383                             m->set_src = XEXP (temp, 0), m->move_insn = 1;
1384                           else
1385                             m->move_insn = 0;
1386
1387                         }
1388                       m->is_equiv
1389                         = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1390                     }
1391                 }
1392               /* If this register is always set within a STRICT_LOW_PART
1393                  or set to zero, then its high bytes are constant.
1394                  So clear them outside the loop and within the loop
1395                  just load the low bytes.
1396                  We must check that the machine has an instruction to do so.
1397                  Also, if the value loaded into the register
1398                  depends on the same register, this cannot be done.  */
1399               else if (SET_SRC (set) == const0_rtx
1400                        && NONJUMP_INSN_P (NEXT_INSN (p))
1401                        && (set1 = single_set (NEXT_INSN (p)))
1402                        && GET_CODE (set1) == SET
1403                        && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1404                        && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1405                        && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1406                            == SET_DEST (set))
1407                        && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1408                 {
1409                   int regno = REGNO (SET_DEST (set));
1410                   if (regs->array[regno].set_in_loop == 2)
1411                     {
1412                       struct movable *m;
1413                       m = xmalloc (sizeof (struct movable));
1414                       m->next = 0;
1415                       m->insn = p;
1416                       m->set_dest = SET_DEST (set);
1417                       m->dependencies = 0;
1418                       m->force = 0;
1419                       m->consec = 0;
1420                       m->done = 0;
1421                       m->forces = 0;
1422                       m->move_insn = 0;
1423                       m->move_insn_first = 0;
1424                       m->insert_temp = insert_temp;
1425                       m->partial = 1;
1426                       /* If the insn may not be executed on some cycles,
1427                          we can't clear the whole reg; clear just high part.
1428                          Not even if the reg is used only within this loop.
1429                          Consider this:
1430                          while (1)
1431                            while (s != t) {
1432                              if (foo ()) x = *s;
1433                              use (x);
1434                            }
1435                          Clearing x before the inner loop could clobber a value
1436                          being saved from the last time around the outer loop.
1437                          However, if the reg is not used outside this loop
1438                          and all uses of the register are in the same
1439                          basic block as the store, there is no problem.
1440
1441                          If this insn was made by loop, we don't know its
1442                          INSN_LUID and hence must make a conservative
1443                          assumption.  */
1444                       m->global = (INSN_UID (p) >= max_uid_for_loop
1445                                    || LOOP_REG_GLOBAL_P (loop, regno)
1446                                    || (labels_in_range_p
1447                                        (p, REGNO_FIRST_LUID (regno))));
1448                       if (maybe_never && m->global)
1449                         m->savemode = GET_MODE (SET_SRC (set1));
1450                       else
1451                         m->savemode = VOIDmode;
1452                       m->regno = regno;
1453                       m->cond = 0;
1454                       m->match = 0;
1455                       m->lifetime = LOOP_REG_LIFETIME (loop, regno);
1456                       m->savings = 1;
1457                       for (i = 0;
1458                            i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
1459                            i++)
1460                         regs->array[regno+i].set_in_loop = -1;
1461                       /* Add M to the end of the chain MOVABLES.  */
1462                       loop_movables_add (movables, m);
1463                     }
1464                 }
1465             }
1466         }
1467       /* Past a call insn, we get to insns which might not be executed
1468          because the call might exit.  This matters for insns that trap.
1469          Constant and pure call insns always return, so they don't count.  */
1470       else if (CALL_P (p) && ! CONST_OR_PURE_CALL_P (p))
1471         call_passed = 1;
1472       /* Past a label or a jump, we get to insns for which we
1473          can't count on whether or how many times they will be
1474          executed during each iteration.  Therefore, we can
1475          only move out sets of trivial variables
1476          (those not used after the loop).  */
1477       /* Similar code appears twice in strength_reduce.  */
1478       else if ((LABEL_P (p) || JUMP_P (p))
1479                /* If we enter the loop in the middle, and scan around to the
1480                   beginning, don't set maybe_never for that.  This must be an
1481                   unconditional jump, otherwise the code at the top of the
1482                   loop might never be executed.  Unconditional jumps are
1483                   followed by a barrier then the loop_end.  */
1484                && ! (JUMP_P (p) && JUMP_LABEL (p) == loop->top
1485                      && NEXT_INSN (NEXT_INSN (p)) == loop_end
1486                      && any_uncondjump_p (p)))
1487         maybe_never = 1;
1488     }
1489
1490   /* If one movable subsumes another, ignore that other.  */
1491
1492   ignore_some_movables (movables);
1493
1494   /* For each movable insn, see if the reg that it loads
1495      leads when it dies right into another conditionally movable insn.
1496      If so, record that the second insn "forces" the first one,
1497      since the second can be moved only if the first is.  */
1498
1499   force_movables (movables);
1500
1501   /* See if there are multiple movable insns that load the same value.
1502      If there are, make all but the first point at the first one
1503      through the `match' field, and add the priorities of them
1504      all together as the priority of the first.  */
1505
1506   combine_movables (movables, regs);
1507
1508   /* Now consider each movable insn to decide whether it is worth moving.
1509      Store 0 in regs->array[I].set_in_loop for each reg I that is moved.
1510
1511      For machines with few registers this increases code size, so do not
1512      move moveables when optimizing for code size on such machines.
1513      (The 18 below is the value for i386.)  */
1514
1515   if (!optimize_size
1516       || (reg_class_size[GENERAL_REGS] > 18 && !loop_info->has_call))
1517     {
1518       move_movables (loop, movables, threshold, insn_count);
1519
1520       /* Recalculate regs->array if move_movables has created new
1521          registers.  */
1522       if (max_reg_num () > regs->num)
1523         {
1524           loop_regs_scan (loop, 0);
1525           for (update_start = loop_start;
1526                PREV_INSN (update_start)
1527                && !LABEL_P (PREV_INSN (update_start));
1528                update_start = PREV_INSN (update_start))
1529             ;
1530           update_end = NEXT_INSN (loop_end);
1531
1532           reg_scan_update (update_start, update_end, loop_max_reg);
1533           loop_max_reg = max_reg_num ();
1534         }
1535     }
1536
1537   /* Now candidates that still are negative are those not moved.
1538      Change regs->array[I].set_in_loop to indicate that those are not actually
1539      invariant.  */
1540   for (i = 0; i < regs->num; i++)
1541     if (regs->array[i].set_in_loop < 0)
1542       regs->array[i].set_in_loop = regs->array[i].n_times_set;
1543
1544   /* Now that we've moved some things out of the loop, we might be able to
1545      hoist even more memory references.  */
1546   load_mems (loop);
1547
1548   /* Recalculate regs->array if load_mems has created new registers.  */
1549   if (max_reg_num () > regs->num)
1550     loop_regs_scan (loop, 0);
1551
1552   for (update_start = loop_start;
1553        PREV_INSN (update_start)
1554          && !LABEL_P (PREV_INSN (update_start));
1555        update_start = PREV_INSN (update_start))
1556     ;
1557   update_end = NEXT_INSN (loop_end);
1558
1559   reg_scan_update (update_start, update_end, loop_max_reg);
1560   loop_max_reg = max_reg_num ();
1561
1562   if (flag_strength_reduce)
1563     {
1564       if (update_end && LABEL_P (update_end))
1565         /* Ensure our label doesn't go away.  */
1566         LABEL_NUSES (update_end)++;
1567
1568       strength_reduce (loop, flags);
1569
1570       reg_scan_update (update_start, update_end, loop_max_reg);
1571       loop_max_reg = max_reg_num ();
1572
1573       if (update_end && LABEL_P (update_end)
1574           && --LABEL_NUSES (update_end) == 0)
1575         delete_related_insns (update_end);
1576     }
1577
1578
1579   /* The movable information is required for strength reduction.  */
1580   loop_movables_free (movables);
1581
1582   free (regs->array);
1583   regs->array = 0;
1584   regs->num = 0;
1585 }
1586 \f
1587 /* Add elements to *OUTPUT to record all the pseudo-regs
1588    mentioned in IN_THIS but not mentioned in NOT_IN_THIS.  */
1589
1590 static void
1591 record_excess_regs (rtx in_this, rtx not_in_this, rtx *output)
1592 {
1593   enum rtx_code code;
1594   const char *fmt;
1595   int i;
1596
1597   code = GET_CODE (in_this);
1598
1599   switch (code)
1600     {
1601     case PC:
1602     case CC0:
1603     case CONST_INT:
1604     case CONST_DOUBLE:
1605     case CONST:
1606     case SYMBOL_REF:
1607     case LABEL_REF:
1608       return;
1609
1610     case REG:
1611       if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1612           && ! reg_mentioned_p (in_this, not_in_this))
1613         *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1614       return;
1615
1616     default:
1617       break;
1618     }
1619
1620   fmt = GET_RTX_FORMAT (code);
1621   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1622     {
1623       int j;
1624
1625       switch (fmt[i])
1626         {
1627         case 'E':
1628           for (j = 0; j < XVECLEN (in_this, i); j++)
1629             record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1630           break;
1631
1632         case 'e':
1633           record_excess_regs (XEXP (in_this, i), not_in_this, output);
1634           break;
1635         }
1636     }
1637 }
1638 \f
1639 /* Check what regs are referred to in the libcall block ending with INSN,
1640    aside from those mentioned in the equivalent value.
1641    If there are none, return 0.
1642    If there are one or more, return an EXPR_LIST containing all of them.  */
1643
1644 static rtx
1645 libcall_other_reg (rtx insn, rtx equiv)
1646 {
1647   rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1648   rtx p = XEXP (note, 0);
1649   rtx output = 0;
1650
1651   /* First, find all the regs used in the libcall block
1652      that are not mentioned as inputs to the result.  */
1653
1654   while (p != insn)
1655     {
1656       if (INSN_P (p))
1657         record_excess_regs (PATTERN (p), equiv, &output);
1658       p = NEXT_INSN (p);
1659     }
1660
1661   return output;
1662 }
1663 \f
1664 /* Return 1 if all uses of REG
1665    are between INSN and the end of the basic block.  */
1666
1667 static int
1668 reg_in_basic_block_p (rtx insn, rtx reg)
1669 {
1670   int regno = REGNO (reg);
1671   rtx p;
1672
1673   if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1674     return 0;
1675
1676   /* Search this basic block for the already recorded last use of the reg.  */
1677   for (p = insn; p; p = NEXT_INSN (p))
1678     {
1679       switch (GET_CODE (p))
1680         {
1681         case NOTE:
1682           break;
1683
1684         case INSN:
1685         case CALL_INSN:
1686           /* Ordinary insn: if this is the last use, we win.  */
1687           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1688             return 1;
1689           break;
1690
1691         case JUMP_INSN:
1692           /* Jump insn: if this is the last use, we win.  */
1693           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1694             return 1;
1695           /* Otherwise, it's the end of the basic block, so we lose.  */
1696           return 0;
1697
1698         case CODE_LABEL:
1699         case BARRIER:
1700           /* It's the end of the basic block, so we lose.  */
1701           return 0;
1702
1703         default:
1704           break;
1705         }
1706     }
1707
1708   /* The "last use" that was recorded can't be found after the first
1709      use.  This can happen when the last use was deleted while
1710      processing an inner loop, this inner loop was then completely
1711      unrolled, and the outer loop is always exited after the inner loop,
1712      so that everything after the first use becomes a single basic block.  */
1713   return 1;
1714 }
1715 \f
1716 /* Compute the benefit of eliminating the insns in the block whose
1717    last insn is LAST.  This may be a group of insns used to compute a
1718    value directly or can contain a library call.  */
1719
1720 static int
1721 libcall_benefit (rtx last)
1722 {
1723   rtx insn;
1724   int benefit = 0;
1725
1726   for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1727        insn != last; insn = NEXT_INSN (insn))
1728     {
1729       if (CALL_P (insn))
1730         benefit += 10;          /* Assume at least this many insns in a library
1731                                    routine.  */
1732       else if (NONJUMP_INSN_P (insn)
1733                && GET_CODE (PATTERN (insn)) != USE
1734                && GET_CODE (PATTERN (insn)) != CLOBBER)
1735         benefit++;
1736     }
1737
1738   return benefit;
1739 }
1740 \f
1741 /* Skip COUNT insns from INSN, counting library calls as 1 insn.  */
1742
1743 static rtx
1744 skip_consec_insns (rtx insn, int count)
1745 {
1746   for (; count > 0; count--)
1747     {
1748       rtx temp;
1749
1750       /* If first insn of libcall sequence, skip to end.  */
1751       /* Do this at start of loop, since INSN is guaranteed to
1752          be an insn here.  */
1753       if (!NOTE_P (insn)
1754           && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1755         insn = XEXP (temp, 0);
1756
1757       do
1758         insn = NEXT_INSN (insn);
1759       while (NOTE_P (insn));
1760     }
1761
1762   return insn;
1763 }
1764
1765 /* Ignore any movable whose insn falls within a libcall
1766    which is part of another movable.
1767    We make use of the fact that the movable for the libcall value
1768    was made later and so appears later on the chain.  */
1769
1770 static void
1771 ignore_some_movables (struct loop_movables *movables)
1772 {
1773   struct movable *m, *m1;
1774
1775   for (m = movables->head; m; m = m->next)
1776     {
1777       /* Is this a movable for the value of a libcall?  */
1778       rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1779       if (note)
1780         {
1781           rtx insn;
1782           /* Check for earlier movables inside that range,
1783              and mark them invalid.  We cannot use LUIDs here because
1784              insns created by loop.c for prior loops don't have LUIDs.
1785              Rather than reject all such insns from movables, we just
1786              explicitly check each insn in the libcall (since invariant
1787              libcalls aren't that common).  */
1788           for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1789             for (m1 = movables->head; m1 != m; m1 = m1->next)
1790               if (m1->insn == insn)
1791                 m1->done = 1;
1792         }
1793     }
1794 }
1795
1796 /* For each movable insn, see if the reg that it loads
1797    leads when it dies right into another conditionally movable insn.
1798    If so, record that the second insn "forces" the first one,
1799    since the second can be moved only if the first is.  */
1800
1801 static void
1802 force_movables (struct loop_movables *movables)
1803 {
1804   struct movable *m, *m1;
1805
1806   for (m1 = movables->head; m1; m1 = m1->next)
1807     /* Omit this if moving just the (SET (REG) 0) of a zero-extend.  */
1808     if (!m1->partial && !m1->done)
1809       {
1810         int regno = m1->regno;
1811         for (m = m1->next; m; m = m->next)
1812           /* ??? Could this be a bug?  What if CSE caused the
1813              register of M1 to be used after this insn?
1814              Since CSE does not update regno_last_uid,
1815              this insn M->insn might not be where it dies.
1816              But very likely this doesn't matter; what matters is
1817              that M's reg is computed from M1's reg.  */
1818           if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1819               && !m->done)
1820             break;
1821         if (m != 0 && m->set_src == m1->set_dest
1822             /* If m->consec, m->set_src isn't valid.  */
1823             && m->consec == 0)
1824           m = 0;
1825
1826         /* Increase the priority of the moving the first insn
1827            since it permits the second to be moved as well.
1828            Likewise for insns already forced by the first insn.  */
1829         if (m != 0)
1830           {
1831             struct movable *m2;
1832
1833             m->forces = m1;
1834             for (m2 = m1; m2; m2 = m2->forces)
1835               {
1836                 m2->lifetime += m->lifetime;
1837                 m2->savings += m->savings;
1838               }
1839           }
1840       }
1841 }
1842 \f
1843 /* Find invariant expressions that are equal and can be combined into
1844    one register.  */
1845
1846 static void
1847 combine_movables (struct loop_movables *movables, struct loop_regs *regs)
1848 {
1849   struct movable *m;
1850   char *matched_regs = xmalloc (regs->num);
1851   enum machine_mode mode;
1852
1853   /* Regs that are set more than once are not allowed to match
1854      or be matched.  I'm no longer sure why not.  */
1855   /* Only pseudo registers are allowed to match or be matched,
1856      since move_movables does not validate the change.  */
1857   /* Perhaps testing m->consec_sets would be more appropriate here?  */
1858
1859   for (m = movables->head; m; m = m->next)
1860     if (m->match == 0 && regs->array[m->regno].n_times_set == 1
1861         && m->regno >= FIRST_PSEUDO_REGISTER
1862         && !m->insert_temp
1863         && !m->partial)
1864       {
1865         struct movable *m1;
1866         int regno = m->regno;
1867
1868         memset (matched_regs, 0, regs->num);
1869         matched_regs[regno] = 1;
1870
1871         /* We want later insns to match the first one.  Don't make the first
1872            one match any later ones.  So start this loop at m->next.  */
1873         for (m1 = m->next; m1; m1 = m1->next)
1874           if (m != m1 && m1->match == 0
1875               && !m1->insert_temp
1876               && regs->array[m1->regno].n_times_set == 1
1877               && m1->regno >= FIRST_PSEUDO_REGISTER
1878               /* A reg used outside the loop mustn't be eliminated.  */
1879               && !m1->global
1880               /* A reg used for zero-extending mustn't be eliminated.  */
1881               && !m1->partial
1882               && (matched_regs[m1->regno]
1883                   ||
1884                   (
1885                    /* Can combine regs with different modes loaded from the
1886                       same constant only if the modes are the same or
1887                       if both are integer modes with M wider or the same
1888                       width as M1.  The check for integer is redundant, but
1889                       safe, since the only case of differing destination
1890                       modes with equal sources is when both sources are
1891                       VOIDmode, i.e., CONST_INT.  */
1892                    (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1893                     || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1894                         && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1895                         && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1896                             >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1897                    /* See if the source of M1 says it matches M.  */
1898                    && ((REG_P (m1->set_src)
1899                         && matched_regs[REGNO (m1->set_src)])
1900                        || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1901                                                 movables, regs))))
1902               && ((m->dependencies == m1->dependencies)
1903                   || rtx_equal_p (m->dependencies, m1->dependencies)))
1904             {
1905               m->lifetime += m1->lifetime;
1906               m->savings += m1->savings;
1907               m1->done = 1;
1908               m1->match = m;
1909               matched_regs[m1->regno] = 1;
1910             }
1911       }
1912
1913   /* Now combine the regs used for zero-extension.
1914      This can be done for those not marked `global'
1915      provided their lives don't overlap.  */
1916
1917   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1918        mode = GET_MODE_WIDER_MODE (mode))
1919     {
1920       struct movable *m0 = 0;
1921
1922       /* Combine all the registers for extension from mode MODE.
1923          Don't combine any that are used outside this loop.  */
1924       for (m = movables->head; m; m = m->next)
1925         if (m->partial && ! m->global
1926             && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1927           {
1928             struct movable *m1;
1929
1930             int first = REGNO_FIRST_LUID (m->regno);
1931             int last = REGNO_LAST_LUID (m->regno);
1932
1933             if (m0 == 0)
1934               {
1935                 /* First one: don't check for overlap, just record it.  */
1936                 m0 = m;
1937                 continue;
1938               }
1939
1940             /* Make sure they extend to the same mode.
1941                (Almost always true.)  */
1942             if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1943               continue;
1944
1945             /* We already have one: check for overlap with those
1946                already combined together.  */
1947             for (m1 = movables->head; m1 != m; m1 = m1->next)
1948               if (m1 == m0 || (m1->partial && m1->match == m0))
1949                 if (! (REGNO_FIRST_LUID (m1->regno) > last
1950                        || REGNO_LAST_LUID (m1->regno) < first))
1951                   goto overlap;
1952
1953             /* No overlap: we can combine this with the others.  */
1954             m0->lifetime += m->lifetime;
1955             m0->savings += m->savings;
1956             m->done = 1;
1957             m->match = m0;
1958
1959           overlap:
1960             ;
1961           }
1962     }
1963
1964   /* Clean up.  */
1965   free (matched_regs);
1966 }
1967
1968 /* Returns the number of movable instructions in LOOP that were not
1969    moved outside the loop.  */
1970
1971 static int
1972 num_unmoved_movables (const struct loop *loop)
1973 {
1974   int num = 0;
1975   struct movable *m;
1976
1977   for (m = LOOP_MOVABLES (loop)->head; m; m = m->next)
1978     if (!m->done)
1979       ++num;
1980
1981   return num;
1982 }
1983
1984 \f
1985 /* Return 1 if regs X and Y will become the same if moved.  */
1986
1987 static int
1988 regs_match_p (rtx x, rtx y, struct loop_movables *movables)
1989 {
1990   unsigned int xn = REGNO (x);
1991   unsigned int yn = REGNO (y);
1992   struct movable *mx, *my;
1993
1994   for (mx = movables->head; mx; mx = mx->next)
1995     if (mx->regno == xn)
1996       break;
1997
1998   for (my = movables->head; my; my = my->next)
1999     if (my->regno == yn)
2000       break;
2001
2002   return (mx && my
2003           && ((mx->match == my->match && mx->match != 0)
2004               || mx->match == my
2005               || mx == my->match));
2006 }
2007
2008 /* Return 1 if X and Y are identical-looking rtx's.
2009    This is the Lisp function EQUAL for rtx arguments.
2010
2011    If two registers are matching movables or a movable register and an
2012    equivalent constant, consider them equal.  */
2013
2014 static int
2015 rtx_equal_for_loop_p (rtx x, rtx y, struct loop_movables *movables,
2016                       struct loop_regs *regs)
2017 {
2018   int i;
2019   int j;
2020   struct movable *m;
2021   enum rtx_code code;
2022   const char *fmt;
2023
2024   if (x == y)
2025     return 1;
2026   if (x == 0 || y == 0)
2027     return 0;
2028
2029   code = GET_CODE (x);
2030
2031   /* If we have a register and a constant, they may sometimes be
2032      equal.  */
2033   if (REG_P (x) && regs->array[REGNO (x)].set_in_loop == -2
2034       && CONSTANT_P (y))
2035     {
2036       for (m = movables->head; m; m = m->next)
2037         if (m->move_insn && m->regno == REGNO (x)
2038             && rtx_equal_p (m->set_src, y))
2039           return 1;
2040     }
2041   else if (REG_P (y) && regs->array[REGNO (y)].set_in_loop == -2
2042            && CONSTANT_P (x))
2043     {
2044       for (m = movables->head; m; m = m->next)
2045         if (m->move_insn && m->regno == REGNO (y)
2046             && rtx_equal_p (m->set_src, x))
2047           return 1;
2048     }
2049
2050   /* Otherwise, rtx's of different codes cannot be equal.  */
2051   if (code != GET_CODE (y))
2052     return 0;
2053
2054   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
2055      (REG:SI x) and (REG:HI x) are NOT equivalent.  */
2056
2057   if (GET_MODE (x) != GET_MODE (y))
2058     return 0;
2059
2060   /* These three types of rtx's can be compared nonrecursively.  */
2061   if (code == REG)
2062     return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
2063
2064   if (code == LABEL_REF)
2065     return XEXP (x, 0) == XEXP (y, 0);
2066   if (code == SYMBOL_REF)
2067     return XSTR (x, 0) == XSTR (y, 0);
2068
2069   /* Compare the elements.  If any pair of corresponding elements
2070      fail to match, return 0 for the whole things.  */
2071
2072   fmt = GET_RTX_FORMAT (code);
2073   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2074     {
2075       switch (fmt[i])
2076         {
2077         case 'w':
2078           if (XWINT (x, i) != XWINT (y, i))
2079             return 0;
2080           break;
2081
2082         case 'i':
2083           if (XINT (x, i) != XINT (y, i))
2084             return 0;
2085           break;
2086
2087         case 'E':
2088           /* Two vectors must have the same length.  */
2089           if (XVECLEN (x, i) != XVECLEN (y, i))
2090             return 0;
2091
2092           /* And the corresponding elements must match.  */
2093           for (j = 0; j < XVECLEN (x, i); j++)
2094             if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j),
2095                                       movables, regs) == 0)
2096               return 0;
2097           break;
2098
2099         case 'e':
2100           if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables, regs)
2101               == 0)
2102             return 0;
2103           break;
2104
2105         case 's':
2106           if (strcmp (XSTR (x, i), XSTR (y, i)))
2107             return 0;
2108           break;
2109
2110         case 'u':
2111           /* These are just backpointers, so they don't matter.  */
2112           break;
2113
2114         case '0':
2115           break;
2116
2117           /* It is believed that rtx's at this level will never
2118              contain anything but integers and other rtx's,
2119              except for within LABEL_REFs and SYMBOL_REFs.  */
2120         default:
2121           gcc_unreachable ();
2122         }
2123     }
2124   return 1;
2125 }
2126 \f
2127 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
2128    insns in INSNS which use the reference.  LABEL_NUSES for CODE_LABEL
2129    references is incremented once for each added note.  */
2130
2131 static void
2132 add_label_notes (rtx x, rtx insns)
2133 {
2134   enum rtx_code code = GET_CODE (x);
2135   int i, j;
2136   const char *fmt;
2137   rtx insn;
2138
2139   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
2140     {
2141       /* This code used to ignore labels that referred to dispatch tables to
2142          avoid flow generating (slightly) worse code.
2143
2144          We no longer ignore such label references (see LABEL_REF handling in
2145          mark_jump_label for additional information).  */
2146       for (insn = insns; insn; insn = NEXT_INSN (insn))
2147         if (reg_mentioned_p (XEXP (x, 0), insn))
2148           {
2149             REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, XEXP (x, 0),
2150                                                   REG_NOTES (insn));
2151             if (LABEL_P (XEXP (x, 0)))
2152               LABEL_NUSES (XEXP (x, 0))++;
2153           }
2154     }
2155
2156   fmt = GET_RTX_FORMAT (code);
2157   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2158     {
2159       if (fmt[i] == 'e')
2160         add_label_notes (XEXP (x, i), insns);
2161       else if (fmt[i] == 'E')
2162         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
2163           add_label_notes (XVECEXP (x, i, j), insns);
2164     }
2165 }
2166 \f
2167 /* Scan MOVABLES, and move the insns that deserve to be moved.
2168    If two matching movables are combined, replace one reg with the
2169    other throughout.  */
2170
2171 static void
2172 move_movables (struct loop *loop, struct loop_movables *movables,
2173                int threshold, int insn_count)
2174 {
2175   struct loop_regs *regs = LOOP_REGS (loop);
2176   int nregs = regs->num;
2177   rtx new_start = 0;
2178   struct movable *m;
2179   rtx p;
2180   rtx loop_start = loop->start;
2181   rtx loop_end = loop->end;
2182   /* Map of pseudo-register replacements to handle combining
2183      when we move several insns that load the same value
2184      into different pseudo-registers.  */
2185   rtx *reg_map = xcalloc (nregs, sizeof (rtx));
2186   char *already_moved = xcalloc (nregs, sizeof (char));
2187
2188   for (m = movables->head; m; m = m->next)
2189     {
2190       /* Describe this movable insn.  */
2191
2192       if (loop_dump_stream)
2193         {
2194           fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
2195                    INSN_UID (m->insn), m->regno, m->lifetime);
2196           if (m->consec > 0)
2197             fprintf (loop_dump_stream, "consec %d, ", m->consec);
2198           if (m->cond)
2199             fprintf (loop_dump_stream, "cond ");
2200           if (m->force)
2201             fprintf (loop_dump_stream, "force ");
2202           if (m->global)
2203             fprintf (loop_dump_stream, "global ");
2204           if (m->done)
2205             fprintf (loop_dump_stream, "done ");
2206           if (m->move_insn)
2207             fprintf (loop_dump_stream, "move-insn ");
2208           if (m->match)
2209             fprintf (loop_dump_stream, "matches %d ",
2210                      INSN_UID (m->match->insn));
2211           if (m->forces)
2212             fprintf (loop_dump_stream, "forces %d ",
2213                      INSN_UID (m->forces->insn));
2214         }
2215
2216       /* Ignore the insn if it's already done (it matched something else).
2217          Otherwise, see if it is now safe to move.  */
2218
2219       if (!m->done
2220           && (! m->cond
2221               || (1 == loop_invariant_p (loop, m->set_src)
2222                   && (m->dependencies == 0
2223                       || 1 == loop_invariant_p (loop, m->dependencies))
2224                   && (m->consec == 0
2225                       || 1 == consec_sets_invariant_p (loop, m->set_dest,
2226                                                        m->consec + 1,
2227                                                        m->insn))))
2228           && (! m->forces || m->forces->done))
2229         {
2230           int regno;
2231           rtx p;
2232           int savings = m->savings;
2233
2234           /* We have an insn that is safe to move.
2235              Compute its desirability.  */
2236
2237           p = m->insn;
2238           regno = m->regno;
2239
2240           if (loop_dump_stream)
2241             fprintf (loop_dump_stream, "savings %d ", savings);
2242
2243           if (regs->array[regno].moved_once && loop_dump_stream)
2244             fprintf (loop_dump_stream, "halved since already moved ");
2245
2246           /* An insn MUST be moved if we already moved something else
2247              which is safe only if this one is moved too: that is,
2248              if already_moved[REGNO] is nonzero.  */
2249
2250           /* An insn is desirable to move if the new lifetime of the
2251              register is no more than THRESHOLD times the old lifetime.
2252              If it's not desirable, it means the loop is so big
2253              that moving won't speed things up much,
2254              and it is liable to make register usage worse.  */
2255
2256           /* It is also desirable to move if it can be moved at no
2257              extra cost because something else was already moved.  */
2258
2259           if (already_moved[regno]
2260               || (threshold * savings * m->lifetime) >=
2261                  (regs->array[regno].moved_once ? insn_count * 2 : insn_count)
2262               || (m->forces && m->forces->done
2263                   && regs->array[m->forces->regno].n_times_set == 1))
2264             {
2265               int count;
2266               struct movable *m1;
2267               rtx first = NULL_RTX;
2268               rtx newreg = NULL_RTX;
2269
2270               if (m->insert_temp)
2271                 newreg = gen_reg_rtx (GET_MODE (m->set_dest));
2272
2273               /* Now move the insns that set the reg.  */
2274
2275               if (m->partial && m->match)
2276                 {
2277                   rtx newpat, i1;
2278                   rtx r1, r2;
2279                   /* Find the end of this chain of matching regs.
2280                      Thus, we load each reg in the chain from that one reg.
2281                      And that reg is loaded with 0 directly,
2282                      since it has ->match == 0.  */
2283                   for (m1 = m; m1->match; m1 = m1->match);
2284                   newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
2285                                           SET_DEST (PATTERN (m1->insn)));
2286                   i1 = loop_insn_hoist (loop, newpat);
2287
2288                   /* Mark the moved, invariant reg as being allowed to
2289                      share a hard reg with the other matching invariant.  */
2290                   REG_NOTES (i1) = REG_NOTES (m->insn);
2291                   r1 = SET_DEST (PATTERN (m->insn));
2292                   r2 = SET_DEST (PATTERN (m1->insn));
2293                   regs_may_share
2294                     = gen_rtx_EXPR_LIST (VOIDmode, r1,
2295                                          gen_rtx_EXPR_LIST (VOIDmode, r2,
2296                                                             regs_may_share));
2297                   delete_insn (m->insn);
2298
2299                   if (new_start == 0)
2300                     new_start = i1;
2301
2302                   if (loop_dump_stream)
2303                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
2304                 }
2305               /* If we are to re-generate the item being moved with a
2306                  new move insn, first delete what we have and then emit
2307                  the move insn before the loop.  */
2308               else if (m->move_insn)
2309                 {
2310                   rtx i1, temp, seq;
2311
2312                   for (count = m->consec; count >= 0; count--)
2313                     {
2314                       if (!NOTE_P (p))
2315                         {
2316                           /* If this is the first insn of a library
2317                              call sequence, something is very
2318                              wrong.  */
2319                           gcc_assert (!find_reg_note
2320                                       (p, REG_LIBCALL, NULL_RTX));
2321
2322                           /* If this is the last insn of a libcall
2323                              sequence, then delete every insn in the
2324                              sequence except the last.  The last insn
2325                              is handled in the normal manner.  */
2326                           temp = find_reg_note (p, REG_RETVAL, NULL_RTX);
2327                           
2328                           if (temp)
2329                             {
2330                               temp = XEXP (temp, 0);
2331                               while (temp != p)
2332                                 temp = delete_insn (temp);
2333                             }
2334                         }
2335
2336                       temp = p;
2337                       p = delete_insn (p);
2338
2339                       /* simplify_giv_expr expects that it can walk the insns
2340                          at m->insn forwards and see this old sequence we are
2341                          tossing here.  delete_insn does preserve the next
2342                          pointers, but when we skip over a NOTE we must fix
2343                          it up.  Otherwise that code walks into the non-deleted
2344                          insn stream.  */
2345                       while (p && NOTE_P (p))
2346                         p = NEXT_INSN (temp) = NEXT_INSN (p);
2347
2348                       if (m->insert_temp)
2349                         {
2350                           /* Replace the original insn with a move from
2351                              our newly created temp.  */
2352                           start_sequence ();
2353                           emit_move_insn (m->set_dest, newreg);
2354                           seq = get_insns ();
2355                           end_sequence ();
2356                           emit_insn_before (seq, p);
2357                         }
2358                     }
2359
2360                   start_sequence ();
2361                   emit_move_insn (m->insert_temp ? newreg : m->set_dest,
2362                                   m->set_src);
2363                   seq = get_insns ();
2364                   end_sequence ();
2365
2366                   add_label_notes (m->set_src, seq);
2367
2368                   i1 = loop_insn_hoist (loop, seq);
2369                   if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2370                     set_unique_reg_note (i1,
2371                                          m->is_equiv ? REG_EQUIV : REG_EQUAL,
2372                                          m->set_src);
2373
2374                   if (loop_dump_stream)
2375                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
2376
2377                   /* The more regs we move, the less we like moving them.  */
2378                   threshold -= 3;
2379                 }
2380               else
2381                 {
2382                   for (count = m->consec; count >= 0; count--)
2383                     {
2384                       rtx i1, temp;
2385
2386                       /* If first insn of libcall sequence, skip to end.  */
2387                       /* Do this at start of loop, since p is guaranteed to
2388                          be an insn here.  */
2389                       if (!NOTE_P (p)
2390                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2391                         p = XEXP (temp, 0);
2392
2393                       /* If last insn of libcall sequence, move all
2394                          insns except the last before the loop.  The last
2395                          insn is handled in the normal manner.  */
2396                       if (!NOTE_P (p)
2397                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
2398                         {
2399                           rtx fn_address = 0;
2400                           rtx fn_reg = 0;
2401                           rtx fn_address_insn = 0;
2402
2403                           first = 0;
2404                           for (temp = XEXP (temp, 0); temp != p;
2405                                temp = NEXT_INSN (temp))
2406                             {
2407                               rtx body;
2408                               rtx n;
2409                               rtx next;
2410
2411                               if (NOTE_P (temp))
2412                                 continue;
2413
2414                               body = PATTERN (temp);
2415
2416                               /* Find the next insn after TEMP,
2417                                  not counting USE or NOTE insns.  */
2418                               for (next = NEXT_INSN (temp); next != p;
2419                                    next = NEXT_INSN (next))
2420                                 if (! (NONJUMP_INSN_P (next)
2421                                        && GET_CODE (PATTERN (next)) == USE)
2422                                     && !NOTE_P (next))
2423                                   break;
2424
2425                               /* If that is the call, this may be the insn
2426                                  that loads the function address.
2427
2428                                  Extract the function address from the insn
2429                                  that loads it into a register.
2430                                  If this insn was cse'd, we get incorrect code.
2431
2432                                  So emit a new move insn that copies the
2433                                  function address into the register that the
2434                                  call insn will use.  flow.c will delete any
2435                                  redundant stores that we have created.  */
2436                               if (CALL_P (next)
2437                                   && GET_CODE (body) == SET
2438                                   && REG_P (SET_DEST (body))
2439                                   && (n = find_reg_note (temp, REG_EQUAL,
2440                                                          NULL_RTX)))
2441                                 {
2442                                   fn_reg = SET_SRC (body);
2443                                   if (!REG_P (fn_reg))
2444                                     fn_reg = SET_DEST (body);
2445                                   fn_address = XEXP (n, 0);
2446                                   fn_address_insn = temp;
2447                                 }
2448                               /* We have the call insn.
2449                                  If it uses the register we suspect it might,
2450                                  load it with the correct address directly.  */
2451                               if (CALL_P (temp)
2452                                   && fn_address != 0
2453                                   && reg_referenced_p (fn_reg, body))
2454                                 loop_insn_emit_after (loop, 0, fn_address_insn,
2455                                                       gen_move_insn
2456                                                       (fn_reg, fn_address));
2457
2458                               if (CALL_P (temp))
2459                                 {
2460                                   i1 = loop_call_insn_hoist (loop, body);
2461                                   /* Because the USAGE information potentially
2462                                      contains objects other than hard registers
2463                                      we need to copy it.  */
2464                                   if (CALL_INSN_FUNCTION_USAGE (temp))
2465                                     CALL_INSN_FUNCTION_USAGE (i1)
2466                                       = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2467                                 }
2468                               else
2469                                 i1 = loop_insn_hoist (loop, body);
2470                               if (first == 0)
2471                                 first = i1;
2472                               if (temp == fn_address_insn)
2473                                 fn_address_insn = i1;
2474                               REG_NOTES (i1) = REG_NOTES (temp);
2475                               REG_NOTES (temp) = NULL;
2476                               delete_insn (temp);
2477                             }
2478                           if (new_start == 0)
2479                             new_start = first;
2480                         }
2481                       if (m->savemode != VOIDmode)
2482                         {
2483                           /* P sets REG to zero; but we should clear only
2484                              the bits that are not covered by the mode
2485                              m->savemode.  */
2486                           rtx reg = m->set_dest;
2487                           rtx sequence;
2488                           rtx tem;
2489
2490                           start_sequence ();
2491                           tem = expand_simple_binop
2492                             (GET_MODE (reg), AND, reg,
2493                              GEN_INT ((((HOST_WIDE_INT) 1
2494                                         << GET_MODE_BITSIZE (m->savemode)))
2495                                       - 1),
2496                              reg, 1, OPTAB_LIB_WIDEN);
2497                           gcc_assert (tem);
2498                           if (tem != reg)
2499                             emit_move_insn (reg, tem);
2500                           sequence = get_insns ();
2501                           end_sequence ();
2502                           i1 = loop_insn_hoist (loop, sequence);
2503                         }
2504                       else if (CALL_P (p))
2505                         {
2506                           i1 = loop_call_insn_hoist (loop, PATTERN (p));
2507                           /* Because the USAGE information potentially
2508                              contains objects other than hard registers
2509                              we need to copy it.  */
2510                           if (CALL_INSN_FUNCTION_USAGE (p))
2511                             CALL_INSN_FUNCTION_USAGE (i1)
2512                               = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2513                         }
2514                       else if (count == m->consec && m->move_insn_first)
2515                         {
2516                           rtx seq;
2517                           /* The SET_SRC might not be invariant, so we must
2518                              use the REG_EQUAL note.  */
2519                           start_sequence ();
2520                           emit_move_insn (m->insert_temp ? newreg : m->set_dest,
2521                                           m->set_src);
2522                           seq = get_insns ();
2523                           end_sequence ();
2524
2525                           add_label_notes (m->set_src, seq);
2526
2527                           i1 = loop_insn_hoist (loop, seq);
2528                           if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2529                             set_unique_reg_note (i1, m->is_equiv ? REG_EQUIV
2530                                                      : REG_EQUAL, m->set_src);
2531                         }
2532                       else if (m->insert_temp)
2533                         {
2534                           rtx *reg_map2 = xcalloc (REGNO (newreg),
2535                                                    sizeof(rtx));
2536                           reg_map2 [m->regno] = newreg;
2537
2538                           i1 = loop_insn_hoist (loop, copy_rtx (PATTERN (p)));
2539                           replace_regs (i1, reg_map2, REGNO (newreg), 1);
2540                           free (reg_map2);
2541                         }
2542                       else
2543                         i1 = loop_insn_hoist (loop, PATTERN (p));
2544
2545                       if (REG_NOTES (i1) == 0)
2546                         {
2547                           REG_NOTES (i1) = REG_NOTES (p);
2548                           REG_NOTES (p) = NULL;
2549
2550                           /* If there is a REG_EQUAL note present whose value
2551                              is not loop invariant, then delete it, since it
2552                              may cause problems with later optimization passes.
2553                              It is possible for cse to create such notes
2554                              like this as a result of record_jump_cond.  */
2555
2556                           if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2557                               && ! loop_invariant_p (loop, XEXP (temp, 0)))
2558                             remove_note (i1, temp);
2559                         }
2560
2561                       if (new_start == 0)
2562                         new_start = i1;
2563
2564                       if (loop_dump_stream)
2565                         fprintf (loop_dump_stream, " moved to %d",
2566                                  INSN_UID (i1));
2567
2568                       /* If library call, now fix the REG_NOTES that contain
2569                          insn pointers, namely REG_LIBCALL on FIRST
2570                          and REG_RETVAL on I1.  */
2571                       if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2572                         {
2573                           XEXP (temp, 0) = first;
2574                           temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2575                           XEXP (temp, 0) = i1;
2576                         }
2577
2578                       temp = p;
2579                       delete_insn (p);
2580                       p = NEXT_INSN (p);
2581
2582                       /* simplify_giv_expr expects that it can walk the insns
2583                          at m->insn forwards and see this old sequence we are
2584                          tossing here.  delete_insn does preserve the next
2585                          pointers, but when we skip over a NOTE we must fix
2586                          it up.  Otherwise that code walks into the non-deleted
2587                          insn stream.  */
2588                       while (p && NOTE_P (p))
2589                         p = NEXT_INSN (temp) = NEXT_INSN (p);
2590
2591                       if (m->insert_temp)
2592                         {
2593                           rtx seq;
2594                           /* Replace the original insn with a move from
2595                              our newly created temp.  */
2596                           start_sequence ();
2597                           emit_move_insn (m->set_dest, newreg);
2598                           seq = get_insns ();
2599                           end_sequence ();
2600                           emit_insn_before (seq, p);
2601                         }
2602                     }
2603
2604                   /* The more regs we move, the less we like moving them.  */
2605                   threshold -= 3;
2606                 }
2607
2608               m->done = 1;
2609
2610               if (!m->insert_temp)
2611                 {
2612                   /* Any other movable that loads the same register
2613                      MUST be moved.  */
2614                   already_moved[regno] = 1;
2615
2616                   /* This reg has been moved out of one loop.  */
2617                   regs->array[regno].moved_once = 1;
2618
2619                   /* The reg set here is now invariant.  */
2620                   if (! m->partial)
2621                     {
2622                       int i;
2623                       for (i = 0; i < LOOP_REGNO_NREGS (regno, m->set_dest); i++)
2624                         regs->array[regno+i].set_in_loop = 0;
2625                     }
2626
2627                   /* Change the length-of-life info for the register
2628                      to say it lives at least the full length of this loop.
2629                      This will help guide optimizations in outer loops.  */
2630
2631                   if (REGNO_FIRST_LUID (regno) > INSN_LUID (loop_start))
2632                     /* This is the old insn before all the moved insns.
2633                        We can't use the moved insn because it is out of range
2634                        in uid_luid.  Only the old insns have luids.  */
2635                     REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2636                   if (REGNO_LAST_LUID (regno) < INSN_LUID (loop_end))
2637                     REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2638                 }
2639
2640               /* Combine with this moved insn any other matching movables.  */
2641
2642               if (! m->partial)
2643                 for (m1 = movables->head; m1; m1 = m1->next)
2644                   if (m1->match == m)
2645                     {
2646                       rtx temp;
2647
2648                       /* Schedule the reg loaded by M1
2649                          for replacement so that shares the reg of M.
2650                          If the modes differ (only possible in restricted
2651                          circumstances, make a SUBREG.
2652
2653                          Note this assumes that the target dependent files
2654                          treat REG and SUBREG equally, including within
2655                          GO_IF_LEGITIMATE_ADDRESS and in all the
2656                          predicates since we never verify that replacing the
2657                          original register with a SUBREG results in a
2658                          recognizable insn.  */
2659                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2660                         reg_map[m1->regno] = m->set_dest;
2661                       else
2662                         reg_map[m1->regno]
2663                           = gen_lowpart_common (GET_MODE (m1->set_dest),
2664                                                 m->set_dest);
2665
2666                       /* Get rid of the matching insn
2667                          and prevent further processing of it.  */
2668                       m1->done = 1;
2669
2670                       /* If library call, delete all insns.  */
2671                       if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2672                                                  NULL_RTX)))
2673                         delete_insn_chain (XEXP (temp, 0), m1->insn);
2674                       else
2675                         delete_insn (m1->insn);
2676
2677                       /* Any other movable that loads the same register
2678                          MUST be moved.  */
2679                       already_moved[m1->regno] = 1;
2680
2681                       /* The reg merged here is now invariant,
2682                          if the reg it matches is invariant.  */
2683                       if (! m->partial)
2684                         {
2685                           int i;
2686                           for (i = 0;
2687                                i < LOOP_REGNO_NREGS (regno, m1->set_dest);
2688                                i++)
2689                             regs->array[m1->regno+i].set_in_loop = 0;
2690                         }
2691                     }
2692             }
2693           else if (loop_dump_stream)
2694             fprintf (loop_dump_stream, "not desirable");
2695         }
2696       else if (loop_dump_stream && !m->match)
2697         fprintf (loop_dump_stream, "not safe");
2698
2699       if (loop_dump_stream)
2700         fprintf (loop_dump_stream, "\n");
2701     }
2702
2703   if (new_start == 0)
2704     new_start = loop_start;
2705
2706   /* Go through all the instructions in the loop, making
2707      all the register substitutions scheduled in REG_MAP.  */
2708   for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2709     if (INSN_P (p))
2710       {
2711         replace_regs (PATTERN (p), reg_map, nregs, 0);
2712         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2713         INSN_CODE (p) = -1;
2714       }
2715
2716   /* Clean up.  */
2717   free (reg_map);
2718   free (already_moved);
2719 }
2720
2721
2722 static void
2723 loop_movables_add (struct loop_movables *movables, struct movable *m)
2724 {
2725   if (movables->head == 0)
2726     movables->head = m;
2727   else
2728     movables->last->next = m;
2729   movables->last = m;
2730 }
2731
2732
2733 static void
2734 loop_movables_free (struct loop_movables *movables)
2735 {
2736   struct movable *m;
2737   struct movable *m_next;
2738
2739   for (m = movables->head; m; m = m_next)
2740     {
2741       m_next = m->next;
2742       free (m);
2743     }
2744 }
2745 \f
2746 #if 0
2747 /* Scan X and replace the address of any MEM in it with ADDR.
2748    REG is the address that MEM should have before the replacement.  */
2749
2750 static void
2751 replace_call_address (rtx x, rtx reg, rtx addr)
2752 {
2753   enum rtx_code code;
2754   int i;
2755   const char *fmt;
2756
2757   if (x == 0)
2758     return;
2759   code = GET_CODE (x);
2760   switch (code)
2761     {
2762     case PC:
2763     case CC0:
2764     case CONST_INT:
2765     case CONST_DOUBLE:
2766     case CONST:
2767     case SYMBOL_REF:
2768     case LABEL_REF:
2769     case REG:
2770       return;
2771
2772     case SET:
2773       /* Short cut for very common case.  */
2774       replace_call_address (XEXP (x, 1), reg, addr);
2775       return;
2776
2777     case CALL:
2778       /* Short cut for very common case.  */
2779       replace_call_address (XEXP (x, 0), reg, addr);
2780       return;
2781
2782     case MEM:
2783       /* If this MEM uses a reg other than the one we expected,
2784          something is wrong.  */
2785       gcc_assert (XEXP (x, 0) == reg);
2786       XEXP (x, 0) = addr;
2787       return;
2788
2789     default:
2790       break;
2791     }
2792
2793   fmt = GET_RTX_FORMAT (code);
2794   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2795     {
2796       if (fmt[i] == 'e')
2797         replace_call_address (XEXP (x, i), reg, addr);
2798       else if (fmt[i] == 'E')
2799         {
2800           int j;
2801           for (j = 0; j < XVECLEN (x, i); j++)
2802             replace_call_address (XVECEXP (x, i, j), reg, addr);
2803         }
2804     }
2805 }
2806 #endif
2807 \f
2808 /* Return the number of memory refs to addresses that vary
2809    in the rtx X.  */
2810
2811 static int
2812 count_nonfixed_reads (const struct loop *loop, rtx x)
2813 {
2814   enum rtx_code code;
2815   int i;
2816   const char *fmt;
2817   int value;
2818
2819   if (x == 0)
2820     return 0;
2821
2822   code = GET_CODE (x);
2823   switch (code)
2824     {
2825     case PC:
2826     case CC0:
2827     case CONST_INT:
2828     case CONST_DOUBLE:
2829     case CONST:
2830     case SYMBOL_REF:
2831     case LABEL_REF:
2832     case REG:
2833       return 0;
2834
2835     case MEM:
2836       return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2837               + count_nonfixed_reads (loop, XEXP (x, 0)));
2838
2839     default:
2840       break;
2841     }
2842
2843   value = 0;
2844   fmt = GET_RTX_FORMAT (code);
2845   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2846     {
2847       if (fmt[i] == 'e')
2848         value += count_nonfixed_reads (loop, XEXP (x, i));
2849       if (fmt[i] == 'E')
2850         {
2851           int j;
2852           for (j = 0; j < XVECLEN (x, i); j++)
2853             value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2854         }
2855     }
2856   return value;
2857 }
2858 \f
2859 /* Scan a loop setting the elements `loops_enclosed',
2860    `has_call', `has_nonconst_call', `has_volatile', `has_tablejump',
2861    `unknown_address_altered', `unknown_constant_address_altered', and
2862    `num_mem_sets' in LOOP.  Also, fill in the array `mems' and the
2863    list `store_mems' in LOOP.  */
2864
2865 static void
2866 prescan_loop (struct loop *loop)
2867 {
2868   int level = 1;
2869   rtx insn;
2870   struct loop_info *loop_info = LOOP_INFO (loop);
2871   rtx start = loop->start;
2872   rtx end = loop->end;
2873   /* The label after END.  Jumping here is just like falling off the
2874      end of the loop.  We use next_nonnote_insn instead of next_label
2875      as a hedge against the (pathological) case where some actual insn
2876      might end up between the two.  */
2877   rtx exit_target = next_nonnote_insn (end);
2878
2879   loop_info->has_indirect_jump = indirect_jump_in_function;
2880   loop_info->pre_header_has_call = 0;
2881   loop_info->has_call = 0;
2882   loop_info->has_nonconst_call = 0;
2883   loop_info->has_prefetch = 0;
2884   loop_info->has_volatile = 0;
2885   loop_info->has_tablejump = 0;
2886   loop_info->has_multiple_exit_targets = 0;
2887   loop->level = 1;
2888
2889   loop_info->unknown_address_altered = 0;
2890   loop_info->unknown_constant_address_altered = 0;
2891   loop_info->store_mems = NULL_RTX;
2892   loop_info->first_loop_store_insn = NULL_RTX;
2893   loop_info->mems_idx = 0;
2894   loop_info->num_mem_sets = 0;
2895
2896   for (insn = start; insn && !LABEL_P (insn);
2897        insn = PREV_INSN (insn))
2898     {
2899       if (CALL_P (insn))
2900         {
2901           loop_info->pre_header_has_call = 1;
2902           break;
2903         }
2904     }
2905
2906   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2907        insn = NEXT_INSN (insn))
2908     {
2909       switch (GET_CODE (insn))
2910         {
2911         case NOTE:
2912           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2913             {
2914               ++level;
2915               /* Count number of loops contained in this one.  */
2916               loop->level++;
2917             }
2918           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2919             --level;
2920           break;
2921
2922         case CALL_INSN:
2923           if (! CONST_OR_PURE_CALL_P (insn))
2924             {
2925               loop_info->unknown_address_altered = 1;
2926               loop_info->has_nonconst_call = 1;
2927             }
2928           else if (pure_call_p (insn))
2929             loop_info->has_nonconst_call = 1;
2930           loop_info->has_call = 1;
2931           if (can_throw_internal (insn))
2932             loop_info->has_multiple_exit_targets = 1;
2933           break;
2934
2935         case JUMP_INSN:
2936           if (! loop_info->has_multiple_exit_targets)
2937             {
2938               rtx set = pc_set (insn);
2939
2940               if (set)
2941                 {
2942                   rtx src = SET_SRC (set);
2943                   rtx label1, label2;
2944
2945                   if (GET_CODE (src) == IF_THEN_ELSE)
2946                     {
2947                       label1 = XEXP (src, 1);
2948                       label2 = XEXP (src, 2);
2949                     }
2950                   else
2951                     {
2952                       label1 = src;
2953                       label2 = NULL_RTX;
2954                     }
2955
2956                   do
2957                     {
2958                       if (label1 && label1 != pc_rtx)
2959                         {
2960                           if (GET_CODE (label1) != LABEL_REF)
2961                             {
2962                               /* Something tricky.  */
2963                               loop_info->has_multiple_exit_targets = 1;
2964                               break;
2965                             }
2966                           else if (XEXP (label1, 0) != exit_target
2967                                    && LABEL_OUTSIDE_LOOP_P (label1))
2968                             {
2969                               /* A jump outside the current loop.  */
2970                               loop_info->has_multiple_exit_targets = 1;
2971                               break;
2972                             }
2973                         }
2974
2975                       label1 = label2;
2976                       label2 = NULL_RTX;
2977                     }
2978                   while (label1);
2979                 }
2980               else
2981                 {
2982                   /* A return, or something tricky.  */
2983                   loop_info->has_multiple_exit_targets = 1;
2984                 }
2985             }
2986           /* Fall through.  */
2987
2988         case INSN:
2989           if (volatile_refs_p (PATTERN (insn)))
2990             loop_info->has_volatile = 1;
2991
2992           if (JUMP_P (insn)
2993               && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2994                   || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2995             loop_info->has_tablejump = 1;
2996
2997           note_stores (PATTERN (insn), note_addr_stored, loop_info);
2998           if (! loop_info->first_loop_store_insn && loop_info->store_mems)
2999             loop_info->first_loop_store_insn = insn;
3000
3001           if (flag_non_call_exceptions && can_throw_internal (insn))
3002             loop_info->has_multiple_exit_targets = 1;
3003           break;
3004
3005         default:
3006           break;
3007         }
3008     }
3009
3010   /* Now, rescan the loop, setting up the LOOP_MEMS array.  */
3011   if (/* An exception thrown by a called function might land us
3012          anywhere.  */
3013       ! loop_info->has_nonconst_call
3014       /* We don't want loads for MEMs moved to a location before the
3015          one at which their stack memory becomes allocated.  (Note
3016          that this is not a problem for malloc, etc., since those
3017          require actual function calls.  */
3018       && ! current_function_calls_alloca
3019       /* There are ways to leave the loop other than falling off the
3020          end.  */
3021       && ! loop_info->has_multiple_exit_targets)
3022     for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
3023          insn = NEXT_INSN (insn))
3024       for_each_rtx (&insn, insert_loop_mem, loop_info);
3025
3026   /* BLKmode MEMs are added to LOOP_STORE_MEM as necessary so
3027      that loop_invariant_p and load_mems can use true_dependence
3028      to determine what is really clobbered.  */
3029   if (loop_info->unknown_address_altered)
3030     {
3031       rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
3032
3033       loop_info->store_mems
3034         = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
3035     }
3036   if (loop_info->unknown_constant_address_altered)
3037     {
3038       rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
3039       MEM_READONLY_P (mem) = 1;
3040       loop_info->store_mems
3041         = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
3042     }
3043 }
3044 \f
3045 /* Invalidate all loops containing LABEL.  */
3046
3047 static void
3048 invalidate_loops_containing_label (rtx label)
3049 {
3050   struct loop *loop;
3051   for (loop = uid_loop[INSN_UID (label)]; loop; loop = loop->outer)
3052     loop->invalid = 1;
3053 }
3054
3055 /* Scan the function looking for loops.  Record the start and end of each loop.
3056    Also mark as invalid loops any loops that contain a setjmp or are branched
3057    to from outside the loop.  */
3058
3059 static void
3060 find_and_verify_loops (rtx f, struct loops *loops)
3061 {
3062   rtx insn;
3063   rtx label;
3064   int num_loops;
3065   struct loop *current_loop;
3066   struct loop *next_loop;
3067   struct loop *loop;
3068
3069   num_loops = loops->num;
3070
3071   compute_luids (f, NULL_RTX, 0);
3072
3073   /* If there are jumps to undefined labels,
3074      treat them as jumps out of any/all loops.
3075      This also avoids writing past end of tables when there are no loops.  */
3076   uid_loop[0] = NULL;
3077
3078   /* Find boundaries of loops, mark which loops are contained within
3079      loops, and invalidate loops that have setjmp.  */
3080
3081   num_loops = 0;
3082   current_loop = NULL;
3083   for (insn = f; insn; insn = NEXT_INSN (insn))
3084     {
3085       if (NOTE_P (insn))
3086         switch (NOTE_LINE_NUMBER (insn))
3087           {
3088           case NOTE_INSN_LOOP_BEG:
3089             next_loop = loops->array + num_loops;
3090             next_loop->num = num_loops;
3091             num_loops++;
3092             next_loop->start = insn;
3093             next_loop->outer = current_loop;
3094             current_loop = next_loop;
3095             break;
3096
3097           case NOTE_INSN_LOOP_END:
3098             gcc_assert (current_loop);
3099
3100             current_loop->end = insn;
3101             current_loop = current_loop->outer;
3102             break;
3103
3104           default:
3105             break;
3106           }
3107
3108       if (CALL_P (insn)
3109           && find_reg_note (insn, REG_SETJMP, NULL))
3110         {
3111           /* In this case, we must invalidate our current loop and any
3112              enclosing loop.  */
3113           for (loop = current_loop; loop; loop = loop->outer)
3114             {
3115               loop->invalid = 1;
3116               if (loop_dump_stream)
3117                 fprintf (loop_dump_stream,
3118                          "\nLoop at %d ignored due to setjmp.\n",
3119                          INSN_UID (loop->start));
3120             }
3121         }
3122
3123       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
3124          enclosing loop, but this doesn't matter.  */
3125       uid_loop[INSN_UID (insn)] = current_loop;
3126     }
3127
3128   /* Any loop containing a label used in an initializer must be invalidated,
3129      because it can be jumped into from anywhere.  */
3130   for (label = forced_labels; label; label = XEXP (label, 1))
3131     invalidate_loops_containing_label (XEXP (label, 0));
3132
3133   /* Any loop containing a label used for an exception handler must be
3134      invalidated, because it can be jumped into from anywhere.  */
3135   for_each_eh_label (invalidate_loops_containing_label);
3136
3137   /* Now scan all insn's in the function.  If any JUMP_INSN branches into a
3138      loop that it is not contained within, that loop is marked invalid.
3139      If any INSN or CALL_INSN uses a label's address, then the loop containing
3140      that label is marked invalid, because it could be jumped into from
3141      anywhere.
3142
3143      Also look for blocks of code ending in an unconditional branch that
3144      exits the loop.  If such a block is surrounded by a conditional
3145      branch around the block, move the block elsewhere (see below) and
3146      invert the jump to point to the code block.  This may eliminate a
3147      label in our loop and will simplify processing by both us and a
3148      possible second cse pass.  */
3149
3150   for (insn = f; insn; insn = NEXT_INSN (insn))
3151     if (INSN_P (insn))
3152       {
3153         struct loop *this_loop = uid_loop[INSN_UID (insn)];
3154
3155         if (NONJUMP_INSN_P (insn) || CALL_P (insn))
3156           {
3157             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
3158             if (note)
3159               invalidate_loops_containing_label (XEXP (note, 0));
3160           }
3161
3162         if (!JUMP_P (insn))
3163           continue;
3164
3165         mark_loop_jump (PATTERN (insn), this_loop);
3166
3167         /* See if this is an unconditional branch outside the loop.  */
3168         if (this_loop
3169             && (GET_CODE (PATTERN (insn)) == RETURN
3170                 || (any_uncondjump_p (insn)
3171                     && onlyjump_p (insn)
3172                     && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
3173                         != this_loop)))
3174             && get_max_uid () < max_uid_for_loop)
3175           {
3176             rtx p;
3177             rtx our_next = next_real_insn (insn);
3178             rtx last_insn_to_move = NEXT_INSN (insn);
3179             struct loop *dest_loop;
3180             struct loop *outer_loop = NULL;
3181
3182             /* Go backwards until we reach the start of the loop, a label,
3183                or a JUMP_INSN.  */
3184             for (p = PREV_INSN (insn);
3185                  !LABEL_P (p)
3186                  && ! (NOTE_P (p)
3187                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3188                  && !JUMP_P (p);
3189                  p = PREV_INSN (p))
3190               ;
3191
3192             /* Check for the case where we have a jump to an inner nested
3193                loop, and do not perform the optimization in that case.  */
3194
3195             if (JUMP_LABEL (insn))
3196               {
3197                 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
3198                 if (dest_loop)
3199                   {
3200                     for (outer_loop = dest_loop; outer_loop;
3201                          outer_loop = outer_loop->outer)
3202                       if (outer_loop == this_loop)
3203                         break;
3204                   }
3205               }
3206
3207             /* Make sure that the target of P is within the current loop.  */
3208
3209             if (JUMP_P (p) && JUMP_LABEL (p)
3210                 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
3211               outer_loop = this_loop;
3212
3213             /* If we stopped on a JUMP_INSN to the next insn after INSN,
3214                we have a block of code to try to move.
3215
3216                We look backward and then forward from the target of INSN
3217                to find a BARRIER at the same loop depth as the target.
3218                If we find such a BARRIER, we make a new label for the start
3219                of the block, invert the jump in P and point it to that label,
3220                and move the block of code to the spot we found.  */
3221
3222             if (! outer_loop
3223                 && JUMP_P (p)
3224                 && JUMP_LABEL (p) != 0
3225                 /* Just ignore jumps to labels that were never emitted.
3226                    These always indicate compilation errors.  */
3227                 && INSN_UID (JUMP_LABEL (p)) != 0
3228                 && any_condjump_p (p) && onlyjump_p (p)
3229                 && next_real_insn (JUMP_LABEL (p)) == our_next
3230                 /* If it's not safe to move the sequence, then we
3231                    mustn't try.  */
3232                 && insns_safe_to_move_p (p, NEXT_INSN (insn),
3233                                          &last_insn_to_move))
3234               {
3235                 rtx target
3236                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
3237                 struct loop *target_loop = uid_loop[INSN_UID (target)];
3238                 rtx loc, loc2;
3239                 rtx tmp;
3240
3241                 /* Search for possible garbage past the conditional jumps
3242                    and look for the last barrier.  */
3243                 for (tmp = last_insn_to_move;
3244                      tmp && !LABEL_P (tmp); tmp = NEXT_INSN (tmp))
3245                   if (BARRIER_P (tmp))
3246                     last_insn_to_move = tmp;
3247
3248                 for (loc = target; loc; loc = PREV_INSN (loc))
3249                   if (BARRIER_P (loc)
3250                       /* Don't move things inside a tablejump.  */
3251                       && ((loc2 = next_nonnote_insn (loc)) == 0
3252                           || !LABEL_P (loc2)
3253                           || (loc2 = next_nonnote_insn (loc2)) == 0
3254                           || !JUMP_P (loc2)
3255                           || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
3256                               && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
3257                       && uid_loop[INSN_UID (loc)] == target_loop)
3258                     break;
3259
3260                 if (loc == 0)
3261                   for (loc = target; loc; loc = NEXT_INSN (loc))
3262                     if (BARRIER_P (loc)
3263                         /* Don't move things inside a tablejump.  */
3264                         && ((loc2 = next_nonnote_insn (loc)) == 0
3265                             || !LABEL_P (loc2)
3266                             || (loc2 = next_nonnote_insn (loc2)) == 0
3267                             || !JUMP_P (loc2)
3268                             || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
3269                                 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
3270                         && uid_loop[INSN_UID (loc)] == target_loop)
3271                       break;
3272
3273                 if (loc)
3274                   {
3275                     rtx cond_label = JUMP_LABEL (p);
3276                     rtx new_label = get_label_after (p);
3277
3278                     /* Ensure our label doesn't go away.  */
3279                     LABEL_NUSES (cond_label)++;
3280
3281                     /* Verify that uid_loop is large enough and that
3282                        we can invert P.  */
3283                     if (invert_jump (p, new_label, 1))
3284                       {
3285                         rtx q, r;
3286                         bool only_notes;
3287
3288                         /* If no suitable BARRIER was found, create a suitable
3289                            one before TARGET.  Since TARGET is a fall through
3290                            path, we'll need to insert a jump around our block
3291                            and add a BARRIER before TARGET.
3292
3293                            This creates an extra unconditional jump outside
3294                            the loop.  However, the benefits of removing rarely
3295                            executed instructions from inside the loop usually
3296                            outweighs the cost of the extra unconditional jump
3297                            outside the loop.  */
3298                         if (loc == 0)
3299                           {
3300                             rtx temp;
3301
3302                             temp = gen_jump (JUMP_LABEL (insn));
3303                             temp = emit_jump_insn_before (temp, target);
3304                             JUMP_LABEL (temp) = JUMP_LABEL (insn);
3305                             LABEL_NUSES (JUMP_LABEL (insn))++;
3306                             loc = emit_barrier_before (target);
3307                           }
3308
3309                         /* Include the BARRIER after INSN and copy the
3310                            block after LOC.  */
3311                         only_notes = squeeze_notes (&new_label,
3312                                                     &last_insn_to_move);
3313                         gcc_assert (!only_notes);
3314                         
3315                         reorder_insns (new_label, last_insn_to_move, loc);
3316
3317                         /* All those insns are now in TARGET_LOOP.  */
3318                         for (q = new_label;
3319                              q != NEXT_INSN (last_insn_to_move);
3320                              q = NEXT_INSN (q))
3321                           uid_loop[INSN_UID (q)] = target_loop;
3322
3323                         /* The label jumped to by INSN is no longer a loop
3324                            exit.  Unless INSN does not have a label (e.g.,
3325                            it is a RETURN insn), search loop->exit_labels
3326                            to find its label_ref, and remove it.  Also turn
3327                            off LABEL_OUTSIDE_LOOP_P bit.  */
3328                         if (JUMP_LABEL (insn))
3329                           {
3330                             for (q = 0, r = this_loop->exit_labels;
3331                                  r;
3332                                  q = r, r = LABEL_NEXTREF (r))
3333                               if (XEXP (r, 0) == JUMP_LABEL (insn))
3334                                 {
3335                                   LABEL_OUTSIDE_LOOP_P (r) = 0;
3336                                   if (q)
3337                                     LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
3338                                   else
3339                                     this_loop->exit_labels = LABEL_NEXTREF (r);
3340                                   break;
3341                                 }
3342
3343                             for (loop = this_loop; loop && loop != target_loop;
3344                                  loop = loop->outer)
3345                               loop->exit_count--;
3346
3347                             /* If we didn't find it, then something is
3348                                wrong.  */
3349                             gcc_assert (r);
3350                           }
3351
3352                         /* P is now a jump outside the loop, so it must be put
3353                            in loop->exit_labels, and marked as such.
3354                            The easiest way to do this is to just call
3355                            mark_loop_jump again for P.  */
3356                         mark_loop_jump (PATTERN (p), this_loop);
3357
3358                         /* If INSN now jumps to the insn after it,
3359                            delete INSN.  */
3360                         if (JUMP_LABEL (insn) != 0
3361                             && (next_real_insn (JUMP_LABEL (insn))
3362                                 == next_real_insn (insn)))
3363                           delete_related_insns (insn);
3364                       }
3365
3366                     /* Continue the loop after where the conditional
3367                        branch used to jump, since the only branch insn
3368                        in the block (if it still remains) is an inter-loop
3369                        branch and hence needs no processing.  */
3370                     insn = NEXT_INSN (cond_label);
3371
3372                     if (--LABEL_NUSES (cond_label) == 0)
3373                       delete_related_insns (cond_label);
3374
3375                     /* This loop will be continued with NEXT_INSN (insn).  */
3376                     insn = PREV_INSN (insn);
3377                   }
3378               }
3379           }
3380       }
3381 }
3382
3383 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
3384    loops it is contained in, mark the target loop invalid.
3385
3386    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
3387
3388 static void
3389 mark_loop_jump (rtx x, struct loop *loop)
3390 {
3391   struct loop *dest_loop;
3392   struct loop *outer_loop;
3393   int i;
3394
3395   switch (GET_CODE (x))
3396     {
3397     case PC:
3398     case USE:
3399     case CLOBBER:
3400     case REG:
3401     case MEM:
3402     case CONST_INT:
3403     case CONST_DOUBLE:
3404     case RETURN:
3405       return;
3406
3407     case CONST:
3408       /* There could be a label reference in here.  */
3409       mark_loop_jump (XEXP (x, 0), loop);
3410       return;
3411
3412     case PLUS:
3413     case MINUS:
3414     case MULT:
3415       mark_loop_jump (XEXP (x, 0), loop);
3416       mark_loop_jump (XEXP (x, 1), loop);
3417       return;
3418
3419     case LO_SUM:
3420       /* This may refer to a LABEL_REF or SYMBOL_REF.  */
3421       mark_loop_jump (XEXP (x, 1), loop);
3422       return;
3423
3424     case SIGN_EXTEND:
3425     case ZERO_EXTEND:
3426       mark_loop_jump (XEXP (x, 0), loop);
3427       return;
3428
3429     case LABEL_REF:
3430       dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3431
3432       /* Link together all labels that branch outside the loop.  This
3433          is used by final_[bg]iv_value and the loop unrolling code.  Also
3434          mark this LABEL_REF so we know that this branch should predict
3435          false.  */
3436
3437       /* A check to make sure the label is not in an inner nested loop,
3438          since this does not count as a loop exit.  */
3439       if (dest_loop)
3440         {
3441           for (outer_loop = dest_loop; outer_loop;
3442                outer_loop = outer_loop->outer)
3443             if (outer_loop == loop)
3444               break;
3445         }
3446       else
3447         outer_loop = NULL;
3448
3449       if (loop && ! outer_loop)
3450         {
3451           LABEL_OUTSIDE_LOOP_P (x) = 1;
3452           LABEL_NEXTREF (x) = loop->exit_labels;
3453           loop->exit_labels = x;
3454
3455           for (outer_loop = loop;
3456                outer_loop && outer_loop != dest_loop;
3457                outer_loop = outer_loop->outer)
3458             outer_loop->exit_count++;
3459         }
3460
3461       /* If this is inside a loop, but not in the current loop or one enclosed
3462          by it, it invalidates at least one loop.  */
3463
3464       if (! dest_loop)
3465         return;
3466
3467       /* We must invalidate every nested loop containing the target of this
3468          label, except those that also contain the jump insn.  */
3469
3470       for (; dest_loop; dest_loop = dest_loop->outer)
3471         {
3472           /* Stop when we reach a loop that also contains the jump insn.  */
3473           for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3474             if (dest_loop == outer_loop)
3475               return;
3476
3477           /* If we get here, we know we need to invalidate a loop.  */
3478           if (loop_dump_stream && ! dest_loop->invalid)
3479             fprintf (loop_dump_stream,
3480                      "\nLoop at %d ignored due to multiple entry points.\n",
3481                      INSN_UID (dest_loop->start));
3482
3483           dest_loop->invalid = 1;
3484         }
3485       return;
3486
3487     case SET:
3488       /* If this is not setting pc, ignore.  */
3489       if (SET_DEST (x) == pc_rtx)
3490         mark_loop_jump (SET_SRC (x), loop);
3491       return;
3492
3493     case IF_THEN_ELSE:
3494       mark_loop_jump (XEXP (x, 1), loop);
3495       mark_loop_jump (XEXP (x, 2), loop);
3496       return;
3497
3498     case PARALLEL:
3499     case ADDR_VEC:
3500       for (i = 0; i < XVECLEN (x, 0); i++)
3501         mark_loop_jump (XVECEXP (x, 0, i), loop);
3502       return;
3503
3504     case ADDR_DIFF_VEC:
3505       for (i = 0; i < XVECLEN (x, 1); i++)
3506         mark_loop_jump (XVECEXP (x, 1, i), loop);
3507       return;
3508
3509     default:
3510       /* Strictly speaking this is not a jump into the loop, only a possible
3511          jump out of the loop.  However, we have no way to link the destination
3512          of this jump onto the list of exit labels.  To be safe we mark this
3513          loop and any containing loops as invalid.  */
3514       if (loop)
3515         {
3516           for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3517             {
3518               if (loop_dump_stream && ! outer_loop->invalid)
3519                 fprintf (loop_dump_stream,
3520                          "\nLoop at %d ignored due to unknown exit jump.\n",
3521                          INSN_UID (outer_loop->start));
3522               outer_loop->invalid = 1;
3523             }
3524         }
3525       return;
3526     }
3527 }
3528 \f
3529 /* Return nonzero if there is a label in the range from
3530    insn INSN to and including the insn whose luid is END
3531    INSN must have an assigned luid (i.e., it must not have
3532    been previously created by loop.c).  */
3533
3534 static int
3535 labels_in_range_p (rtx insn, int end)
3536 {
3537   while (insn && INSN_LUID (insn) <= end)
3538     {
3539       if (LABEL_P (insn))
3540         return 1;
3541       insn = NEXT_INSN (insn);
3542     }
3543
3544   return 0;
3545 }
3546
3547 /* Record that a memory reference X is being set.  */
3548
3549 static void
3550 note_addr_stored (rtx x, rtx y ATTRIBUTE_UNUSED,
3551                   void *data ATTRIBUTE_UNUSED)
3552 {
3553   struct loop_info *loop_info = data;
3554
3555   if (x == 0 || !MEM_P (x))
3556     return;
3557
3558   /* Count number of memory writes.
3559      This affects heuristics in strength_reduce.  */
3560   loop_info->num_mem_sets++;
3561
3562   /* BLKmode MEM means all memory is clobbered.  */
3563   if (GET_MODE (x) == BLKmode)
3564     {
3565       if (MEM_READONLY_P (x))
3566         loop_info->unknown_constant_address_altered = 1;
3567       else
3568         loop_info->unknown_address_altered = 1;
3569
3570       return;
3571     }
3572
3573   loop_info->store_mems = gen_rtx_EXPR_LIST (VOIDmode, x,
3574                                              loop_info->store_mems);
3575 }
3576
3577 /* X is a value modified by an INSN that references a biv inside a loop
3578    exit test (i.e., X is somehow related to the value of the biv).  If X
3579    is a pseudo that is used more than once, then the biv is (effectively)
3580    used more than once.  DATA is a pointer to a loop_regs structure.  */
3581
3582 static void
3583 note_set_pseudo_multiple_uses (rtx x, rtx y ATTRIBUTE_UNUSED, void *data)
3584 {
3585   struct loop_regs *regs = (struct loop_regs *) data;
3586
3587   if (x == 0)
3588     return;
3589
3590   while (GET_CODE (x) == STRICT_LOW_PART
3591          || GET_CODE (x) == SIGN_EXTRACT
3592          || GET_CODE (x) == ZERO_EXTRACT
3593          || GET_CODE (x) == SUBREG)
3594     x = XEXP (x, 0);
3595
3596   if (!REG_P (x) || REGNO (x) < FIRST_PSEUDO_REGISTER)
3597     return;
3598
3599   /* If we do not have usage information, or if we know the register
3600      is used more than once, note that fact for check_dbra_loop.  */
3601   if (REGNO (x) >= max_reg_before_loop
3602       || ! regs->array[REGNO (x)].single_usage
3603       || regs->array[REGNO (x)].single_usage == const0_rtx)
3604     regs->multiple_uses = 1;
3605 }
3606 \f
3607 /* Return nonzero if the rtx X is invariant over the current loop.
3608
3609    The value is 2 if we refer to something only conditionally invariant.
3610
3611    A memory ref is invariant if it is not volatile and does not conflict
3612    with anything stored in `loop_info->store_mems'.  */
3613
3614 static int
3615 loop_invariant_p (const struct loop *loop, rtx x)
3616 {
3617   struct loop_info *loop_info = LOOP_INFO (loop);
3618   struct loop_regs *regs = LOOP_REGS (loop);
3619   int i;
3620   enum rtx_code code;
3621   const char *fmt;
3622   int conditional = 0;
3623   rtx mem_list_entry;
3624
3625   if (x == 0)
3626     return 1;
3627   code = GET_CODE (x);
3628   switch (code)
3629     {
3630     case CONST_INT:
3631     case CONST_DOUBLE:
3632     case SYMBOL_REF:
3633     case CONST:
3634       return 1;
3635
3636     case LABEL_REF:
3637       return 1;
3638
3639     case PC:
3640     case CC0:
3641     case UNSPEC_VOLATILE:
3642       return 0;
3643
3644     case REG:
3645       if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3646            || x == arg_pointer_rtx || x == pic_offset_table_rtx)
3647           && ! current_function_has_nonlocal_goto)
3648         return 1;
3649
3650       if (LOOP_INFO (loop)->has_call
3651           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3652         return 0;
3653
3654       /* Out-of-range regs can occur when we are called from unrolling.
3655          These registers created by the unroller are set in the loop,
3656          hence are never invariant.
3657          Other out-of-range regs can be generated by load_mems; those that
3658          are written to in the loop are not invariant, while those that are
3659          not written to are invariant.  It would be easy for load_mems
3660          to set n_times_set correctly for these registers, however, there
3661          is no easy way to distinguish them from registers created by the
3662          unroller.  */
3663
3664       if (REGNO (x) >= (unsigned) regs->num)
3665         return 0;
3666
3667       if (regs->array[REGNO (x)].set_in_loop < 0)
3668         return 2;
3669
3670       return regs->array[REGNO (x)].set_in_loop == 0;
3671
3672     case MEM:
3673       /* Volatile memory references must be rejected.  Do this before
3674          checking for read-only items, so that volatile read-only items
3675          will be rejected also.  */
3676       if (MEM_VOLATILE_P (x))
3677         return 0;
3678
3679       /* See if there is any dependence between a store and this load.  */
3680       mem_list_entry = loop_info->store_mems;
3681       while (mem_list_entry)
3682         {
3683           if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3684                                x, rtx_varies_p))
3685             return 0;
3686
3687           mem_list_entry = XEXP (mem_list_entry, 1);
3688         }
3689
3690       /* It's not invalidated by a store in memory
3691          but we must still verify the address is invariant.  */
3692       break;
3693
3694     case ASM_OPERANDS:
3695       /* Don't mess with insns declared volatile.  */
3696       if (MEM_VOLATILE_P (x))
3697         return 0;
3698       break;
3699
3700     default:
3701       break;
3702     }
3703
3704   fmt = GET_RTX_FORMAT (code);
3705   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3706     {
3707       if (fmt[i] == 'e')
3708         {
3709           int tem = loop_invariant_p (loop, XEXP (x, i));
3710           if (tem == 0)
3711             return 0;
3712           if (tem == 2)
3713             conditional = 1;
3714         }
3715       else if (fmt[i] == 'E')
3716         {
3717           int j;
3718           for (j = 0; j < XVECLEN (x, i); j++)
3719             {
3720               int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3721               if (tem == 0)
3722                 return 0;
3723               if (tem == 2)
3724                 conditional = 1;
3725             }
3726
3727         }
3728     }
3729
3730   return 1 + conditional;
3731 }
3732 \f
3733 /* Return nonzero if all the insns in the loop that set REG
3734    are INSN and the immediately following insns,
3735    and if each of those insns sets REG in an invariant way
3736    (not counting uses of REG in them).
3737
3738    The value is 2 if some of these insns are only conditionally invariant.
3739
3740    We assume that INSN itself is the first set of REG
3741    and that its source is invariant.  */
3742
3743 static int
3744 consec_sets_invariant_p (const struct loop *loop, rtx reg, int n_sets,
3745                          rtx insn)
3746 {
3747   struct loop_regs *regs = LOOP_REGS (loop);
3748   rtx p = insn;
3749   unsigned int regno = REGNO (reg);
3750   rtx temp;
3751   /* Number of sets we have to insist on finding after INSN.  */
3752   int count = n_sets - 1;
3753   int old = regs->array[regno].set_in_loop;
3754   int value = 0;
3755   int this;
3756
3757   /* If N_SETS hit the limit, we can't rely on its value.  */
3758   if (n_sets == 127)
3759     return 0;
3760
3761   regs->array[regno].set_in_loop = 0;
3762
3763   while (count > 0)
3764     {
3765       enum rtx_code code;
3766       rtx set;
3767
3768       p = NEXT_INSN (p);
3769       code = GET_CODE (p);
3770
3771       /* If library call, skip to end of it.  */
3772       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3773         p = XEXP (temp, 0);
3774
3775       this = 0;
3776       if (code == INSN
3777           && (set = single_set (p))
3778           && REG_P (SET_DEST (set))
3779           && REGNO (SET_DEST (set)) == regno)
3780         {
3781           this = loop_invariant_p (loop, SET_SRC (set));
3782           if (this != 0)
3783             value |= this;
3784           else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3785             {
3786               /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3787                  If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3788                  notes are OK.  */
3789               this = (CONSTANT_P (XEXP (temp, 0))
3790                       || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3791                           && loop_invariant_p (loop, XEXP (temp, 0))));
3792               if (this != 0)
3793                 value |= this;
3794             }
3795         }
3796       if (this != 0)
3797         count--;
3798       else if (code != NOTE)
3799         {
3800           regs->array[regno].set_in_loop = old;
3801           return 0;
3802         }
3803     }
3804
3805   regs->array[regno].set_in_loop = old;
3806   /* If loop_invariant_p ever returned 2, we return 2.  */
3807   return 1 + (value & 2);
3808 }
3809 \f
3810 /* Look at all uses (not sets) of registers in X.  For each, if it is
3811    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3812    a different insn, set USAGE[REGNO] to const0_rtx.  */
3813
3814 static void
3815 find_single_use_in_loop (struct loop_regs *regs, rtx insn, rtx x)
3816 {
3817   enum rtx_code code = GET_CODE (x);
3818   const char *fmt = GET_RTX_FORMAT (code);
3819   int i, j;
3820
3821   if (code == REG)
3822     regs->array[REGNO (x)].single_usage
3823       = (regs->array[REGNO (x)].single_usage != 0
3824          && regs->array[REGNO (x)].single_usage != insn)
3825         ? const0_rtx : insn;
3826
3827   else if (code == SET)
3828     {
3829       /* Don't count SET_DEST if it is a REG; otherwise count things
3830          in SET_DEST because if a register is partially modified, it won't
3831          show up as a potential movable so we don't care how USAGE is set
3832          for it.  */
3833       if (!REG_P (SET_DEST (x)))
3834         find_single_use_in_loop (regs, insn, SET_DEST (x));
3835       find_single_use_in_loop (regs, insn, SET_SRC (x));
3836     }
3837   else
3838     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3839       {
3840         if (fmt[i] == 'e' && XEXP (x, i) != 0)
3841           find_single_use_in_loop (regs, insn, XEXP (x, i));
3842         else if (fmt[i] == 'E')
3843           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3844             find_single_use_in_loop (regs, insn, XVECEXP (x, i, j));
3845       }
3846 }
3847 \f
3848 /* Count and record any set in X which is contained in INSN.  Update
3849    REGS->array[I].MAY_NOT_OPTIMIZE and LAST_SET for any register I set
3850    in X.  */
3851
3852 static void
3853 count_one_set (struct loop_regs *regs, rtx insn, rtx x, rtx *last_set)
3854 {
3855   if (GET_CODE (x) == CLOBBER && REG_P (XEXP (x, 0)))
3856     /* Don't move a reg that has an explicit clobber.
3857        It's not worth the pain to try to do it correctly.  */
3858     regs->array[REGNO (XEXP (x, 0))].may_not_optimize = 1;
3859
3860   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3861     {
3862       rtx dest = SET_DEST (x);
3863       while (GET_CODE (dest) == SUBREG
3864              || GET_CODE (dest) == ZERO_EXTRACT
3865              || GET_CODE (dest) == STRICT_LOW_PART)
3866         dest = XEXP (dest, 0);
3867       if (REG_P (dest))
3868         {
3869           int i;
3870           int regno = REGNO (dest);
3871           for (i = 0; i < LOOP_REGNO_NREGS (regno, dest); i++)
3872             {
3873               /* If this is the first setting of this reg
3874                  in current basic block, and it was set before,
3875                  it must be set in two basic blocks, so it cannot
3876                  be moved out of the loop.  */
3877               if (regs->array[regno].set_in_loop > 0
3878                   && last_set[regno] == 0)
3879                 regs->array[regno+i].may_not_optimize = 1;
3880               /* If this is not first setting in current basic block,
3881                  see if reg was used in between previous one and this.
3882                  If so, neither one can be moved.  */
3883               if (last_set[regno] != 0
3884                   && reg_used_between_p (dest, last_set[regno], insn))
3885                 regs->array[regno+i].may_not_optimize = 1;
3886               if (regs->array[regno+i].set_in_loop < 127)
3887                 ++regs->array[regno+i].set_in_loop;
3888               last_set[regno+i] = insn;
3889             }
3890         }
3891     }
3892 }
3893 \f
3894 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3895    is entered at LOOP->SCAN_START, return 1 if the register set in SET
3896    contained in insn INSN is used by any insn that precedes INSN in
3897    cyclic order starting from the loop entry point.
3898
3899    We don't want to use INSN_LUID here because if we restrict INSN to those
3900    that have a valid INSN_LUID, it means we cannot move an invariant out
3901    from an inner loop past two loops.  */
3902
3903 static int
3904 loop_reg_used_before_p (const struct loop *loop, rtx set, rtx insn)
3905 {
3906   rtx reg = SET_DEST (set);
3907   rtx p;
3908
3909   /* Scan forward checking for register usage.  If we hit INSN, we
3910      are done.  Otherwise, if we hit LOOP->END, wrap around to LOOP->START.  */
3911   for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3912     {
3913       if (INSN_P (p) && reg_overlap_mentioned_p (reg, PATTERN (p)))
3914         return 1;
3915
3916       if (p == loop->end)
3917         p = loop->start;
3918     }
3919
3920   return 0;
3921 }
3922 \f
3923
3924 /* Information we collect about arrays that we might want to prefetch.  */
3925 struct prefetch_info
3926 {
3927   struct iv_class *class;       /* Class this prefetch is based on.  */
3928   struct induction *giv;        /* GIV this prefetch is based on.  */
3929   rtx base_address;             /* Start prefetching from this address plus
3930                                    index.  */
3931   HOST_WIDE_INT index;
3932   HOST_WIDE_INT stride;         /* Prefetch stride in bytes in each
3933                                    iteration.  */
3934   unsigned int bytes_accessed;  /* Sum of sizes of all accesses to this
3935                                    prefetch area in one iteration.  */
3936   unsigned int total_bytes;     /* Total bytes loop will access in this block.
3937                                    This is set only for loops with known
3938                                    iteration counts and is 0xffffffff
3939                                    otherwise.  */
3940   int prefetch_in_loop;         /* Number of prefetch insns in loop.  */
3941   int prefetch_before_loop;     /* Number of prefetch insns before loop.  */
3942   unsigned int write : 1;       /* 1 for read/write prefetches.  */
3943 };
3944
3945 /* Data used by check_store function.  */
3946 struct check_store_data
3947 {
3948   rtx mem_address;
3949   int mem_write;
3950 };
3951
3952 static void check_store (rtx, rtx, void *);
3953 static void emit_prefetch_instructions (struct loop *);
3954 static int rtx_equal_for_prefetch_p (rtx, rtx);
3955
3956 /* Set mem_write when mem_address is found.  Used as callback to
3957    note_stores.  */
3958 static void
3959 check_store (rtx x, rtx pat ATTRIBUTE_UNUSED, void *data)
3960 {
3961   struct check_store_data *d = (struct check_store_data *) data;
3962
3963   if ((MEM_P (x)) && rtx_equal_p (d->mem_address, XEXP (x, 0)))
3964     d->mem_write = 1;
3965 }
3966 \f
3967 /* Like rtx_equal_p, but attempts to swap commutative operands.  This is
3968    important to get some addresses combined.  Later more sophisticated
3969    transformations can be added when necessary.
3970
3971    ??? Same trick with swapping operand is done at several other places.
3972    It can be nice to develop some common way to handle this.  */
3973
3974 static int
3975 rtx_equal_for_prefetch_p (rtx x, rtx y)
3976 {
3977   int i;
3978   int j;
3979   enum rtx_code code = GET_CODE (x);
3980   const char *fmt;
3981
3982   if (x == y)
3983     return 1;
3984   if (code != GET_CODE (y))
3985     return 0;
3986
3987   if (COMMUTATIVE_ARITH_P (x))
3988     {
3989       return ((rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 0))
3990                && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 1)))
3991               || (rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 1))
3992                   && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 0))));
3993     }
3994
3995   /* Compare the elements.  If any pair of corresponding elements fails to
3996      match, return 0 for the whole thing.  */
3997
3998   fmt = GET_RTX_FORMAT (code);
3999   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4000     {
4001       switch (fmt[i])
4002         {
4003         case 'w':
4004           if (XWINT (x, i) != XWINT (y, i))
4005             return 0;
4006           break;
4007
4008         case 'i':
4009           if (XINT (x, i) != XINT (y, i))
4010             return 0;
4011           break;
4012
4013         case 'E':
4014           /* Two vectors must have the same length.  */
4015           if (XVECLEN (x, i) != XVECLEN (y, i))
4016             return 0;
4017
4018           /* And the corresponding elements must match.  */
4019           for (j = 0; j < XVECLEN (x, i); j++)
4020             if (rtx_equal_for_prefetch_p (XVECEXP (x, i, j),
4021                                           XVECEXP (y, i, j)) == 0)
4022               return 0;
4023           break;
4024
4025         case 'e':
4026           if (rtx_equal_for_prefetch_p (XEXP (x, i), XEXP (y, i)) == 0)
4027             return 0;
4028           break;
4029
4030         case 's':
4031           if (strcmp (XSTR (x, i), XSTR (y, i)))
4032             return 0;
4033           break;
4034
4035         case 'u':
4036           /* These are just backpointers, so they don't matter.  */
4037           break;
4038
4039         case '0':
4040           break;
4041
4042           /* It is believed that rtx's at this level will never
4043              contain anything but integers and other rtx's,
4044              except for within LABEL_REFs and SYMBOL_REFs.  */
4045         default:
4046           gcc_unreachable ();
4047         }
4048     }
4049   return 1;
4050 }
4051 \f
4052 /* Remove constant addition value from the expression X (when present)
4053    and return it.  */
4054
4055 static HOST_WIDE_INT
4056 remove_constant_addition (rtx *x)
4057 {
4058   HOST_WIDE_INT addval = 0;
4059   rtx exp = *x;
4060
4061   /* Avoid clobbering a shared CONST expression.  */
4062   if (GET_CODE (exp) == CONST)
4063     {
4064       if (GET_CODE (XEXP (exp, 0)) == PLUS
4065           && GET_CODE (XEXP (XEXP (exp, 0), 0)) == SYMBOL_REF
4066           && GET_CODE (XEXP (XEXP (exp, 0), 1)) == CONST_INT)
4067         {
4068           *x = XEXP (XEXP (exp, 0), 0);
4069           return INTVAL (XEXP (XEXP (exp, 0), 1));
4070         }
4071       return 0;
4072     }
4073
4074   if (GET_CODE (exp) == CONST_INT)
4075     {
4076       addval = INTVAL (exp);
4077       *x = const0_rtx;
4078     }
4079
4080   /* For plus expression recurse on ourself.  */
4081   else if (GET_CODE (exp) == PLUS)
4082     {
4083       addval += remove_constant_addition (&XEXP (exp, 0));
4084       addval += remove_constant_addition (&XEXP (exp, 1));
4085
4086       /* In case our parameter was constant, remove extra zero from the
4087          expression.  */
4088       if (XEXP (exp, 0) == const0_rtx)
4089         *x = XEXP (exp, 1);
4090       else if (XEXP (exp, 1) == const0_rtx)
4091         *x = XEXP (exp, 0);
4092     }
4093
4094   return addval;
4095 }
4096
4097 /* Attempt to identify accesses to arrays that are most likely to cause cache
4098    misses, and emit prefetch instructions a few prefetch blocks forward.
4099
4100    To detect the arrays we use the GIV information that was collected by the
4101    strength reduction pass.
4102
4103    The prefetch instructions are generated after the GIV information is done
4104    and before the strength reduction process. The new GIVs are injected into
4105    the strength reduction tables, so the prefetch addresses are optimized as
4106    well.
4107
4108    GIVs are split into base address, stride, and constant addition values.
4109    GIVs with the same address, stride and close addition values are combined
4110    into a single prefetch.  Also writes to GIVs are detected, so that prefetch
4111    for write instructions can be used for the block we write to, on machines
4112    that support write prefetches.
4113
4114    Several heuristics are used to determine when to prefetch.  They are
4115    controlled by defined symbols that can be overridden for each target.  */
4116
4117 static void
4118 emit_prefetch_instructions (struct loop *loop)
4119 {
4120   int num_prefetches = 0;
4121   int num_real_prefetches = 0;
4122   int num_real_write_prefetches = 0;
4123   int num_prefetches_before = 0;
4124   int num_write_prefetches_before = 0;
4125   int ahead = 0;
4126   int i;
4127   struct iv_class *bl;
4128   struct induction *iv;
4129   struct prefetch_info info[MAX_PREFETCHES];
4130   struct loop_ivs *ivs = LOOP_IVS (loop);
4131
4132   if (!HAVE_prefetch || PREFETCH_BLOCK == 0)
4133     return;
4134
4135   /* Consider only loops w/o calls.  When a call is done, the loop is probably
4136      slow enough to read the memory.  */
4137   if (PREFETCH_NO_CALL && LOOP_INFO (loop)->has_call)
4138     {
4139       if (loop_dump_stream)
4140         fprintf (loop_dump_stream, "Prefetch: ignoring loop: has call.\n");
4141
4142       return;
4143     }
4144
4145   /* Don't prefetch in loops known to have few iterations.  */
4146   if (PREFETCH_NO_LOW_LOOPCNT
4147       && LOOP_INFO (loop)->n_iterations
4148       && LOOP_INFO (loop)->n_iterations <= PREFETCH_LOW_LOOPCNT)
4149     {
4150       if (loop_dump_stream)
4151         fprintf (loop_dump_stream,
4152                  "Prefetch: ignoring loop: not enough iterations.\n");
4153       return;
4154     }
4155
4156   /* Search all induction variables and pick those interesting for the prefetch
4157      machinery.  */
4158   for (bl = ivs->list; bl; bl = bl->next)
4159     {
4160       struct induction *biv = bl->biv, *biv1;
4161       int basestride = 0;
4162
4163       biv1 = biv;
4164
4165       /* Expect all BIVs to be executed in each iteration.  This makes our
4166          analysis more conservative.  */
4167       while (biv1)
4168         {
4169           /* Discard non-constant additions that we can't handle well yet, and
4170              BIVs that are executed multiple times; such BIVs ought to be
4171              handled in the nested loop.  We accept not_every_iteration BIVs,
4172              since these only result in larger strides and make our
4173              heuristics more conservative.  */
4174           if (GET_CODE (biv->add_val) != CONST_INT)
4175             {
4176               if (loop_dump_stream)
4177                 {
4178                   fprintf (loop_dump_stream,
4179                     "Prefetch: ignoring biv %d: non-constant addition at insn %d:",
4180                            REGNO (biv->src_reg), INSN_UID (biv->insn));
4181                   print_rtl (loop_dump_stream, biv->add_val);
4182                   fprintf (loop_dump_stream, "\n");
4183                 }
4184               break;
4185             }
4186
4187           if (biv->maybe_multiple)
4188             {
4189               if (loop_dump_stream)
4190                 {
4191                   fprintf (loop_dump_stream,
4192                            "Prefetch: ignoring biv %d: maybe_multiple at insn %i:",
4193                            REGNO (biv->src_reg), INSN_UID (biv->insn));
4194                   print_rtl (loop_dump_stream, biv->add_val);
4195                   fprintf (loop_dump_stream, "\n");
4196                 }
4197               break;
4198             }
4199
4200           basestride += INTVAL (biv1->add_val);
4201           biv1 = biv1->next_iv;
4202         }
4203
4204       if (biv1 || !basestride)
4205         continue;
4206
4207       for (iv = bl->giv; iv; iv = iv->next_iv)
4208         {
4209           rtx address;
4210           rtx temp;
4211           HOST_WIDE_INT index = 0;
4212           int add = 1;
4213           HOST_WIDE_INT stride = 0;
4214           int stride_sign = 1;
4215           struct check_store_data d;
4216           const char *ignore_reason = NULL;
4217           int size = GET_MODE_SIZE (GET_MODE (iv));
4218
4219           /* See whether an induction variable is interesting to us and if
4220              not, report the reason.  */
4221           if (iv->giv_type != DEST_ADDR)
4222             ignore_reason = "giv is not a destination address";
4223
4224           /* We are interested only in constant stride memory references
4225              in order to be able to compute density easily.  */
4226           else if (GET_CODE (iv->mult_val) != CONST_INT)
4227             ignore_reason = "stride is not constant";
4228
4229           else
4230             {
4231               stride = INTVAL (iv->mult_val) * basestride;
4232               if (stride < 0)
4233                 {
4234                   stride = -stride;
4235                   stride_sign = -1;
4236                 }
4237
4238               /* On some targets, reversed order prefetches are not
4239                  worthwhile.  */
4240               if (PREFETCH_NO_REVERSE_ORDER && stride_sign < 0)
4241                 ignore_reason = "reversed order stride";
4242
4243               /* Prefetch of accesses with an extreme stride might not be
4244                  worthwhile, either.  */
4245               else if (PREFETCH_NO_EXTREME_STRIDE
4246                        && stride > PREFETCH_EXTREME_STRIDE)
4247                 ignore_reason = "extreme stride";
4248
4249               /* Ignore GIVs with varying add values; we can't predict the
4250                  value for the next iteration.  */
4251               else if (!loop_invariant_p (loop, iv->add_val))
4252                 ignore_reason = "giv has varying add value";
4253
4254               /* Ignore GIVs in the nested loops; they ought to have been
4255                  handled already.  */
4256               else if (iv->maybe_multiple)
4257                 ignore_reason = "giv is in nested loop";
4258             }
4259
4260           if (ignore_reason != NULL)
4261             {
4262               if (loop_dump_stream)
4263                 fprintf (loop_dump_stream,
4264                          "Prefetch: ignoring giv at %d: %s.\n",
4265                          INSN_UID (iv->insn), ignore_reason);
4266               continue;
4267             }
4268
4269           /* Determine the pointer to the basic array we are examining.  It is
4270              the sum of the BIV's initial value and the GIV's add_val.  */
4271           address = copy_rtx (iv->add_val);
4272           temp = copy_rtx (bl->initial_value);
4273
4274           address = simplify_gen_binary (PLUS, Pmode, temp, address);
4275           index = remove_constant_addition (&address);
4276
4277           d.mem_write = 0;
4278           d.mem_address = *iv->location;
4279
4280           /* When the GIV is not always executed, we might be better off by
4281              not dirtying the cache pages.  */
4282           if (PREFETCH_CONDITIONAL || iv->always_executed)
4283             note_stores (PATTERN (iv->insn), check_store, &d);
4284           else
4285             {
4286               if (loop_dump_stream)
4287                 fprintf (loop_dump_stream, "Prefetch: Ignoring giv at %d: %s\n",
4288                          INSN_UID (iv->insn), "in conditional code.");
4289               continue;
4290             }
4291
4292           /* Attempt to find another prefetch to the same array and see if we
4293              can merge this one.  */
4294           for (i = 0; i < num_prefetches; i++)
4295             if (rtx_equal_for_prefetch_p (address, info[i].base_address)
4296                 && stride == info[i].stride)
4297               {
4298                 /* In case both access same array (same location
4299                    just with small difference in constant indexes), merge
4300                    the prefetches.  Just do the later and the earlier will
4301                    get prefetched from previous iteration.
4302                    The artificial threshold should not be too small,
4303                    but also not bigger than small portion of memory usually
4304                    traversed by single loop.  */
4305                 if (index >= info[i].index
4306                     && index - info[i].index < PREFETCH_EXTREME_DIFFERENCE)
4307                   {
4308                     info[i].write |= d.mem_write;
4309                     info[i].bytes_accessed += size;
4310                     info[i].index = index;
4311                     info[i].giv = iv;
4312                     info[i].class = bl;
4313                     info[num_prefetches].base_address = address;
4314                     add = 0;
4315                     break;
4316                   }
4317
4318                 if (index < info[i].index
4319                     && info[i].index - index < PREFETCH_EXTREME_DIFFERENCE)
4320                   {
4321                     info[i].write |= d.mem_write;
4322                     info[i].bytes_accessed += size;
4323                     add = 0;
4324                     break;
4325                   }
4326               }
4327
4328           /* Merging failed.  */
4329           if (add)
4330             {
4331               info[num_prefetches].giv = iv;
4332               info[num_prefetches].class = bl;
4333               info[num_prefetches].index = index;
4334               info[num_prefetches].stride = stride;
4335               info[num_prefetches].base_address = address;
4336               info[num_prefetches].write = d.mem_write;
4337               info[num_prefetches].bytes_accessed = size;
4338               num_prefetches++;
4339               if (num_prefetches >= MAX_PREFETCHES)
4340                 {
4341                   if (loop_dump_stream)
4342                     fprintf (loop_dump_stream,
4343                              "Maximal number of prefetches exceeded.\n");
4344                   return;
4345                 }
4346             }
4347         }
4348     }
4349
4350   for (i = 0; i < num_prefetches; i++)
4351     {
4352       int density;
4353
4354       /* Attempt to calculate the total number of bytes fetched by all
4355          iterations of the loop.  Avoid overflow.  */
4356       if (LOOP_INFO (loop)->n_iterations
4357           && ((unsigned HOST_WIDE_INT) (0xffffffff / info[i].stride)
4358               >= LOOP_INFO (loop)->n_iterations))
4359         info[i].total_bytes = info[i].stride * LOOP_INFO (loop)->n_iterations;
4360       else
4361         info[i].total_bytes = 0xffffffff;
4362
4363       density = info[i].bytes_accessed * 100 / info[i].stride;
4364
4365       /* Prefetch might be worthwhile only when the loads/stores are dense.  */
4366       if (PREFETCH_ONLY_DENSE_MEM)
4367         if (density * 256 > PREFETCH_DENSE_MEM * 100
4368             && (info[i].total_bytes / PREFETCH_BLOCK
4369                 >= PREFETCH_BLOCKS_BEFORE_LOOP_MIN))
4370           {
4371             info[i].prefetch_before_loop = 1;
4372             info[i].prefetch_in_loop
4373               = (info[i].total_bytes / PREFETCH_BLOCK
4374                  > PREFETCH_BLOCKS_BEFORE_LOOP_MAX);
4375           }
4376         else
4377           {
4378             info[i].prefetch_in_loop = 0, info[i].prefetch_before_loop = 0;
4379             if (loop_dump_stream)
4380               fprintf (loop_dump_stream,
4381                   "Prefetch: ignoring giv at %d: %d%% density is too low.\n",
4382                        INSN_UID (info[i].giv->insn), density);
4383           }
4384       else
4385         info[i].prefetch_in_loop = 1, info[i].prefetch_before_loop = 1;
4386
4387       /* Find how many prefetch instructions we'll use within the loop.  */
4388       if (info[i].prefetch_in_loop != 0)
4389         {
4390           info[i].prefetch_in_loop = ((info[i].stride + PREFETCH_BLOCK - 1)
4391                                   / PREFETCH_BLOCK);
4392           num_real_prefetches += info[i].prefetch_in_loop;
4393           if (info[i].write)
4394             num_real_write_prefetches += info[i].prefetch_in_loop;
4395         }
4396     }
4397
4398   /* Determine how many iterations ahead to prefetch within the loop, based
4399      on how many prefetches we currently expect to do within the loop.  */
4400   if (num_real_prefetches != 0)
4401     {
4402       if ((ahead = SIMULTANEOUS_PREFETCHES / num_real_prefetches) == 0)
4403         {
4404           if (loop_dump_stream)
4405             fprintf (loop_dump_stream,
4406                      "Prefetch: ignoring prefetches within loop: ahead is zero; %d < %d\n",
4407                      SIMULTANEOUS_PREFETCHES, num_real_prefetches);
4408           num_real_prefetches = 0, num_real_write_prefetches = 0;
4409         }
4410     }
4411   /* We'll also use AHEAD to determine how many prefetch instructions to
4412      emit before a loop, so don't leave it zero.  */
4413   if (ahead == 0)
4414     ahead = PREFETCH_BLOCKS_BEFORE_LOOP_MAX;
4415
4416   for (i = 0; i < num_prefetches; i++)
4417     {
4418       /* Update if we've decided not to prefetch anything within the loop.  */
4419       if (num_real_prefetches == 0)
4420         info[i].prefetch_in_loop = 0;
4421
4422       /* Find how many prefetch instructions we'll use before the loop.  */
4423       if (info[i].prefetch_before_loop != 0)
4424         {
4425           int n = info[i].total_bytes / PREFETCH_BLOCK;
4426           if (n > ahead)
4427             n = ahead;
4428           info[i].prefetch_before_loop = n;
4429           num_prefetches_before += n;
4430           if (info[i].write)
4431             num_write_prefetches_before += n;
4432         }
4433
4434       if (loop_dump_stream)
4435         {
4436           if (info[i].prefetch_in_loop == 0
4437               && info[i].prefetch_before_loop == 0)
4438             continue;
4439           fprintf (loop_dump_stream, "Prefetch insn: %d",
4440                    INSN_UID (info[i].giv->insn));
4441           fprintf (loop_dump_stream,
4442                    "; in loop: %d; before: %d; %s\n",
4443                    info[i].prefetch_in_loop,
4444                    info[i].prefetch_before_loop,
4445                    info[i].write ? "read/write" : "read only");
4446           fprintf (loop_dump_stream,
4447                    " density: %d%%; bytes_accessed: %u; total_bytes: %u\n",
4448                    (int) (info[i].bytes_accessed * 100 / info[i].stride),
4449                    info[i].bytes_accessed, info[i].total_bytes);
4450           fprintf (loop_dump_stream, " index: " HOST_WIDE_INT_PRINT_DEC
4451                    "; stride: " HOST_WIDE_INT_PRINT_DEC "; address: ",
4452                    info[i].index, info[i].stride);
4453           print_rtl (loop_dump_stream, info[i].base_address);
4454           fprintf (loop_dump_stream, "\n");
4455         }
4456     }
4457
4458   if (num_real_prefetches + num_prefetches_before > 0)
4459     {
4460       /* Record that this loop uses prefetch instructions.  */
4461       LOOP_INFO (loop)->has_prefetch = 1;
4462
4463       if (loop_dump_stream)
4464         {
4465           fprintf (loop_dump_stream, "Real prefetches needed within loop: %d (write: %d)\n",
4466                    num_real_prefetches, num_real_write_prefetches);
4467           fprintf (loop_dump_stream, "Real prefetches needed before loop: %d (write: %d)\n",
4468                    num_prefetches_before, num_write_prefetches_before);
4469         }
4470     }
4471
4472   for (i = 0; i < num_prefetches; i++)
4473     {
4474       int y;
4475
4476       for (y = 0; y < info[i].prefetch_in_loop; y++)
4477         {
4478           rtx loc = copy_rtx (*info[i].giv->location);
4479           rtx insn;
4480           int bytes_ahead = PREFETCH_BLOCK * (ahead + y);
4481           rtx before_insn = info[i].giv->insn;
4482           rtx prev_insn = PREV_INSN (info[i].giv->insn);
4483           rtx seq;
4484
4485           /* We can save some effort by offsetting the address on
4486              architectures with offsettable memory references.  */
4487           if (offsettable_address_p (0, VOIDmode, loc))
4488             loc = plus_constant (loc, bytes_ahead);
4489           else
4490             {
4491               rtx reg = gen_reg_rtx (Pmode);
4492               loop_iv_add_mult_emit_before (loop, loc, const1_rtx,
4493                                             GEN_INT (bytes_ahead), reg,
4494                                             0, before_insn);
4495               loc = reg;
4496             }
4497
4498           start_sequence ();
4499           /* Make sure the address operand is valid for prefetch.  */
4500           if (! (*insn_data[(int)CODE_FOR_prefetch].operand[0].predicate)
4501                   (loc, insn_data[(int)CODE_FOR_prefetch].operand[0].mode))
4502             loc = force_reg (Pmode, loc);
4503           emit_insn (gen_prefetch (loc, GEN_INT (info[i].write),
4504                                    GEN_INT (3)));
4505           seq = get_insns ();
4506           end_sequence ();
4507           emit_insn_before (seq, before_insn);
4508
4509           /* Check all insns emitted and record the new GIV
4510              information.  */
4511           insn = NEXT_INSN (prev_insn);
4512           while (insn != before_insn)
4513             {
4514               insn = check_insn_for_givs (loop, insn,
4515                                           info[i].giv->always_executed,
4516                                           info[i].giv->maybe_multiple);
4517               insn = NEXT_INSN (insn);
4518             }
4519         }
4520
4521       if (PREFETCH_BEFORE_LOOP)
4522         {
4523           /* Emit insns before the loop to fetch the first cache lines or,
4524              if we're not prefetching within the loop, everything we expect
4525              to need.  */
4526           for (y = 0; y < info[i].prefetch_before_loop; y++)
4527             {
4528               rtx reg = gen_reg_rtx (Pmode);
4529               rtx loop_start = loop->start;
4530               rtx init_val = info[i].class->initial_value;
4531               rtx add_val = simplify_gen_binary (PLUS, Pmode,
4532                                                  info[i].giv->add_val,
4533                                                  GEN_INT (y * PREFETCH_BLOCK));
4534
4535               /* Functions called by LOOP_IV_ADD_EMIT_BEFORE expect a
4536                  non-constant INIT_VAL to have the same mode as REG, which
4537                  in this case we know to be Pmode.  */
4538               if (GET_MODE (init_val) != Pmode && !CONSTANT_P (init_val))
4539                 {
4540                   rtx seq;
4541
4542                   start_sequence ();
4543                   init_val = convert_to_mode (Pmode, init_val, 0);
4544                   seq = get_insns ();
4545                   end_sequence ();
4546                   loop_insn_emit_before (loop, 0, loop_start, seq);
4547                 }
4548               loop_iv_add_mult_emit_before (loop, init_val,
4549                                             info[i].giv->mult_val,
4550                                             add_val, reg, 0, loop_start);
4551               emit_insn_before (gen_prefetch (reg, GEN_INT (info[i].write),
4552                                               GEN_INT (3)),
4553                                 loop_start);
4554             }
4555         }
4556     }
4557
4558   return;
4559 }
4560 \f
4561 /* Communication with routines called via `note_stores'.  */
4562
4563 static rtx note_insn;
4564
4565 /* Dummy register to have nonzero DEST_REG for DEST_ADDR type givs.  */
4566
4567 static rtx addr_placeholder;
4568
4569 /* ??? Unfinished optimizations, and possible future optimizations,
4570    for the strength reduction code.  */
4571
4572 /* ??? The interaction of biv elimination, and recognition of 'constant'
4573    bivs, may cause problems.  */
4574
4575 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
4576    performance problems.
4577
4578    Perhaps don't eliminate things that can be combined with an addressing
4579    mode.  Find all givs that have the same biv, mult_val, and add_val;
4580    then for each giv, check to see if its only use dies in a following
4581    memory address.  If so, generate a new memory address and check to see
4582    if it is valid.   If it is valid, then store the modified memory address,
4583    otherwise, mark the giv as not done so that it will get its own iv.  */
4584
4585 /* ??? Could try to optimize branches when it is known that a biv is always
4586    positive.  */
4587
4588 /* ??? When replace a biv in a compare insn, we should replace with closest
4589    giv so that an optimized branch can still be recognized by the combiner,
4590    e.g. the VAX acb insn.  */
4591
4592 /* ??? Many of the checks involving uid_luid could be simplified if regscan
4593    was rerun in loop_optimize whenever a register was added or moved.
4594    Also, some of the optimizations could be a little less conservative.  */
4595 \f
4596 /* Searches the insns between INSN and LOOP->END.  Returns 1 if there
4597    is a backward branch in that range that branches to somewhere between
4598    LOOP->START and INSN.  Returns 0 otherwise.  */
4599
4600 /* ??? This is quadratic algorithm.  Could be rewritten to be linear.
4601    In practice, this is not a problem, because this function is seldom called,
4602    and uses a negligible amount of CPU time on average.  */
4603
4604 static int
4605 back_branch_in_range_p (const struct loop *loop, rtx insn)
4606 {
4607   rtx p, q, target_insn;
4608   rtx loop_start = loop->start;
4609   rtx loop_end = loop->end;
4610   rtx orig_loop_end = loop->end;
4611
4612   /* Stop before we get to the backward branch at the end of the loop.  */
4613   loop_end = prev_nonnote_insn (loop_end);
4614   if (BARRIER_P (loop_end))
4615     loop_end = PREV_INSN (loop_end);
4616
4617   /* Check in case insn has been deleted, search forward for first non
4618      deleted insn following it.  */
4619   while (INSN_DELETED_P (insn))
4620     insn = NEXT_INSN (insn);
4621
4622   /* Check for the case where insn is the last insn in the loop.  Deal
4623      with the case where INSN was a deleted loop test insn, in which case
4624      it will now be the NOTE_LOOP_END.  */
4625   if (insn == loop_end || insn == orig_loop_end)
4626     return 0;
4627
4628   for (p = NEXT_INSN (insn); p != loop_end; p = NEXT_INSN (p))
4629     {
4630       if (JUMP_P (p))
4631         {
4632           target_insn = JUMP_LABEL (p);
4633
4634           /* Search from loop_start to insn, to see if one of them is
4635              the target_insn.  We can't use INSN_LUID comparisons here,
4636              since insn may not have an LUID entry.  */
4637           for (q = loop_start; q != insn; q = NEXT_INSN (q))
4638             if (q == target_insn)
4639               return 1;
4640         }
4641     }
4642
4643   return 0;
4644 }
4645
4646 /* Scan the loop body and call FNCALL for each insn.  In the addition to the
4647    LOOP and INSN parameters pass MAYBE_MULTIPLE and NOT_EVERY_ITERATION to the
4648    callback.
4649
4650    NOT_EVERY_ITERATION is 1 if current insn is not known to be executed at
4651    least once for every loop iteration except for the last one.
4652
4653    MAYBE_MULTIPLE is 1 if current insn may be executed more than once for every
4654    loop iteration.
4655  */
4656 typedef rtx (*loop_insn_callback) (struct loop *, rtx, int, int);
4657 static void
4658 for_each_insn_in_loop (struct loop *loop, loop_insn_callback fncall)
4659 {
4660   int not_every_iteration = 0;
4661   int maybe_multiple = 0;
4662   int past_loop_latch = 0;
4663   bool exit_test_is_entry = false;
4664   rtx p;
4665
4666   /* If loop_scan_start points to the loop exit test, the loop body
4667      cannot be counted on running on every iteration, and we have to
4668      be wary of subversive use of gotos inside expression
4669      statements.  */
4670   if (prev_nonnote_insn (loop->scan_start) != prev_nonnote_insn (loop->start))
4671     {
4672       exit_test_is_entry = true;
4673       maybe_multiple = back_branch_in_range_p (loop, loop->scan_start);
4674     }
4675
4676   /* Scan through loop and update NOT_EVERY_ITERATION and MAYBE_MULTIPLE.  */
4677   for (p = next_insn_in_loop (loop, loop->scan_start);
4678        p != NULL_RTX;
4679        p = next_insn_in_loop (loop, p))
4680     {
4681       p = fncall (loop, p, not_every_iteration, maybe_multiple);
4682
4683       /* Past CODE_LABEL, we get to insns that may be executed multiple
4684          times.  The only way we can be sure that they can't is if every
4685          jump insn between here and the end of the loop either
4686          returns, exits the loop, is a jump to a location that is still
4687          behind the label, or is a jump to the loop start.  */
4688
4689       if (LABEL_P (p))
4690         {
4691           rtx insn = p;
4692
4693           maybe_multiple = 0;
4694
4695           while (1)
4696             {
4697               insn = NEXT_INSN (insn);
4698               if (insn == loop->scan_start)
4699                 break;
4700               if (insn == loop->end)
4701                 {
4702                   if (loop->top != 0)
4703                     insn = loop->top;
4704                   else
4705                     break;
4706                   if (insn == loop->scan_start)
4707                     break;
4708                 }
4709
4710               if (JUMP_P (insn)
4711                   && GET_CODE (PATTERN (insn)) != RETURN
4712                   && (!any_condjump_p (insn)
4713                       || (JUMP_LABEL (insn) != 0
4714                           && JUMP_LABEL (insn) != loop->scan_start
4715                           && !loop_insn_first_p (p, JUMP_LABEL (insn)))))
4716                 {
4717                   maybe_multiple = 1;
4718                   break;
4719                 }
4720             }
4721         }
4722
4723       /* Past a jump, we get to insns for which we can't count
4724          on whether they will be executed during each iteration.  */
4725       /* This code appears twice in strength_reduce.  There is also similar
4726          code in scan_loop.  */
4727       if (JUMP_P (p)
4728       /* If we enter the loop in the middle, and scan around to the
4729          beginning, don't set not_every_iteration for that.
4730          This can be any kind of jump, since we want to know if insns
4731          will be executed if the loop is executed.  */
4732           && (exit_test_is_entry
4733               || !(JUMP_LABEL (p) == loop->top
4734                    && ((NEXT_INSN (NEXT_INSN (p)) == loop->end
4735                         && any_uncondjump_p (p))
4736                        || (NEXT_INSN (p) == loop->end
4737                            && any_condjump_p (p))))))
4738         {
4739           rtx label = 0;
4740
4741           /* If this is a jump outside the loop, then it also doesn't
4742              matter.  Check to see if the target of this branch is on the
4743              loop->exits_labels list.  */
4744
4745           for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
4746             if (XEXP (label, 0) == JUMP_LABEL (p))
4747               break;
4748
4749           if (!label)
4750             not_every_iteration = 1;
4751         }
4752
4753       /* Note if we pass a loop latch.  If we do, then we can not clear
4754          NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
4755          a loop since a jump before the last CODE_LABEL may have started
4756          a new loop iteration.
4757
4758          Note that LOOP_TOP is only set for rotated loops and we need
4759          this check for all loops, so compare against the CODE_LABEL
4760          which immediately follows LOOP_START.  */
4761       if (JUMP_P (p)
4762           && JUMP_LABEL (p) == NEXT_INSN (loop->start))
4763         past_loop_latch = 1;
4764
4765       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4766          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4767          or not an insn is known to be executed each iteration of the
4768          loop, whether or not any iterations are known to occur.
4769
4770          Therefore, if we have just passed a label and have no more labels
4771          between here and the test insn of the loop, and we have not passed
4772          a jump to the top of the loop, then we know these insns will be
4773          executed each iteration.  */
4774
4775       if (not_every_iteration
4776           && !past_loop_latch
4777           && LABEL_P (p)
4778           && no_labels_between_p (p, loop->end))
4779         not_every_iteration = 0;
4780     }
4781 }
4782 \f
4783 static void
4784 loop_bivs_find (struct loop *loop)
4785 {
4786   struct loop_regs *regs = LOOP_REGS (loop);
4787   struct loop_ivs *ivs = LOOP_IVS (loop);
4788   /* Temporary list pointers for traversing ivs->list.  */
4789   struct iv_class *bl, **backbl;
4790
4791   ivs->list = 0;
4792
4793   for_each_insn_in_loop (loop, check_insn_for_bivs);
4794
4795   /* Scan ivs->list to remove all regs that proved not to be bivs.
4796      Make a sanity check against regs->n_times_set.  */
4797   for (backbl = &ivs->list, bl = *backbl; bl; bl = bl->next)
4798     {
4799       if (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4800           /* Above happens if register modified by subreg, etc.  */
4801           /* Make sure it is not recognized as a basic induction var: */
4802           || regs->array[bl->regno].n_times_set != bl->biv_count
4803           /* If never incremented, it is invariant that we decided not to
4804              move.  So leave it alone.  */
4805           || ! bl->incremented)
4806         {
4807           if (loop_dump_stream)
4808             fprintf (loop_dump_stream, "Biv %d: discarded, %s\n",
4809                      bl->regno,
4810                      (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4811                       ? "not induction variable"
4812                       : (! bl->incremented ? "never incremented"
4813                          : "count error")));
4814
4815           REG_IV_TYPE (ivs, bl->regno) = NOT_BASIC_INDUCT;
4816           *backbl = bl->next;
4817         }
4818       else
4819         {
4820           backbl = &bl->next;
4821
4822           if (loop_dump_stream)
4823             fprintf (loop_dump_stream, "Biv %d: verified\n", bl->regno);
4824         }
4825     }
4826 }
4827
4828
4829 /* Determine how BIVS are initialized by looking through pre-header
4830    extended basic block.  */
4831 static void
4832 loop_bivs_init_find (struct loop *loop)
4833 {
4834   struct loop_ivs *ivs = LOOP_IVS (loop);
4835   /* Temporary list pointers for traversing ivs->list.  */
4836   struct iv_class *bl;
4837   int call_seen;
4838   rtx p;
4839
4840   /* Find initial value for each biv by searching backwards from loop_start,
4841      halting at first label.  Also record any test condition.  */
4842
4843   call_seen = 0;
4844   for (p = loop->start; p && !LABEL_P (p); p = PREV_INSN (p))
4845     {
4846       rtx test;
4847
4848       note_insn = p;
4849
4850       if (CALL_P (p))
4851         call_seen = 1;
4852
4853       if (INSN_P (p))
4854         note_stores (PATTERN (p), record_initial, ivs);
4855
4856       /* Record any test of a biv that branches around the loop if no store
4857          between it and the start of loop.  We only care about tests with
4858          constants and registers and only certain of those.  */
4859       if (JUMP_P (p)
4860           && JUMP_LABEL (p) != 0
4861           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop->end)
4862           && (test = get_condition_for_loop (loop, p)) != 0
4863           && REG_P (XEXP (test, 0))
4864           && REGNO (XEXP (test, 0)) < max_reg_before_loop
4865           && (bl = REG_IV_CLASS (ivs, REGNO (XEXP (test, 0)))) != 0
4866           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop->start)
4867           && bl->init_insn == 0)
4868         {
4869           /* If an NE test, we have an initial value!  */
4870           if (GET_CODE (test) == NE)
4871             {
4872               bl->init_insn = p;
4873               bl->init_set = gen_rtx_SET (VOIDmode,
4874                                           XEXP (test, 0), XEXP (test, 1));
4875             }
4876           else
4877             bl->initial_test = test;
4878         }
4879     }
4880 }
4881
4882
4883 /* Look at the each biv and see if we can say anything better about its
4884    initial value from any initializing insns set up above.  (This is done
4885    in two passes to avoid missing SETs in a PARALLEL.)  */
4886 static void
4887 loop_bivs_check (struct loop *loop)
4888 {
4889   struct loop_ivs *ivs = LOOP_IVS (loop);
4890   /* Temporary list pointers for traversing ivs->list.  */
4891   struct iv_class *bl;
4892   struct iv_class **backbl;
4893
4894   for (backbl = &ivs->list; (bl = *backbl); backbl = &bl->next)
4895     {
4896       rtx src;
4897       rtx note;
4898
4899       if (! bl->init_insn)
4900         continue;
4901
4902       /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4903          is a constant, use the value of that.  */
4904       if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4905            && CONSTANT_P (XEXP (note, 0)))
4906           || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4907               && CONSTANT_P (XEXP (note, 0))))
4908         src = XEXP (note, 0);
4909       else
4910         src = SET_SRC (bl->init_set);
4911
4912       if (loop_dump_stream)
4913         fprintf (loop_dump_stream,
4914                  "Biv %d: initialized at insn %d: initial value ",
4915                  bl->regno, INSN_UID (bl->init_insn));
4916
4917       if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4918            || GET_MODE (src) == VOIDmode)
4919           && valid_initial_value_p (src, bl->init_insn,
4920                                     LOOP_INFO (loop)->pre_header_has_call,
4921                                     loop->start))
4922         {
4923           bl->initial_value = src;
4924
4925           if (loop_dump_stream)
4926             {
4927               print_simple_rtl (loop_dump_stream, src);
4928               fputc ('\n', loop_dump_stream);
4929             }
4930         }
4931       /* If we can't make it a giv,
4932          let biv keep initial value of "itself".  */
4933       else if (loop_dump_stream)
4934         fprintf (loop_dump_stream, "is complex\n");
4935     }
4936 }
4937
4938
4939 /* Search the loop for general induction variables.  */
4940
4941 static void
4942 loop_givs_find (struct loop* loop)
4943 {
4944   for_each_insn_in_loop (loop, check_insn_for_givs);
4945 }
4946
4947
4948 /* For each giv for which we still don't know whether or not it is
4949    replaceable, check to see if it is replaceable because its final value
4950    can be calculated.  */
4951
4952 static void
4953 loop_givs_check (struct loop *loop)
4954 {
4955   struct loop_ivs *ivs = LOOP_IVS (loop);
4956   struct iv_class *bl;
4957
4958   for (bl = ivs->list; bl; bl = bl->next)
4959     {
4960       struct induction *v;
4961
4962       for (v = bl->giv; v; v = v->next_iv)
4963         if (! v->replaceable && ! v->not_replaceable)
4964           check_final_value (loop, v);
4965     }
4966 }
4967
4968 /* Try to generate the simplest rtx for the expression
4969    (PLUS (MULT mult1 mult2) add1).  This is used to calculate the initial
4970    value of giv's.  */
4971
4972 static rtx
4973 fold_rtx_mult_add (rtx mult1, rtx mult2, rtx add1, enum machine_mode mode)
4974 {
4975   rtx temp, mult_res;
4976   rtx result;
4977
4978   /* The modes must all be the same.  This should always be true.  For now,
4979      check to make sure.  */
4980   gcc_assert (GET_MODE (mult1) == mode || GET_MODE (mult1) == VOIDmode);
4981   gcc_assert (GET_MODE (mult2) == mode || GET_MODE (mult2) == VOIDmode);
4982   gcc_assert (GET_MODE (add1) == mode || GET_MODE (add1) == VOIDmode);
4983
4984   /* Ensure that if at least one of mult1/mult2 are constant, then mult2
4985      will be a constant.  */
4986   if (GET_CODE (mult1) == CONST_INT)
4987     {
4988       temp = mult2;
4989       mult2 = mult1;
4990       mult1 = temp;
4991     }
4992
4993   mult_res = simplify_binary_operation (MULT, mode, mult1, mult2);
4994   if (! mult_res)
4995     mult_res = gen_rtx_MULT (mode, mult1, mult2);
4996
4997   /* Again, put the constant second.  */
4998   if (GET_CODE (add1) == CONST_INT)
4999     {
5000       temp = add1;
5001       add1 = mult_res;
5002       mult_res = temp;
5003     }
5004
5005   result = simplify_binary_operation (PLUS, mode, add1, mult_res);
5006   if (! result)
5007     result = gen_rtx_PLUS (mode, add1, mult_res);
5008
5009   return result;
5010 }
5011
5012 /* Searches the list of induction struct's for the biv BL, to try to calculate
5013    the total increment value for one iteration of the loop as a constant.
5014
5015    Returns the increment value as an rtx, simplified as much as possible,
5016    if it can be calculated.  Otherwise, returns 0.  */
5017
5018 static rtx
5019 biv_total_increment (const struct iv_class *bl)
5020 {
5021   struct induction *v;
5022   rtx result;
5023
5024   /* For increment, must check every instruction that sets it.  Each
5025      instruction must be executed only once each time through the loop.
5026      To verify this, we check that the insn is always executed, and that
5027      there are no backward branches after the insn that branch to before it.
5028      Also, the insn must have a mult_val of one (to make sure it really is
5029      an increment).  */
5030
5031   result = const0_rtx;
5032   for (v = bl->biv; v; v = v->next_iv)
5033     {
5034       if (v->always_computable && v->mult_val == const1_rtx
5035           && ! v->maybe_multiple
5036           && SCALAR_INT_MODE_P (v->mode))
5037         {
5038           /* If we have already counted it, skip it.  */
5039           if (v->same)
5040             continue;
5041
5042           result = fold_rtx_mult_add (result, const1_rtx, v->add_val, v->mode);
5043         }
5044       else
5045         return 0;
5046     }
5047
5048   return result;
5049 }
5050
5051 /* Try to prove that the register is dead after the loop exits.  Trace every
5052    loop exit looking for an insn that will always be executed, which sets
5053    the register to some value, and appears before the first use of the register
5054    is found.  If successful, then return 1, otherwise return 0.  */
5055
5056 /* ?? Could be made more intelligent in the handling of jumps, so that
5057    it can search past if statements and other similar structures.  */
5058
5059 static int
5060 reg_dead_after_loop (const struct loop *loop, rtx reg)
5061 {
5062   rtx insn, label;
5063   int jump_count = 0;
5064   int label_count = 0;
5065
5066   /* In addition to checking all exits of this loop, we must also check
5067      all exits of inner nested loops that would exit this loop.  We don't
5068      have any way to identify those, so we just give up if there are any
5069      such inner loop exits.  */
5070
5071   for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
5072     label_count++;
5073
5074   if (label_count != loop->exit_count)
5075     return 0;
5076
5077   /* HACK: Must also search the loop fall through exit, create a label_ref
5078      here which points to the loop->end, and append the loop_number_exit_labels
5079      list to it.  */
5080   label = gen_rtx_LABEL_REF (Pmode, loop->end);
5081   LABEL_NEXTREF (label) = loop->exit_labels;
5082
5083   for (; label; label = LABEL_NEXTREF (label))
5084     {
5085       /* Succeed if find an insn which sets the biv or if reach end of
5086          function.  Fail if find an insn that uses the biv, or if come to
5087          a conditional jump.  */
5088
5089       insn = NEXT_INSN (XEXP (label, 0));
5090       while (insn)
5091         {
5092           if (INSN_P (insn))
5093             {
5094               rtx set, note;
5095
5096               if (reg_referenced_p (reg, PATTERN (insn)))
5097                 return 0;
5098
5099               note = find_reg_equal_equiv_note (insn);
5100               if (note && reg_overlap_mentioned_p (reg, XEXP (note, 0)))
5101                 return 0;
5102
5103               set = single_set (insn);
5104               if (set && rtx_equal_p (SET_DEST (set), reg))
5105                 break;
5106
5107               if (JUMP_P (insn))
5108                 {
5109                   if (GET_CODE (PATTERN (insn)) == RETURN)
5110                     break;
5111                   else if (!any_uncondjump_p (insn)
5112                            /* Prevent infinite loop following infinite loops.  */
5113                            || jump_count++ > 20)
5114                     return 0;
5115                   else
5116                     insn = JUMP_LABEL (insn);
5117                 }
5118             }
5119
5120           insn = NEXT_INSN (insn);
5121         }
5122     }
5123
5124   /* Success, the register is dead on all loop exits.  */
5125   return 1;
5126 }
5127
5128 /* Try to calculate the final value of the biv, the value it will have at
5129    the end of the loop.  If we can do it, return that value.  */
5130
5131 static rtx
5132 final_biv_value (const struct loop *loop, struct iv_class *bl)
5133 {
5134   unsigned HOST_WIDE_INT n_iterations = LOOP_INFO (loop)->n_iterations;
5135   rtx increment, tem;
5136
5137   /* ??? This only works for MODE_INT biv's.  Reject all others for now.  */
5138
5139   if (GET_MODE_CLASS (bl->biv->mode) != MODE_INT)
5140     return 0;
5141
5142   /* The final value for reversed bivs must be calculated differently than
5143      for ordinary bivs.  In this case, there is already an insn after the
5144      loop which sets this biv's final value (if necessary), and there are
5145      no other loop exits, so we can return any value.  */
5146   if (bl->reversed)
5147     {
5148       if (loop_dump_stream)
5149         fprintf (loop_dump_stream,
5150                  "Final biv value for %d, reversed biv.\n", bl->regno);
5151
5152       return const0_rtx;
5153     }
5154
5155   /* Try to calculate the final value as initial value + (number of iterations
5156      * increment).  For this to work, increment must be invariant, the only
5157      exit from the loop must be the fall through at the bottom (otherwise
5158      it may not have its final value when the loop exits), and the initial
5159      value of the biv must be invariant.  */
5160
5161   if (n_iterations != 0
5162       && ! loop->exit_count
5163       && loop_invariant_p (loop, bl->initial_value))
5164     {
5165       increment = biv_total_increment (bl);
5166
5167       if (increment && loop_invariant_p (loop, increment))
5168         {
5169           /* Can calculate the loop exit value, emit insns after loop
5170              end to calculate this value into a temporary register in
5171              case it is needed later.  */
5172
5173           tem = gen_reg_rtx (bl->biv->mode);
5174           record_base_value (REGNO (tem), bl->biv->add_val, 0);
5175           loop_iv_add_mult_sink (loop, increment, GEN_INT (n_iterations),
5176                                  bl->initial_value, tem);
5177
5178           if (loop_dump_stream)
5179             fprintf (loop_dump_stream,
5180                      "Final biv value for %d, calculated.\n", bl->regno);
5181
5182           return tem;
5183         }
5184     }
5185
5186   /* Check to see if the biv is dead at all loop exits.  */
5187   if (reg_dead_after_loop (loop, bl->biv->src_reg))
5188     {
5189       if (loop_dump_stream)
5190         fprintf (loop_dump_stream,
5191                  "Final biv value for %d, biv dead after loop exit.\n",
5192                  bl->regno);
5193
5194       return const0_rtx;
5195     }
5196
5197   return 0;
5198 }
5199
5200 /* Return nonzero if it is possible to eliminate the biv BL provided
5201    all givs are reduced.  This is possible if either the reg is not
5202    used outside the loop, or we can compute what its final value will
5203    be.  */
5204
5205 static int
5206 loop_biv_eliminable_p (struct loop *loop, struct iv_class *bl,
5207                        int threshold, int insn_count)
5208 {
5209   /* For architectures with a decrement_and_branch_until_zero insn,
5210      don't do this if we put a REG_NONNEG note on the endtest for this
5211      biv.  */
5212
5213 #ifdef HAVE_decrement_and_branch_until_zero
5214   if (bl->nonneg)
5215     {
5216       if (loop_dump_stream)
5217         fprintf (loop_dump_stream,
5218                  "Cannot eliminate nonneg biv %d.\n", bl->regno);
5219       return 0;
5220     }
5221 #endif
5222
5223   /* Check that biv is used outside loop or if it has a final value.
5224      Compare against bl->init_insn rather than loop->start.  We aren't
5225      concerned with any uses of the biv between init_insn and
5226      loop->start since these won't be affected by the value of the biv
5227      elsewhere in the function, so long as init_insn doesn't use the
5228      biv itself.  */
5229
5230   if ((REGNO_LAST_LUID (bl->regno) < INSN_LUID (loop->end)
5231        && bl->init_insn
5232        && INSN_UID (bl->init_insn) < max_uid_for_loop
5233        && REGNO_FIRST_LUID (bl->regno) >= INSN_LUID (bl->init_insn)
5234        && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
5235       || (bl->final_value = final_biv_value (loop, bl)))
5236     return maybe_eliminate_biv (loop, bl, 0, threshold, insn_count);
5237
5238   if (loop_dump_stream)
5239     {
5240       fprintf (loop_dump_stream,
5241                "Cannot eliminate biv %d.\n",
5242                bl->regno);
5243       fprintf (loop_dump_stream,
5244                "First use: insn %d, last use: insn %d.\n",
5245                REGNO_FIRST_UID (bl->regno),
5246                REGNO_LAST_UID (bl->regno));
5247     }
5248   return 0;
5249 }
5250
5251
5252 /* Reduce each giv of BL that we have decided to reduce.  */
5253
5254 static void
5255 loop_givs_reduce (struct loop *loop, struct iv_class *bl)
5256 {
5257   struct induction *v;
5258
5259   for (v = bl->giv; v; v = v->next_iv)
5260     {
5261       struct induction *tv;
5262       if (! v->ignore && v->same == 0)
5263         {
5264           int auto_inc_opt = 0;
5265
5266           /* If the code for derived givs immediately below has already
5267              allocated a new_reg, we must keep it.  */
5268           if (! v->new_reg)
5269             v->new_reg = gen_reg_rtx (v->mode);
5270
5271 #ifdef AUTO_INC_DEC
5272           /* If the target has auto-increment addressing modes, and
5273              this is an address giv, then try to put the increment
5274              immediately after its use, so that flow can create an
5275              auto-increment addressing mode.  */
5276           /* Don't do this for loops entered at the bottom, to avoid
5277              this invalid transformation:
5278                 jmp L;          ->          jmp L;
5279              TOP:                       TOP:
5280                 use giv                     use giv
5281              L:                             inc giv
5282                 inc biv                 L:
5283                 test biv                    test giv
5284                 cbr TOP                     cbr TOP
5285           */
5286           if (v->giv_type == DEST_ADDR && bl->biv_count == 1
5287               && bl->biv->always_executed && ! bl->biv->maybe_multiple
5288               /* We don't handle reversed biv's because bl->biv->insn
5289                  does not have a valid INSN_LUID.  */
5290               && ! bl->reversed
5291               && v->always_executed && ! v->maybe_multiple
5292               && INSN_UID (v->insn) < max_uid_for_loop
5293               && !loop->top)    
5294             {
5295               /* If other giv's have been combined with this one, then
5296                  this will work only if all uses of the other giv's occur
5297                  before this giv's insn.  This is difficult to check.
5298
5299                  We simplify this by looking for the common case where
5300                  there is one DEST_REG giv, and this giv's insn is the
5301                  last use of the dest_reg of that DEST_REG giv.  If the
5302                  increment occurs after the address giv, then we can
5303                  perform the optimization.  (Otherwise, the increment
5304                  would have to go before other_giv, and we would not be
5305                  able to combine it with the address giv to get an
5306                  auto-inc address.)  */
5307               if (v->combined_with)
5308                 {
5309                   struct induction *other_giv = 0;
5310
5311                   for (tv = bl->giv; tv; tv = tv->next_iv)
5312                     if (tv->same == v)
5313                       {
5314                         if (other_giv)
5315                           break;
5316                         else
5317                           other_giv = tv;
5318                       }
5319                   if (! tv && other_giv
5320                       && REGNO (other_giv->dest_reg) < max_reg_before_loop
5321                       && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
5322                           == INSN_UID (v->insn))
5323                       && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
5324                     auto_inc_opt = 1;
5325                 }
5326               /* Check for case where increment is before the address
5327                  giv.  Do this test in "loop order".  */
5328               else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
5329                         && (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
5330                             || (INSN_LUID (bl->biv->insn)
5331                                 > INSN_LUID (loop->scan_start))))
5332                        || (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
5333                            && (INSN_LUID (loop->scan_start)
5334                                < INSN_LUID (bl->biv->insn))))
5335                 auto_inc_opt = -1;
5336               else
5337                 auto_inc_opt = 1;
5338
5339 #ifdef HAVE_cc0
5340               {
5341                 rtx prev;
5342
5343                 /* We can't put an insn immediately after one setting
5344                    cc0, or immediately before one using cc0.  */
5345                 if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
5346                     || (auto_inc_opt == -1
5347                         && (prev = prev_nonnote_insn (v->insn)) != 0
5348                         && INSN_P (prev)
5349                         && sets_cc0_p (PATTERN (prev))))
5350                   auto_inc_opt = 0;
5351               }
5352 #endif
5353
5354               if (auto_inc_opt)
5355                 v->auto_inc_opt = 1;
5356             }
5357 #endif
5358
5359           /* For each place where the biv is incremented, add an insn
5360              to increment the new, reduced reg for the giv.  */
5361           for (tv = bl->biv; tv; tv = tv->next_iv)
5362             {
5363               rtx insert_before;
5364
5365               /* Skip if location is the same as a previous one.  */
5366               if (tv->same)
5367                 continue;
5368               if (! auto_inc_opt)
5369                 insert_before = NEXT_INSN (tv->insn);
5370               else if (auto_inc_opt == 1)
5371                 insert_before = NEXT_INSN (v->insn);
5372               else
5373                 insert_before = v->insn;
5374
5375               if (tv->mult_val == const1_rtx)
5376                 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
5377                                               v->new_reg, v->new_reg,
5378                                               0, insert_before);
5379               else /* tv->mult_val == const0_rtx */
5380                 /* A multiply is acceptable here
5381                    since this is presumed to be seldom executed.  */
5382                 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
5383                                               v->add_val, v->new_reg,
5384                                               0, insert_before);
5385             }
5386
5387           /* Add code at loop start to initialize giv's reduced reg.  */
5388
5389           loop_iv_add_mult_hoist (loop,
5390                                   extend_value_for_giv (v, bl->initial_value),
5391                                   v->mult_val, v->add_val, v->new_reg);
5392         }
5393     }
5394 }
5395
5396
5397 /* Check for givs whose first use is their definition and whose
5398    last use is the definition of another giv.  If so, it is likely
5399    dead and should not be used to derive another giv nor to
5400    eliminate a biv.  */
5401
5402 static void
5403 loop_givs_dead_check (struct loop *loop ATTRIBUTE_UNUSED, struct iv_class *bl)
5404 {
5405   struct induction *v;
5406
5407   for (v = bl->giv; v; v = v->next_iv)
5408     {
5409       if (v->ignore
5410           || (v->same && v->same->ignore))
5411         continue;
5412
5413       if (v->giv_type == DEST_REG
5414           && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
5415         {
5416           struct induction *v1;
5417
5418           for (v1 = bl->giv; v1; v1 = v1->next_iv)
5419             if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
5420               v->maybe_dead = 1;
5421         }
5422     }
5423 }
5424
5425
5426 static void
5427 loop_givs_rescan (struct loop *loop, struct iv_class *bl, rtx *reg_map)
5428 {
5429   struct induction *v;
5430
5431   for (v = bl->giv; v; v = v->next_iv)
5432     {
5433       if (v->same && v->same->ignore)
5434         v->ignore = 1;
5435
5436       if (v->ignore)
5437         continue;
5438
5439       /* Update expression if this was combined, in case other giv was
5440          replaced.  */
5441       if (v->same)
5442         v->new_reg = replace_rtx (v->new_reg,
5443                                   v->same->dest_reg, v->same->new_reg);
5444
5445       /* See if this register is known to be a pointer to something.  If
5446          so, see if we can find the alignment.  First see if there is a
5447          destination register that is a pointer.  If so, this shares the
5448          alignment too.  Next see if we can deduce anything from the
5449          computational information.  If not, and this is a DEST_ADDR
5450          giv, at least we know that it's a pointer, though we don't know
5451          the alignment.  */
5452       if (REG_P (v->new_reg)
5453           && v->giv_type == DEST_REG
5454           && REG_POINTER (v->dest_reg))
5455         mark_reg_pointer (v->new_reg,
5456                           REGNO_POINTER_ALIGN (REGNO (v->dest_reg)));
5457       else if (REG_P (v->new_reg)
5458                && REG_POINTER (v->src_reg))
5459         {
5460           unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->src_reg));
5461
5462           if (align == 0
5463               || GET_CODE (v->add_val) != CONST_INT
5464               || INTVAL (v->add_val) % (align / BITS_PER_UNIT) != 0)
5465             align = 0;
5466
5467           mark_reg_pointer (v->new_reg, align);
5468         }
5469       else if (REG_P (v->new_reg)
5470                && REG_P (v->add_val)
5471                && REG_POINTER (v->add_val))
5472         {
5473           unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->add_val));
5474
5475           if (align == 0 || GET_CODE (v->mult_val) != CONST_INT
5476               || INTVAL (v->mult_val) % (align / BITS_PER_UNIT) != 0)
5477             align = 0;
5478
5479           mark_reg_pointer (v->new_reg, align);
5480         }
5481       else if (REG_P (v->new_reg) && v->giv_type == DEST_ADDR)
5482         mark_reg_pointer (v->new_reg, 0);
5483
5484       if (v->giv_type == DEST_ADDR)
5485         {
5486           /* Store reduced reg as the address in the memref where we found
5487              this giv.  */
5488           if (validate_change_maybe_volatile (v->insn, v->location,
5489                                               v->new_reg))
5490             /* Yay, it worked!  */;
5491           /* Not replaceable; emit an insn to set the original
5492              giv reg from the reduced giv.  */
5493           else if (REG_P (*v->location))
5494             loop_insn_emit_before (loop, 0, v->insn,
5495                                    gen_move_insn (*v->location,
5496                                                   v->new_reg));
5497           else if (GET_CODE (*v->location) == PLUS
5498                    && REG_P (XEXP (*v->location, 0))
5499                    && CONSTANT_P (XEXP (*v->location, 1)))
5500             loop_insn_emit_before (loop, 0, v->insn,
5501                                    gen_move_insn (XEXP (*v->location, 0),
5502                                                   gen_rtx_MINUS
5503                                                   (GET_MODE (*v->location),
5504                                                    v->new_reg,
5505                                                    XEXP (*v->location, 1))));
5506           else
5507             {
5508               /* If it wasn't a reg, create a pseudo and use that.  */
5509               rtx reg, seq;
5510               start_sequence ();
5511               reg = force_reg (v->mode, *v->location);
5512               seq = get_insns ();
5513               end_sequence ();
5514               loop_insn_emit_before (loop, 0, v->insn, seq);
5515               if (!validate_change_maybe_volatile (v->insn, v->location, reg))
5516                 gcc_unreachable ();
5517             }
5518         }
5519       else if (v->replaceable)
5520         {
5521           reg_map[REGNO (v->dest_reg)] = v->new_reg;
5522         }
5523       else
5524         {
5525           rtx original_insn = v->insn;
5526           rtx note;
5527
5528           /* Not replaceable; emit an insn to set the original giv reg from
5529              the reduced giv, same as above.  */
5530           v->insn = loop_insn_emit_after (loop, 0, original_insn,
5531                                           gen_move_insn (v->dest_reg,
5532                                                          v->new_reg));
5533
5534           /* The original insn may have a REG_EQUAL note.  This note is
5535              now incorrect and may result in invalid substitutions later.
5536              The original insn is dead, but may be part of a libcall
5537              sequence, which doesn't seem worth the bother of handling.  */
5538           note = find_reg_note (original_insn, REG_EQUAL, NULL_RTX);
5539           if (note)
5540             remove_note (original_insn, note);
5541         }
5542
5543       /* When a loop is reversed, givs which depend on the reversed
5544          biv, and which are live outside the loop, must be set to their
5545          correct final value.  This insn is only needed if the giv is
5546          not replaceable.  The correct final value is the same as the
5547          value that the giv starts the reversed loop with.  */
5548       if (bl->reversed && ! v->replaceable)
5549         loop_iv_add_mult_sink (loop,
5550                                extend_value_for_giv (v, bl->initial_value),
5551                                v->mult_val, v->add_val, v->dest_reg);
5552       else if (v->final_value)
5553         loop_insn_sink_or_swim (loop,
5554                                 gen_load_of_final_value (v->dest_reg,
5555                                                          v->final_value));
5556
5557       if (loop_dump_stream)
5558         {
5559           fprintf (loop_dump_stream, "giv at %d reduced to ",
5560                    INSN_UID (v->insn));
5561           print_simple_rtl (loop_dump_stream, v->new_reg);
5562           fprintf (loop_dump_stream, "\n");
5563         }
5564     }
5565 }
5566
5567
5568 static int
5569 loop_giv_reduce_benefit (struct loop *loop ATTRIBUTE_UNUSED,
5570                          struct iv_class *bl, struct induction *v,
5571                          rtx test_reg)
5572 {
5573   int add_cost;
5574   int benefit;
5575
5576   benefit = v->benefit;
5577   PUT_MODE (test_reg, v->mode);
5578   add_cost = iv_add_mult_cost (bl->biv->add_val, v->mult_val,
5579                                test_reg, test_reg);
5580
5581   /* Reduce benefit if not replaceable, since we will insert a
5582      move-insn to replace the insn that calculates this giv.  Don't do
5583      this unless the giv is a user variable, since it will often be
5584      marked non-replaceable because of the duplication of the exit
5585      code outside the loop.  In such a case, the copies we insert are
5586      dead and will be deleted.  So they don't have a cost.  Similar
5587      situations exist.  */
5588   /* ??? The new final_[bg]iv_value code does a much better job of
5589      finding replaceable giv's, and hence this code may no longer be
5590      necessary.  */
5591   if (! v->replaceable && ! bl->eliminable
5592       && REG_USERVAR_P (v->dest_reg))
5593     benefit -= copy_cost;
5594
5595   /* Decrease the benefit to count the add-insns that we will insert
5596      to increment the reduced reg for the giv.  ??? This can
5597      overestimate the run-time cost of the additional insns, e.g. if
5598      there are multiple basic blocks that increment the biv, but only
5599      one of these blocks is executed during each iteration.  There is
5600      no good way to detect cases like this with the current structure
5601      of the loop optimizer.  This code is more accurate for
5602      determining code size than run-time benefits.  */
5603   benefit -= add_cost * bl->biv_count;
5604
5605   /* Decide whether to strength-reduce this giv or to leave the code
5606      unchanged (recompute it from the biv each time it is used).  This
5607      decision can be made independently for each giv.  */
5608
5609 #ifdef AUTO_INC_DEC
5610   /* Attempt to guess whether autoincrement will handle some of the
5611      new add insns; if so, increase BENEFIT (undo the subtraction of
5612      add_cost that was done above).  */
5613   if (v->giv_type == DEST_ADDR
5614       /* Increasing the benefit is risky, since this is only a guess.
5615          Avoid increasing register pressure in cases where there would
5616          be no other benefit from reducing this giv.  */
5617       && benefit > 0
5618       && GET_CODE (v->mult_val) == CONST_INT)
5619     {
5620       int size = GET_MODE_SIZE (GET_MODE (v->mem));
5621
5622       if (HAVE_POST_INCREMENT
5623           && INTVAL (v->mult_val) == size)
5624         benefit += add_cost * bl->biv_count;
5625       else if (HAVE_PRE_INCREMENT
5626                && INTVAL (v->mult_val) == size)
5627         benefit += add_cost * bl->biv_count;
5628       else if (HAVE_POST_DECREMENT
5629                && -INTVAL (v->mult_val) == size)
5630         benefit += add_cost * bl->biv_count;
5631       else if (HAVE_PRE_DECREMENT
5632                && -INTVAL (v->mult_val) == size)
5633         benefit += add_cost * bl->biv_count;
5634     }
5635 #endif
5636
5637   return benefit;
5638 }
5639
5640
5641 /* Free IV structures for LOOP.  */
5642
5643 static void
5644 loop_ivs_free (struct loop *loop)
5645 {
5646   struct loop_ivs *ivs = LOOP_IVS (loop);
5647   struct iv_class *iv = ivs->list;
5648
5649   free (ivs->regs);
5650
5651   while (iv)
5652     {
5653       struct iv_class *next = iv->next;
5654       struct induction *induction;
5655       struct induction *next_induction;
5656
5657       for (induction = iv->biv; induction; induction = next_induction)
5658         {
5659           next_induction = induction->next_iv;
5660           free (induction);
5661         }
5662       for (induction = iv->giv; induction; induction = next_induction)
5663         {
5664           next_induction = induction->next_iv;
5665           free (induction);
5666         }
5667
5668       free (iv);
5669       iv = next;
5670     }
5671 }
5672
5673 /* Look back before LOOP->START for the insn that sets REG and return
5674    the equivalent constant if there is a REG_EQUAL note otherwise just
5675    the SET_SRC of REG.  */
5676
5677 static rtx
5678 loop_find_equiv_value (const struct loop *loop, rtx reg)
5679 {
5680   rtx loop_start = loop->start;
5681   rtx insn, set;
5682   rtx ret;
5683
5684   ret = reg;
5685   for (insn = PREV_INSN (loop_start); insn; insn = PREV_INSN (insn))
5686     {
5687       if (LABEL_P (insn))
5688         break;
5689
5690       else if (INSN_P (insn) && reg_set_p (reg, insn))
5691         {
5692           /* We found the last insn before the loop that sets the register.
5693              If it sets the entire register, and has a REG_EQUAL note,
5694              then use the value of the REG_EQUAL note.  */
5695           if ((set = single_set (insn))
5696               && (SET_DEST (set) == reg))
5697             {
5698               rtx note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
5699
5700               /* Only use the REG_EQUAL note if it is a constant.
5701                  Other things, divide in particular, will cause
5702                  problems later if we use them.  */
5703               if (note && GET_CODE (XEXP (note, 0)) != EXPR_LIST
5704                   && CONSTANT_P (XEXP (note, 0)))
5705                 ret = XEXP (note, 0);
5706               else
5707                 ret = SET_SRC (set);
5708
5709               /* We cannot do this if it changes between the
5710                  assignment and loop start though.  */
5711               if (modified_between_p (ret, insn, loop_start))
5712                 ret = reg;
5713             }
5714           break;
5715         }
5716     }
5717   return ret;
5718 }
5719
5720 /* Find and return register term common to both expressions OP0 and
5721    OP1 or NULL_RTX if no such term exists.  Each expression must be a
5722    REG or a PLUS of a REG.  */
5723
5724 static rtx
5725 find_common_reg_term (rtx op0, rtx op1)
5726 {
5727   if ((REG_P (op0) || GET_CODE (op0) == PLUS)
5728       && (REG_P (op1) || GET_CODE (op1) == PLUS))
5729     {
5730       rtx op00;
5731       rtx op01;
5732       rtx op10;
5733       rtx op11;
5734
5735       if (GET_CODE (op0) == PLUS)
5736         op01 = XEXP (op0, 1), op00 = XEXP (op0, 0);
5737       else
5738         op01 = const0_rtx, op00 = op0;
5739
5740       if (GET_CODE (op1) == PLUS)
5741         op11 = XEXP (op1, 1), op10 = XEXP (op1, 0);
5742       else
5743         op11 = const0_rtx, op10 = op1;
5744
5745       /* Find and return common register term if present.  */
5746       if (REG_P (op00) && (op00 == op10 || op00 == op11))
5747         return op00;
5748       else if (REG_P (op01) && (op01 == op10 || op01 == op11))
5749         return op01;
5750     }
5751
5752   /* No common register term found.  */
5753   return NULL_RTX;
5754 }
5755
5756 /* Determine the loop iterator and calculate the number of loop
5757    iterations.  Returns the exact number of loop iterations if it can
5758    be calculated, otherwise returns zero.  */
5759
5760 static unsigned HOST_WIDE_INT
5761 loop_iterations (struct loop *loop)
5762 {
5763   struct loop_info *loop_info = LOOP_INFO (loop);
5764   struct loop_ivs *ivs = LOOP_IVS (loop);
5765   rtx comparison, comparison_value;
5766   rtx iteration_var, initial_value, increment, final_value;
5767   enum rtx_code comparison_code;
5768   HOST_WIDE_INT inc;
5769   unsigned HOST_WIDE_INT abs_inc;
5770   unsigned HOST_WIDE_INT abs_diff;
5771   int off_by_one;
5772   int increment_dir;
5773   int unsigned_p, compare_dir, final_larger;
5774   rtx last_loop_insn;
5775   struct iv_class *bl;
5776
5777   loop_info->n_iterations = 0;
5778   loop_info->initial_value = 0;
5779   loop_info->initial_equiv_value = 0;
5780   loop_info->comparison_value = 0;
5781   loop_info->final_value = 0;
5782   loop_info->final_equiv_value = 0;
5783   loop_info->increment = 0;
5784   loop_info->iteration_var = 0;
5785   loop_info->iv = 0;
5786
5787   /* We used to use prev_nonnote_insn here, but that fails because it might
5788      accidentally get the branch for a contained loop if the branch for this
5789      loop was deleted.  We can only trust branches immediately before the
5790      loop_end.  */
5791   last_loop_insn = PREV_INSN (loop->end);
5792
5793   /* ??? We should probably try harder to find the jump insn
5794      at the end of the loop.  The following code assumes that
5795      the last loop insn is a jump to the top of the loop.  */
5796   if (!JUMP_P (last_loop_insn))
5797     {
5798       if (loop_dump_stream)
5799         fprintf (loop_dump_stream,
5800                  "Loop iterations: No final conditional branch found.\n");
5801       return 0;
5802     }
5803
5804   /* If there is a more than a single jump to the top of the loop
5805      we cannot (easily) determine the iteration count.  */
5806   if (LABEL_NUSES (JUMP_LABEL (last_loop_insn)) > 1)
5807     {
5808       if (loop_dump_stream)
5809         fprintf (loop_dump_stream,
5810                  "Loop iterations: Loop has multiple back edges.\n");
5811       return 0;
5812     }
5813
5814   /* Find the iteration variable.  If the last insn is a conditional
5815      branch, and the insn before tests a register value, make that the
5816      iteration variable.  */
5817
5818   comparison = get_condition_for_loop (loop, last_loop_insn);
5819   if (comparison == 0)
5820     {
5821       if (loop_dump_stream)
5822         fprintf (loop_dump_stream,
5823                  "Loop iterations: No final comparison found.\n");
5824       return 0;
5825     }
5826
5827   /* ??? Get_condition may switch position of induction variable and
5828      invariant register when it canonicalizes the comparison.  */
5829
5830   comparison_code = GET_CODE (comparison);
5831   iteration_var = XEXP (comparison, 0);
5832   comparison_value = XEXP (comparison, 1);
5833
5834   if (!REG_P (iteration_var))
5835     {
5836       if (loop_dump_stream)
5837         fprintf (loop_dump_stream,
5838                  "Loop iterations: Comparison not against register.\n");
5839       return 0;
5840     }
5841
5842   /* The only new registers that are created before loop iterations
5843      are givs made from biv increments or registers created by
5844      load_mems.  In the latter case, it is possible that try_copy_prop
5845      will propagate a new pseudo into the old iteration register but
5846      this will be marked by having the REG_USERVAR_P bit set.  */
5847
5848   gcc_assert ((unsigned) REGNO (iteration_var) < ivs->n_regs
5849               || REG_USERVAR_P (iteration_var));
5850
5851   /* Determine the initial value of the iteration variable, and the amount
5852      that it is incremented each loop.  Use the tables constructed by
5853      the strength reduction pass to calculate these values.  */
5854
5855   /* Clear the result values, in case no answer can be found.  */
5856   initial_value = 0;
5857   increment = 0;
5858
5859   /* The iteration variable can be either a giv or a biv.  Check to see
5860      which it is, and compute the variable's initial value, and increment
5861      value if possible.  */
5862
5863   /* If this is a new register, can't handle it since we don't have any
5864      reg_iv_type entry for it.  */
5865   if ((unsigned) REGNO (iteration_var) >= ivs->n_regs)
5866     {
5867       if (loop_dump_stream)
5868         fprintf (loop_dump_stream,
5869                  "Loop iterations: No reg_iv_type entry for iteration var.\n");
5870       return 0;
5871     }
5872
5873   /* Reject iteration variables larger than the host wide int size, since they
5874      could result in a number of iterations greater than the range of our
5875      `unsigned HOST_WIDE_INT' variable loop_info->n_iterations.  */
5876   else if ((GET_MODE_BITSIZE (GET_MODE (iteration_var))
5877             > HOST_BITS_PER_WIDE_INT))
5878     {
5879       if (loop_dump_stream)
5880         fprintf (loop_dump_stream,
5881                  "Loop iterations: Iteration var rejected because mode too large.\n");
5882       return 0;
5883     }
5884   else if (GET_MODE_CLASS (GET_MODE (iteration_var)) != MODE_INT)
5885     {
5886       if (loop_dump_stream)
5887         fprintf (loop_dump_stream,
5888                  "Loop iterations: Iteration var not an integer.\n");
5889       return 0;
5890     }
5891
5892   /* Try swapping the comparison to identify a suitable iv.  */
5893   if (REG_IV_TYPE (ivs, REGNO (iteration_var)) != BASIC_INDUCT
5894       && REG_IV_TYPE (ivs, REGNO (iteration_var)) != GENERAL_INDUCT
5895       && REG_P (comparison_value)
5896       && REGNO (comparison_value) < ivs->n_regs)
5897     {
5898       rtx temp = comparison_value;
5899       comparison_code = swap_condition (comparison_code);
5900       comparison_value = iteration_var;
5901       iteration_var = temp;
5902     }
5903
5904   if (REG_IV_TYPE (ivs, REGNO (iteration_var)) == BASIC_INDUCT)
5905     {
5906       gcc_assert (REGNO (iteration_var) < ivs->n_regs);
5907
5908       /* Grab initial value, only useful if it is a constant.  */
5909       bl = REG_IV_CLASS (ivs, REGNO (iteration_var));
5910       initial_value = bl->initial_value;
5911       if (!bl->biv->always_executed || bl->biv->maybe_multiple)
5912         {
5913           if (loop_dump_stream)
5914             fprintf (loop_dump_stream,
5915                      "Loop iterations: Basic induction var not set once in each iteration.\n");
5916           return 0;
5917         }
5918
5919       increment = biv_total_increment (bl);
5920     }
5921   else if (REG_IV_TYPE (ivs, REGNO (iteration_var)) == GENERAL_INDUCT)
5922     {
5923       HOST_WIDE_INT offset = 0;
5924       struct induction *v = REG_IV_INFO (ivs, REGNO (iteration_var));
5925       rtx biv_initial_value;
5926
5927       gcc_assert (REGNO (v->src_reg) < ivs->n_regs);
5928
5929       if (!v->always_executed || v->maybe_multiple)
5930         {
5931           if (loop_dump_stream)
5932             fprintf (loop_dump_stream,
5933                      "Loop iterations: General induction var not set once in each iteration.\n");
5934           return 0;
5935         }
5936
5937       bl = REG_IV_CLASS (ivs, REGNO (v->src_reg));
5938
5939       /* Increment value is mult_val times the increment value of the biv.  */
5940
5941       increment = biv_total_increment (bl);
5942       if (increment)
5943         {
5944           struct induction *biv_inc;
5945
5946           increment = fold_rtx_mult_add (v->mult_val,
5947                                          extend_value_for_giv (v, increment),
5948                                          const0_rtx, v->mode);
5949           /* The caller assumes that one full increment has occurred at the
5950              first loop test.  But that's not true when the biv is incremented
5951              after the giv is set (which is the usual case), e.g.:
5952              i = 6; do {;} while (i++ < 9) .
5953              Therefore, we bias the initial value by subtracting the amount of
5954              the increment that occurs between the giv set and the giv test.  */
5955           for (biv_inc = bl->biv; biv_inc; biv_inc = biv_inc->next_iv)
5956             {
5957               if (loop_insn_first_p (v->insn, biv_inc->insn))
5958                 {
5959                   if (REG_P (biv_inc->add_val))
5960                     {
5961                       if (loop_dump_stream)
5962                         fprintf (loop_dump_stream,
5963                                  "Loop iterations: Basic induction var add_val is REG %d.\n",
5964                                  REGNO (biv_inc->add_val));
5965                         return 0;
5966                     }
5967
5968                   /* If we have already counted it, skip it.  */
5969                   if (biv_inc->same)
5970                     continue;
5971
5972                   offset -= INTVAL (biv_inc->add_val);
5973                 }
5974             }
5975         }
5976       if (loop_dump_stream)
5977         fprintf (loop_dump_stream,
5978                  "Loop iterations: Giv iterator, initial value bias %ld.\n",
5979                  (long) offset);
5980
5981       /* Initial value is mult_val times the biv's initial value plus
5982          add_val.  Only useful if it is a constant.  */
5983       biv_initial_value = extend_value_for_giv (v, bl->initial_value);
5984       initial_value
5985         = fold_rtx_mult_add (v->mult_val,
5986                              plus_constant (biv_initial_value, offset),
5987                              v->add_val, v->mode);
5988     }
5989   else
5990     {
5991       if (loop_dump_stream)
5992         fprintf (loop_dump_stream,
5993                  "Loop iterations: Not basic or general induction var.\n");
5994       return 0;
5995     }
5996
5997   if (initial_value == 0)
5998     return 0;
5999
6000   unsigned_p = 0;
6001   off_by_one = 0;
6002   switch (comparison_code)
6003     {
6004     case LEU:
6005       unsigned_p = 1;
6006     case LE:
6007       compare_dir = 1;
6008       off_by_one = 1;
6009       break;
6010     case GEU:
6011       unsigned_p = 1;
6012     case GE:
6013       compare_dir = -1;
6014       off_by_one = -1;
6015       break;
6016     case EQ:
6017       /* Cannot determine loop iterations with this case.  */
6018       compare_dir = 0;
6019       break;
6020     case LTU:
6021       unsigned_p = 1;
6022     case LT:
6023       compare_dir = 1;
6024       break;
6025     case GTU:
6026       unsigned_p = 1;
6027     case GT:
6028       compare_dir = -1;
6029       break;
6030     case NE:
6031       compare_dir = 0;
6032       break;
6033     default:
6034       gcc_unreachable ();
6035     }
6036
6037   /* If the comparison value is an invariant register, then try to find
6038      its value from the insns before the start of the loop.  */
6039
6040   final_value = comparison_value;
6041   if (REG_P (comparison_value)
6042       && loop_invariant_p (loop, comparison_value))
6043     {
6044       final_value = loop_find_equiv_value (loop, comparison_value);
6045
6046       /* If we don't get an invariant final value, we are better
6047          off with the original register.  */
6048       if (! loop_invariant_p (loop, final_value))
6049         final_value = comparison_value;
6050     }
6051
6052   /* Calculate the approximate final value of the induction variable
6053      (on the last successful iteration).  The exact final value
6054      depends on the branch operator, and increment sign.  It will be
6055      wrong if the iteration variable is not incremented by one each
6056      time through the loop and (comparison_value + off_by_one -
6057      initial_value) % increment != 0.
6058      ??? Note that the final_value may overflow and thus final_larger
6059      will be bogus.  A potentially infinite loop will be classified
6060      as immediate, e.g. for (i = 0x7ffffff0; i <= 0x7fffffff; i++)  */
6061   if (off_by_one)
6062     final_value = plus_constant (final_value, off_by_one);
6063
6064   /* Save the calculated values describing this loop's bounds, in case
6065      precondition_loop_p will need them later.  These values can not be
6066      recalculated inside precondition_loop_p because strength reduction
6067      optimizations may obscure the loop's structure.
6068
6069      These values are only required by precondition_loop_p and insert_bct
6070      whenever the number of iterations cannot be computed at compile time.
6071      Only the difference between final_value and initial_value is
6072      important.  Note that final_value is only approximate.  */
6073   loop_info->initial_value = initial_value;
6074   loop_info->comparison_value = comparison_value;
6075   loop_info->final_value = plus_constant (comparison_value, off_by_one);
6076   loop_info->increment = increment;
6077   loop_info->iteration_var = iteration_var;
6078   loop_info->comparison_code = comparison_code;
6079   loop_info->iv = bl;
6080
6081   /* Try to determine the iteration count for loops such
6082      as (for i = init; i < init + const; i++).  When running the
6083      loop optimization twice, the first pass often converts simple
6084      loops into this form.  */
6085
6086   if (REG_P (initial_value))
6087     {
6088       rtx reg1;
6089       rtx reg2;
6090       rtx const2;
6091
6092       reg1 = initial_value;
6093       if (GET_CODE (final_value) == PLUS)
6094         reg2 = XEXP (final_value, 0), const2 = XEXP (final_value, 1);
6095       else
6096         reg2 = final_value, const2 = const0_rtx;
6097
6098       /* Check for initial_value = reg1, final_value = reg2 + const2,
6099          where reg1 != reg2.  */
6100       if (REG_P (reg2) && reg2 != reg1)
6101         {
6102           rtx temp;
6103
6104           /* Find what reg1 is equivalent to.  Hopefully it will
6105              either be reg2 or reg2 plus a constant.  */
6106           temp = loop_find_equiv_value (loop, reg1);
6107
6108           if (find_common_reg_term (temp, reg2))
6109             initial_value = temp;
6110           else if (loop_invariant_p (loop, reg2))
6111             {
6112               /* Find what reg2 is equivalent to.  Hopefully it will
6113                  either be reg1 or reg1 plus a constant.  Let's ignore
6114                  the latter case for now since it is not so common.  */
6115               temp = loop_find_equiv_value (loop, reg2);
6116
6117               if (temp == loop_info->iteration_var)
6118                 temp = initial_value;
6119               if (temp == reg1)
6120                 final_value = (const2 == const0_rtx)
6121                   ? reg1 : gen_rtx_PLUS (GET_MODE (reg1), reg1, const2);
6122             }
6123         }
6124     }
6125
6126   loop_info->initial_equiv_value = initial_value;
6127   loop_info->final_equiv_value = final_value;
6128
6129   /* For EQ comparison loops, we don't have a valid final value.
6130      Check this now so that we won't leave an invalid value if we
6131      return early for any other reason.  */
6132   if (comparison_code == EQ)
6133     loop_info->final_equiv_value = loop_info->final_value = 0;
6134
6135   if (increment == 0)
6136     {
6137       if (loop_dump_stream)
6138         fprintf (loop_dump_stream,
6139                  "Loop iterations: Increment value can't be calculated.\n");
6140       return 0;
6141     }
6142
6143   if (GET_CODE (increment) != CONST_INT)
6144     {
6145       /* If we have a REG, check to see if REG holds a constant value.  */
6146       /* ??? Other RTL, such as (neg (reg)) is possible here, but it isn't
6147          clear if it is worthwhile to try to handle such RTL.  */
6148       if (REG_P (increment) || GET_CODE (increment) == SUBREG)
6149         increment = loop_find_equiv_value (loop, increment);
6150
6151       if (GET_CODE (increment) != CONST_INT)
6152         {
6153           if (loop_dump_stream)
6154             {
6155               fprintf (loop_dump_stream,
6156                        "Loop iterations: Increment value not constant ");
6157               print_simple_rtl (loop_dump_stream, increment);
6158               fprintf (loop_dump_stream, ".\n");
6159             }
6160           return 0;
6161         }
6162       loop_info->increment = increment;
6163     }
6164
6165   if (GET_CODE (initial_value) != CONST_INT)
6166     {
6167       if (loop_dump_stream)
6168         {
6169           fprintf (loop_dump_stream,
6170                    "Loop iterations: Initial value not constant ");
6171           print_simple_rtl (loop_dump_stream, initial_value);
6172           fprintf (loop_dump_stream, ".\n");
6173         }
6174       return 0;
6175     }
6176   else if (GET_CODE (final_value) != CONST_INT)
6177     {
6178       if (loop_dump_stream)
6179         {
6180           fprintf (loop_dump_stream,
6181                    "Loop iterations: Final value not constant ");
6182           print_simple_rtl (loop_dump_stream, final_value);
6183           fprintf (loop_dump_stream, ".\n");
6184         }
6185       return 0;
6186     }
6187   else if (comparison_code == EQ)
6188     {
6189       rtx inc_once;
6190
6191       if (loop_dump_stream)
6192         fprintf (loop_dump_stream, "Loop iterations: EQ comparison loop.\n");
6193
6194       inc_once = gen_int_mode (INTVAL (initial_value) + INTVAL (increment),
6195                                GET_MODE (iteration_var));
6196
6197       if (inc_once == final_value)
6198         {
6199           /* The iterator value once through the loop is equal to the
6200              comparison value.  Either we have an infinite loop, or
6201              we'll loop twice.  */
6202           if (increment == const0_rtx)
6203             return 0;
6204           loop_info->n_iterations = 2;
6205         }
6206       else
6207         loop_info->n_iterations = 1;
6208
6209       if (GET_CODE (loop_info->initial_value) == CONST_INT)
6210         loop_info->final_value
6211           = gen_int_mode ((INTVAL (loop_info->initial_value)
6212                            + loop_info->n_iterations * INTVAL (increment)),
6213                           GET_MODE (iteration_var));
6214       else
6215         loop_info->final_value
6216           = plus_constant (loop_info->initial_value,
6217                            loop_info->n_iterations * INTVAL (increment));
6218       loop_info->final_equiv_value
6219         = gen_int_mode ((INTVAL (initial_value)
6220                          + loop_info->n_iterations * INTVAL (increment)),
6221                         GET_MODE (iteration_var));
6222       return loop_info->n_iterations;
6223     }
6224
6225   /* Final_larger is 1 if final larger, 0 if they are equal, otherwise -1.  */
6226   if (unsigned_p)
6227     final_larger
6228       = ((unsigned HOST_WIDE_INT) INTVAL (final_value)
6229          > (unsigned HOST_WIDE_INT) INTVAL (initial_value))
6230         - ((unsigned HOST_WIDE_INT) INTVAL (final_value)
6231            < (unsigned HOST_WIDE_INT) INTVAL (initial_value));
6232   else
6233     final_larger = (INTVAL (final_value) > INTVAL (initial_value))
6234       - (INTVAL (final_value) < INTVAL (initial_value));
6235
6236   if (INTVAL (increment) > 0)
6237     increment_dir = 1;
6238   else if (INTVAL (increment) == 0)
6239     increment_dir = 0;
6240   else
6241     increment_dir = -1;
6242
6243   /* There are 27 different cases: compare_dir = -1, 0, 1;
6244      final_larger = -1, 0, 1; increment_dir = -1, 0, 1.
6245      There are 4 normal cases, 4 reverse cases (where the iteration variable
6246      will overflow before the loop exits), 4 infinite loop cases, and 15
6247      immediate exit (0 or 1 iteration depending on loop type) cases.
6248      Only try to optimize the normal cases.  */
6249
6250   /* (compare_dir/final_larger/increment_dir)
6251      Normal cases: (0/-1/-1), (0/1/1), (-1/-1/-1), (1/1/1)
6252      Reverse cases: (0/-1/1), (0/1/-1), (-1/-1/1), (1/1/-1)
6253      Infinite loops: (0/-1/0), (0/1/0), (-1/-1/0), (1/1/0)
6254      Immediate exit: (0/0/X), (-1/0/X), (-1/1/X), (1/0/X), (1/-1/X) */
6255
6256   /* ?? If the meaning of reverse loops (where the iteration variable
6257      will overflow before the loop exits) is undefined, then could
6258      eliminate all of these special checks, and just always assume
6259      the loops are normal/immediate/infinite.  Note that this means
6260      the sign of increment_dir does not have to be known.  Also,
6261      since it does not really hurt if immediate exit loops or infinite loops
6262      are optimized, then that case could be ignored also, and hence all
6263      loops can be optimized.
6264
6265      According to ANSI Spec, the reverse loop case result is undefined,
6266      because the action on overflow is undefined.
6267
6268      See also the special test for NE loops below.  */
6269
6270   if (final_larger == increment_dir && final_larger != 0
6271       && (final_larger == compare_dir || compare_dir == 0))
6272     /* Normal case.  */
6273     ;
6274   else
6275     {
6276       if (loop_dump_stream)
6277         fprintf (loop_dump_stream, "Loop iterations: Not normal loop.\n");
6278       return 0;
6279     }
6280
6281   /* Calculate the number of iterations, final_value is only an approximation,
6282      so correct for that.  Note that abs_diff and n_iterations are
6283      unsigned, because they can be as large as 2^n - 1.  */
6284
6285   inc = INTVAL (increment);
6286   gcc_assert (inc);
6287   if (inc > 0)
6288     {
6289       abs_diff = INTVAL (final_value) - INTVAL (initial_value);
6290       abs_inc = inc;
6291     }
6292   else
6293     {
6294       abs_diff = INTVAL (initial_value) - INTVAL (final_value);
6295       abs_inc = -inc;
6296     }
6297
6298   /* Given that iteration_var is going to iterate over its own mode,
6299      not HOST_WIDE_INT, disregard higher bits that might have come
6300      into the picture due to sign extension of initial and final
6301      values.  */
6302   abs_diff &= ((unsigned HOST_WIDE_INT) 1
6303                << (GET_MODE_BITSIZE (GET_MODE (iteration_var)) - 1)
6304                << 1) - 1;
6305
6306   /* For NE tests, make sure that the iteration variable won't miss
6307      the final value.  If abs_diff mod abs_incr is not zero, then the
6308      iteration variable will overflow before the loop exits, and we
6309      can not calculate the number of iterations.  */
6310   if (compare_dir == 0 && (abs_diff % abs_inc) != 0)
6311     return 0;
6312
6313   /* Note that the number of iterations could be calculated using
6314      (abs_diff + abs_inc - 1) / abs_inc, provided care was taken to
6315      handle potential overflow of the summation.  */
6316   loop_info->n_iterations = abs_diff / abs_inc + ((abs_diff % abs_inc) != 0);
6317   return loop_info->n_iterations;
6318 }
6319
6320 /* Perform strength reduction and induction variable elimination.
6321
6322    Pseudo registers created during this function will be beyond the
6323    last valid index in several tables including
6324    REGS->ARRAY[I].N_TIMES_SET and REGNO_LAST_UID.  This does not cause a
6325    problem here, because the added registers cannot be givs outside of
6326    their loop, and hence will never be reconsidered.  But scan_loop
6327    must check regnos to make sure they are in bounds.  */
6328
6329 static void
6330 strength_reduce (struct loop *loop, int flags)
6331 {
6332   struct loop_info *loop_info = LOOP_INFO (loop);
6333   struct loop_regs *regs = LOOP_REGS (loop);
6334   struct loop_ivs *ivs = LOOP_IVS (loop);
6335   rtx p;
6336   /* Temporary list pointer for traversing ivs->list.  */
6337   struct iv_class *bl;
6338   /* Ratio of extra register life span we can justify
6339      for saving an instruction.  More if loop doesn't call subroutines
6340      since in that case saving an insn makes more difference
6341      and more registers are available.  */
6342   /* ??? could set this to last value of threshold in move_movables */
6343   int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
6344   /* Map of pseudo-register replacements.  */
6345   rtx *reg_map = NULL;
6346   int reg_map_size;
6347   rtx test_reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
6348   int insn_count = count_insns_in_loop (loop);
6349
6350   addr_placeholder = gen_reg_rtx (Pmode);
6351
6352   ivs->n_regs = max_reg_before_loop;
6353   ivs->regs = xcalloc (ivs->n_regs, sizeof (struct iv));
6354
6355   /* Find all BIVs in loop.  */
6356   loop_bivs_find (loop);
6357
6358   /* Exit if there are no bivs.  */
6359   if (! ivs->list)
6360     {
6361       loop_ivs_free (loop);
6362       return;
6363     }
6364
6365   /* Determine how BIVS are initialized by looking through pre-header
6366      extended basic block.  */
6367   loop_bivs_init_find (loop);
6368
6369   /* Look at the each biv and see if we can say anything better about its
6370      initial value from any initializing insns set up above.  */
6371   loop_bivs_check (loop);
6372
6373   /* Search the loop for general induction variables.  */
6374   loop_givs_find (loop);
6375
6376   /* Try to calculate and save the number of loop iterations.  This is
6377      set to zero if the actual number can not be calculated.  This must
6378      be called after all giv's have been identified, since otherwise it may
6379      fail if the iteration variable is a giv.  */
6380   loop_iterations (loop);
6381
6382 #ifdef HAVE_prefetch
6383   if (flags & LOOP_PREFETCH)
6384     emit_prefetch_instructions (loop);
6385 #endif
6386
6387   /* Now for each giv for which we still don't know whether or not it is
6388      replaceable, check to see if it is replaceable because its final value
6389      can be calculated.  This must be done after loop_iterations is called,
6390      so that final_giv_value will work correctly.  */
6391   loop_givs_check (loop);
6392
6393   /* Try to prove that the loop counter variable (if any) is always
6394      nonnegative; if so, record that fact with a REG_NONNEG note
6395      so that "decrement and branch until zero" insn can be used.  */
6396   check_dbra_loop (loop, insn_count);
6397
6398   /* Create reg_map to hold substitutions for replaceable giv regs.
6399      Some givs might have been made from biv increments, so look at
6400      ivs->reg_iv_type for a suitable size.  */
6401   reg_map_size = ivs->n_regs;
6402   reg_map = xcalloc (reg_map_size, sizeof (rtx));
6403
6404   /* Examine each iv class for feasibility of strength reduction/induction
6405      variable elimination.  */
6406
6407   for (bl = ivs->list; bl; bl = bl->next)
6408     {
6409       struct induction *v;
6410       int benefit;
6411
6412       /* Test whether it will be possible to eliminate this biv
6413          provided all givs are reduced.  */
6414       bl->eliminable = loop_biv_eliminable_p (loop, bl, threshold, insn_count);
6415
6416       /* This will be true at the end, if all givs which depend on this
6417          biv have been strength reduced.
6418          We can't (currently) eliminate the biv unless this is so.  */
6419       bl->all_reduced = 1;
6420
6421       /* Check each extension dependent giv in this class to see if its
6422          root biv is safe from wrapping in the interior mode.  */
6423       check_ext_dependent_givs (loop, bl);
6424
6425       /* Combine all giv's for this iv_class.  */
6426       combine_givs (regs, bl);
6427
6428       for (v = bl->giv; v; v = v->next_iv)
6429         {
6430           struct induction *tv;
6431
6432           if (v->ignore || v->same)
6433             continue;
6434
6435           benefit = loop_giv_reduce_benefit (loop, bl, v, test_reg);
6436
6437           /* If an insn is not to be strength reduced, then set its ignore
6438              flag, and clear bl->all_reduced.  */
6439
6440           /* A giv that depends on a reversed biv must be reduced if it is
6441              used after the loop exit, otherwise, it would have the wrong
6442              value after the loop exit.  To make it simple, just reduce all
6443              of such giv's whether or not we know they are used after the loop
6444              exit.  */
6445
6446           if (v->lifetime * threshold * benefit < insn_count
6447               && ! bl->reversed)
6448             {
6449               if (loop_dump_stream)
6450                 fprintf (loop_dump_stream,
6451                          "giv of insn %d not worth while, %d vs %d.\n",
6452                          INSN_UID (v->insn),
6453                          v->lifetime * threshold * benefit, insn_count);
6454               v->ignore = 1;
6455               bl->all_reduced = 0;
6456             }
6457           else
6458             {
6459               /* Check that we can increment the reduced giv without a
6460                  multiply insn.  If not, reject it.  */
6461
6462               for (tv = bl->biv; tv; tv = tv->next_iv)
6463                 if (tv->mult_val == const1_rtx
6464                     && ! product_cheap_p (tv->add_val, v->mult_val))
6465                   {
6466                     if (loop_dump_stream)
6467                       fprintf (loop_dump_stream,
6468                                "giv of insn %d: would need a multiply.\n",
6469                                INSN_UID (v->insn));
6470                     v->ignore = 1;
6471                     bl->all_reduced = 0;
6472                     break;
6473                   }
6474             }
6475         }
6476
6477       /* Check for givs whose first use is their definition and whose
6478          last use is the definition of another giv.  If so, it is likely
6479          dead and should not be used to derive another giv nor to
6480          eliminate a biv.  */
6481       loop_givs_dead_check (loop, bl);
6482
6483       /* Reduce each giv that we decided to reduce.  */
6484       loop_givs_reduce (loop, bl);
6485
6486       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
6487          as not reduced.
6488
6489          For each giv register that can be reduced now: if replaceable,
6490          substitute reduced reg wherever the old giv occurs;
6491          else add new move insn "giv_reg = reduced_reg".  */
6492       loop_givs_rescan (loop, bl, reg_map);
6493
6494       /* All the givs based on the biv bl have been reduced if they
6495          merit it.  */
6496
6497       /* For each giv not marked as maybe dead that has been combined with a
6498          second giv, clear any "maybe dead" mark on that second giv.
6499          v->new_reg will either be or refer to the register of the giv it
6500          combined with.
6501
6502          Doing this clearing avoids problems in biv elimination where
6503          a giv's new_reg is a complex value that can't be put in the
6504          insn but the giv combined with (with a reg as new_reg) is
6505          marked maybe_dead.  Since the register will be used in either
6506          case, we'd prefer it be used from the simpler giv.  */
6507
6508       for (v = bl->giv; v; v = v->next_iv)
6509         if (! v->maybe_dead && v->same)
6510           v->same->maybe_dead = 0;
6511
6512       /* Try to eliminate the biv, if it is a candidate.
6513          This won't work if ! bl->all_reduced,
6514          since the givs we planned to use might not have been reduced.
6515
6516          We have to be careful that we didn't initially think we could
6517          eliminate this biv because of a giv that we now think may be
6518          dead and shouldn't be used as a biv replacement.
6519
6520          Also, there is the possibility that we may have a giv that looks
6521          like it can be used to eliminate a biv, but the resulting insn
6522          isn't valid.  This can happen, for example, on the 88k, where a
6523          JUMP_INSN can compare a register only with zero.  Attempts to
6524          replace it with a compare with a constant will fail.
6525
6526          Note that in cases where this call fails, we may have replaced some
6527          of the occurrences of the biv with a giv, but no harm was done in
6528          doing so in the rare cases where it can occur.  */
6529
6530       if (bl->all_reduced == 1 && bl->eliminable
6531           && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
6532         {
6533           /* ?? If we created a new test to bypass the loop entirely,
6534              or otherwise drop straight in, based on this test, then
6535              we might want to rewrite it also.  This way some later
6536              pass has more hope of removing the initialization of this
6537              biv entirely.  */
6538
6539           /* If final_value != 0, then the biv may be used after loop end
6540              and we must emit an insn to set it just in case.
6541
6542              Reversed bivs already have an insn after the loop setting their
6543              value, so we don't need another one.  We can't calculate the
6544              proper final value for such a biv here anyways.  */
6545           if (bl->final_value && ! bl->reversed)
6546               loop_insn_sink_or_swim (loop,
6547                                       gen_load_of_final_value (bl->biv->dest_reg,
6548                                                                bl->final_value));
6549
6550           if (loop_dump_stream)
6551             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
6552                      bl->regno);
6553         }
6554       /* See above note wrt final_value.  But since we couldn't eliminate
6555          the biv, we must set the value after the loop instead of before.  */
6556       else if (bl->final_value && ! bl->reversed)
6557         loop_insn_sink (loop, gen_load_of_final_value (bl->biv->dest_reg,
6558                                                        bl->final_value));
6559     }
6560
6561   /* Go through all the instructions in the loop, making all the
6562      register substitutions scheduled in REG_MAP.  */
6563
6564   for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
6565     if (INSN_P (p))
6566       {
6567         replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
6568         replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
6569         INSN_CODE (p) = -1;
6570       }
6571
6572   if (loop_dump_stream)
6573     fprintf (loop_dump_stream, "\n");
6574
6575   loop_ivs_free (loop);
6576   if (reg_map)
6577     free (reg_map);
6578 }
6579 \f
6580 /*Record all basic induction variables calculated in the insn.  */
6581 static rtx
6582 check_insn_for_bivs (struct loop *loop, rtx p, int not_every_iteration,
6583                      int maybe_multiple)
6584 {
6585   struct loop_ivs *ivs = LOOP_IVS (loop);
6586   rtx set;
6587   rtx dest_reg;
6588   rtx inc_val;
6589   rtx mult_val;
6590   rtx *location;
6591
6592   if (NONJUMP_INSN_P (p)
6593       && (set = single_set (p))
6594       && REG_P (SET_DEST (set)))
6595     {
6596       dest_reg = SET_DEST (set);
6597       if (REGNO (dest_reg) < max_reg_before_loop
6598           && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
6599           && REG_IV_TYPE (ivs, REGNO (dest_reg)) != NOT_BASIC_INDUCT)
6600         {
6601           if (basic_induction_var (loop, SET_SRC (set),
6602                                    GET_MODE (SET_SRC (set)),
6603                                    dest_reg, p, &inc_val, &mult_val,
6604                                    &location))
6605             {
6606               /* It is a possible basic induction variable.
6607                  Create and initialize an induction structure for it.  */
6608
6609               struct induction *v = xmalloc (sizeof (struct induction));
6610
6611               record_biv (loop, v, p, dest_reg, inc_val, mult_val, location,
6612                           not_every_iteration, maybe_multiple);
6613               REG_IV_TYPE (ivs, REGNO (dest_reg)) = BASIC_INDUCT;
6614             }
6615           else if (REGNO (dest_reg) < ivs->n_regs)
6616             REG_IV_TYPE (ivs, REGNO (dest_reg)) = NOT_BASIC_INDUCT;
6617         }
6618     }
6619   return p;
6620 }
6621 \f
6622 /* Record all givs calculated in the insn.
6623    A register is a giv if: it is only set once, it is a function of a
6624    biv and a constant (or invariant), and it is not a biv.  */
6625 static rtx
6626 check_insn_for_givs (struct loop *loop, rtx p, int not_every_iteration,
6627                      int maybe_multiple)
6628 {
6629   struct loop_regs *regs = LOOP_REGS (loop);
6630
6631   rtx set;
6632   /* Look for a general induction variable in a register.  */
6633   if (NONJUMP_INSN_P (p)
6634       && (set = single_set (p))
6635       && REG_P (SET_DEST (set))
6636       && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
6637     {
6638       rtx src_reg;
6639       rtx dest_reg;
6640       rtx add_val;
6641       rtx mult_val;
6642       rtx ext_val;
6643       int benefit;
6644       rtx regnote = 0;
6645       rtx last_consec_insn;
6646
6647       dest_reg = SET_DEST (set);
6648       if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
6649         return p;
6650
6651       if (/* SET_SRC is a giv.  */
6652           (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
6653                                   &mult_val, &ext_val, 0, &benefit, VOIDmode)
6654            /* Equivalent expression is a giv.  */
6655            || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
6656                && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
6657                                          &add_val, &mult_val, &ext_val, 0,
6658                                          &benefit, VOIDmode)))
6659           /* Don't try to handle any regs made by loop optimization.
6660              We have nothing on them in regno_first_uid, etc.  */
6661           && REGNO (dest_reg) < max_reg_before_loop
6662           /* Don't recognize a BASIC_INDUCT_VAR here.  */
6663           && dest_reg != src_reg
6664           /* This must be the only place where the register is set.  */
6665           && (regs->array[REGNO (dest_reg)].n_times_set == 1
6666               /* or all sets must be consecutive and make a giv.  */
6667               || (benefit = consec_sets_giv (loop, benefit, p,
6668                                              src_reg, dest_reg,
6669                                              &add_val, &mult_val, &ext_val,
6670                                              &last_consec_insn))))
6671         {
6672           struct induction *v = xmalloc (sizeof (struct induction));
6673
6674           /* If this is a library call, increase benefit.  */
6675           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
6676             benefit += libcall_benefit (p);
6677
6678           /* Skip the consecutive insns, if there are any.  */
6679           if (regs->array[REGNO (dest_reg)].n_times_set != 1)
6680             p = last_consec_insn;
6681
6682           record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
6683                       ext_val, benefit, DEST_REG, not_every_iteration,
6684                       maybe_multiple, (rtx*) 0);
6685
6686         }
6687     }
6688
6689   /* Look for givs which are memory addresses.  */
6690   if (NONJUMP_INSN_P (p))
6691     find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
6692                    maybe_multiple);
6693
6694   /* Update the status of whether giv can derive other givs.  This can
6695      change when we pass a label or an insn that updates a biv.  */
6696   if (INSN_P (p) || LABEL_P (p))
6697     update_giv_derive (loop, p);
6698   return p;
6699 }
6700 \f
6701 /* Return 1 if X is a valid source for an initial value (or as value being
6702    compared against in an initial test).
6703
6704    X must be either a register or constant and must not be clobbered between
6705    the current insn and the start of the loop.
6706
6707    INSN is the insn containing X.  */
6708
6709 static int
6710 valid_initial_value_p (rtx x, rtx insn, int call_seen, rtx loop_start)
6711 {
6712   if (CONSTANT_P (x))
6713     return 1;
6714
6715   /* Only consider pseudos we know about initialized in insns whose luids
6716      we know.  */
6717   if (!REG_P (x)
6718       || REGNO (x) >= max_reg_before_loop)
6719     return 0;
6720
6721   /* Don't use call-clobbered registers across a call which clobbers it.  On
6722      some machines, don't use any hard registers at all.  */
6723   if (REGNO (x) < FIRST_PSEUDO_REGISTER
6724       && (SMALL_REGISTER_CLASSES
6725           || (call_seen && call_used_regs[REGNO (x)])))
6726     return 0;
6727
6728   /* Don't use registers that have been clobbered before the start of the
6729      loop.  */
6730   if (reg_set_between_p (x, insn, loop_start))
6731     return 0;
6732
6733   return 1;
6734 }
6735 \f
6736 /* Scan X for memory refs and check each memory address
6737    as a possible giv.  INSN is the insn whose pattern X comes from.
6738    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
6739    every loop iteration.  MAYBE_MULTIPLE is 1 if the insn might be executed
6740    more than once in each loop iteration.  */
6741
6742 static void
6743 find_mem_givs (const struct loop *loop, rtx x, rtx insn,
6744                int not_every_iteration, int maybe_multiple)
6745 {
6746   int i, j;
6747   enum rtx_code code;
6748   const char *fmt;
6749
6750   if (x == 0)
6751     return;
6752
6753   code = GET_CODE (x);
6754   switch (code)
6755     {
6756     case REG:
6757     case CONST_INT:
6758     case CONST:
6759     case CONST_DOUBLE:
6760     case SYMBOL_REF:
6761     case LABEL_REF:
6762     case PC:
6763     case CC0:
6764     case ADDR_VEC:
6765     case ADDR_DIFF_VEC:
6766     case USE:
6767     case CLOBBER:
6768       return;
6769
6770     case MEM:
6771       {
6772         rtx src_reg;
6773         rtx add_val;
6774         rtx mult_val;
6775         rtx ext_val;
6776         int benefit;
6777
6778         /* This code used to disable creating GIVs with mult_val == 1 and
6779            add_val == 0.  However, this leads to lost optimizations when
6780            it comes time to combine a set of related DEST_ADDR GIVs, since
6781            this one would not be seen.  */
6782
6783         if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
6784                                    &mult_val, &ext_val, 1, &benefit,
6785                                    GET_MODE (x)))
6786           {
6787             /* Found one; record it.  */
6788             struct induction *v = xmalloc (sizeof (struct induction));
6789
6790             record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
6791                         add_val, ext_val, benefit, DEST_ADDR,
6792                         not_every_iteration, maybe_multiple, &XEXP (x, 0));
6793
6794             v->mem = x;
6795           }
6796       }
6797       return;
6798
6799     default:
6800       break;
6801     }
6802
6803   /* Recursively scan the subexpressions for other mem refs.  */
6804
6805   fmt = GET_RTX_FORMAT (code);
6806   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
6807     if (fmt[i] == 'e')
6808       find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
6809                      maybe_multiple);
6810     else if (fmt[i] == 'E')
6811       for (j = 0; j < XVECLEN (x, i); j++)
6812         find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
6813                        maybe_multiple);
6814 }
6815 \f
6816 /* Fill in the data about one biv update.
6817    V is the `struct induction' in which we record the biv.  (It is
6818    allocated by the caller, with alloca.)
6819    INSN is the insn that sets it.
6820    DEST_REG is the biv's reg.
6821
6822    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
6823    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
6824    being set to INC_VAL.
6825
6826    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
6827    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
6828    can be executed more than once per iteration.  If MAYBE_MULTIPLE
6829    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
6830    executed exactly once per iteration.  */
6831
6832 static void
6833 record_biv (struct loop *loop, struct induction *v, rtx insn, rtx dest_reg,
6834             rtx inc_val, rtx mult_val, rtx *location,
6835             int not_every_iteration, int maybe_multiple)
6836 {
6837   struct loop_ivs *ivs = LOOP_IVS (loop);
6838   struct iv_class *bl;
6839
6840   v->insn = insn;
6841   v->src_reg = dest_reg;
6842   v->dest_reg = dest_reg;
6843   v->mult_val = mult_val;
6844   v->add_val = inc_val;
6845   v->ext_dependent = NULL_RTX;
6846   v->location = location;
6847   v->mode = GET_MODE (dest_reg);
6848   v->always_computable = ! not_every_iteration;
6849   v->always_executed = ! not_every_iteration;
6850   v->maybe_multiple = maybe_multiple;
6851   v->same = 0;
6852
6853   /* Add this to the reg's iv_class, creating a class
6854      if this is the first incrementation of the reg.  */
6855
6856   bl = REG_IV_CLASS (ivs, REGNO (dest_reg));
6857   if (bl == 0)
6858     {
6859       /* Create and initialize new iv_class.  */
6860
6861       bl = xmalloc (sizeof (struct iv_class));
6862
6863       bl->regno = REGNO (dest_reg);
6864       bl->biv = 0;
6865       bl->giv = 0;
6866       bl->biv_count = 0;
6867       bl->giv_count = 0;
6868
6869       /* Set initial value to the reg itself.  */
6870       bl->initial_value = dest_reg;
6871       bl->final_value = 0;
6872       /* We haven't seen the initializing insn yet.  */
6873       bl->init_insn = 0;
6874       bl->init_set = 0;
6875       bl->initial_test = 0;
6876       bl->incremented = 0;
6877       bl->eliminable = 0;
6878       bl->nonneg = 0;
6879       bl->reversed = 0;
6880       bl->total_benefit = 0;
6881
6882       /* Add this class to ivs->list.  */
6883       bl->next = ivs->list;
6884       ivs->list = bl;
6885
6886       /* Put it in the array of biv register classes.  */
6887       REG_IV_CLASS (ivs, REGNO (dest_reg)) = bl;
6888     }
6889   else
6890     {
6891       /* Check if location is the same as a previous one.  */
6892       struct induction *induction;
6893       for (induction = bl->biv; induction; induction = induction->next_iv)
6894         if (location == induction->location)
6895           {
6896             v->same = induction;
6897             break;
6898           }
6899     }
6900
6901   /* Update IV_CLASS entry for this biv.  */
6902   v->next_iv = bl->biv;
6903   bl->biv = v;
6904   bl->biv_count++;
6905   if (mult_val == const1_rtx)
6906     bl->incremented = 1;
6907
6908   if (loop_dump_stream)
6909     loop_biv_dump (v, loop_dump_stream, 0);
6910 }
6911 \f
6912 /* Fill in the data about one giv.
6913    V is the `struct induction' in which we record the giv.  (It is
6914    allocated by the caller, with alloca.)
6915    INSN is the insn that sets it.
6916    BENEFIT estimates the savings from deleting this insn.
6917    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
6918    into a register or is used as a memory address.
6919
6920    SRC_REG is the biv reg which the giv is computed from.
6921    DEST_REG is the giv's reg (if the giv is stored in a reg).
6922    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
6923    LOCATION points to the place where this giv's value appears in INSN.  */
6924
6925 static void
6926 record_giv (const struct loop *loop, struct induction *v, rtx insn,
6927             rtx src_reg, rtx dest_reg, rtx mult_val, rtx add_val,
6928             rtx ext_val, int benefit, enum g_types type,
6929             int not_every_iteration, int maybe_multiple, rtx *location)
6930 {
6931   struct loop_ivs *ivs = LOOP_IVS (loop);
6932   struct induction *b;
6933   struct iv_class *bl;
6934   rtx set = single_set (insn);
6935   rtx temp;
6936
6937   /* Attempt to prove constantness of the values.  Don't let simplify_rtx
6938      undo the MULT canonicalization that we performed earlier.  */
6939   temp = simplify_rtx (add_val);
6940   if (temp
6941       && ! (GET_CODE (add_val) == MULT
6942             && GET_CODE (temp) == ASHIFT))
6943     add_val = temp;
6944
6945   v->insn = insn;
6946   v->src_reg = src_reg;
6947   v->giv_type = type;
6948   v->dest_reg = dest_reg;
6949   v->mult_val = mult_val;
6950   v->add_val = add_val;
6951   v->ext_dependent = ext_val;
6952   v->benefit = benefit;
6953   v->location = location;
6954   v->cant_derive = 0;
6955   v->combined_with = 0;
6956   v->maybe_multiple = maybe_multiple;
6957   v->maybe_dead = 0;
6958   v->derive_adjustment = 0;
6959   v->same = 0;
6960   v->ignore = 0;
6961   v->new_reg = 0;
6962   v->final_value = 0;
6963   v->same_insn = 0;
6964   v->auto_inc_opt = 0;
6965   v->shared = 0;
6966
6967   /* The v->always_computable field is used in update_giv_derive, to
6968      determine whether a giv can be used to derive another giv.  For a
6969      DEST_REG giv, INSN computes a new value for the giv, so its value
6970      isn't computable if INSN insn't executed every iteration.
6971      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
6972      it does not compute a new value.  Hence the value is always computable
6973      regardless of whether INSN is executed each iteration.  */
6974
6975   if (type == DEST_ADDR)
6976     v->always_computable = 1;
6977   else
6978     v->always_computable = ! not_every_iteration;
6979
6980   v->always_executed = ! not_every_iteration;
6981
6982   if (type == DEST_ADDR)
6983     {
6984       v->mode = GET_MODE (*location);
6985       v->lifetime = 1;
6986     }
6987   else /* type == DEST_REG */
6988     {
6989       v->mode = GET_MODE (SET_DEST (set));
6990
6991       v->lifetime = LOOP_REG_LIFETIME (loop, REGNO (dest_reg));
6992
6993       /* If the lifetime is zero, it means that this register is
6994          really a dead store.  So mark this as a giv that can be
6995          ignored.  This will not prevent the biv from being eliminated.  */
6996       if (v->lifetime == 0)
6997         v->ignore = 1;
6998
6999       REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
7000       REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
7001     }
7002
7003   /* Add the giv to the class of givs computed from one biv.  */
7004
7005   bl = REG_IV_CLASS (ivs, REGNO (src_reg));
7006   gcc_assert (bl);
7007   v->next_iv = bl->giv;
7008   bl->giv = v;
7009   
7010   /* Don't count DEST_ADDR.  This is supposed to count the number of
7011      insns that calculate givs.  */
7012   if (type == DEST_REG)
7013     bl->giv_count++;
7014   bl->total_benefit += benefit;
7015
7016   if (type == DEST_ADDR)
7017     {
7018       v->replaceable = 1;
7019       v->not_replaceable = 0;
7020     }
7021   else
7022     {
7023       /* The giv can be replaced outright by the reduced register only if all
7024          of the following conditions are true:
7025          - the insn that sets the giv is always executed on any iteration
7026            on which the giv is used at all
7027            (there are two ways to deduce this:
7028             either the insn is executed on every iteration,
7029             or all uses follow that insn in the same basic block),
7030          - the giv is not used outside the loop
7031          - no assignments to the biv occur during the giv's lifetime.  */
7032
7033       if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
7034           /* Previous line always fails if INSN was moved by loop opt.  */
7035           && REGNO_LAST_LUID (REGNO (dest_reg))
7036           < INSN_LUID (loop->end)
7037           && (! not_every_iteration
7038               || last_use_this_basic_block (dest_reg, insn)))
7039         {
7040           /* Now check that there are no assignments to the biv within the
7041              giv's lifetime.  This requires two separate checks.  */
7042
7043           /* Check each biv update, and fail if any are between the first
7044              and last use of the giv.
7045
7046              If this loop contains an inner loop that was unrolled, then
7047              the insn modifying the biv may have been emitted by the loop
7048              unrolling code, and hence does not have a valid luid.  Just
7049              mark the biv as not replaceable in this case.  It is not very
7050              useful as a biv, because it is used in two different loops.
7051              It is very unlikely that we would be able to optimize the giv
7052              using this biv anyways.  */
7053
7054           v->replaceable = 1;
7055           v->not_replaceable = 0;
7056           for (b = bl->biv; b; b = b->next_iv)
7057             {
7058               if (INSN_UID (b->insn) >= max_uid_for_loop
7059                   || ((INSN_LUID (b->insn)
7060                        >= REGNO_FIRST_LUID (REGNO (dest_reg)))
7061                       && (INSN_LUID (b->insn)
7062                           <= REGNO_LAST_LUID (REGNO (dest_reg)))))
7063                 {
7064                   v->replaceable = 0;
7065                   v->not_replaceable = 1;
7066                   break;
7067                 }
7068             }
7069
7070           /* If there are any backwards branches that go from after the
7071              biv update to before it, then this giv is not replaceable.  */
7072           if (v->replaceable)
7073             for (b = bl->biv; b; b = b->next_iv)
7074               if (back_branch_in_range_p (loop, b->insn))
7075                 {
7076                   v->replaceable = 0;
7077                   v->not_replaceable = 1;
7078                   break;
7079                 }
7080         }
7081       else
7082         {
7083           /* May still be replaceable, we don't have enough info here to
7084              decide.  */
7085           v->replaceable = 0;
7086           v->not_replaceable = 0;
7087         }
7088     }
7089
7090   /* Record whether the add_val contains a const_int, for later use by
7091      combine_givs.  */
7092   {
7093     rtx tem = add_val;
7094
7095     v->no_const_addval = 1;
7096     if (tem == const0_rtx)
7097       ;
7098     else if (CONSTANT_P (add_val))
7099       v->no_const_addval = 0;
7100     if (GET_CODE (tem) == PLUS)
7101       {
7102         while (1)
7103           {
7104             if (GET_CODE (XEXP (tem, 0)) == PLUS)
7105               tem = XEXP (tem, 0);
7106             else if (GET_CODE (XEXP (tem, 1)) == PLUS)
7107               tem = XEXP (tem, 1);
7108             else
7109               break;
7110           }
7111         if (CONSTANT_P (XEXP (tem, 1)))
7112           v->no_const_addval = 0;
7113       }
7114   }
7115
7116   if (loop_dump_stream)
7117     loop_giv_dump (v, loop_dump_stream, 0);
7118 }
7119
7120 /* Try to calculate the final value of the giv, the value it will have at
7121    the end of the loop.  If we can do it, return that value.  */
7122
7123 static rtx
7124 final_giv_value (const struct loop *loop, struct induction *v)
7125 {
7126   struct loop_ivs *ivs = LOOP_IVS (loop);
7127   struct iv_class *bl;
7128   rtx insn;
7129   rtx increment, tem;
7130   rtx seq;
7131   rtx loop_end = loop->end;
7132   unsigned HOST_WIDE_INT n_iterations = LOOP_INFO (loop)->n_iterations;
7133
7134   bl = REG_IV_CLASS (ivs, REGNO (v->src_reg));
7135
7136   /* The final value for givs which depend on reversed bivs must be calculated
7137      differently than for ordinary givs.  In this case, there is already an
7138      insn after the loop which sets this giv's final value (if necessary),
7139      and there are no other loop exits, so we can return any value.  */
7140   if (bl->reversed)
7141     {
7142       if (loop_dump_stream)
7143         fprintf (loop_dump_stream,
7144                  "Final giv value for %d, depends on reversed biv\n",
7145                  REGNO (v->dest_reg));
7146       return const0_rtx;
7147     }
7148
7149   /* Try to calculate the final value as a function of the biv it depends
7150      upon.  The only exit from the loop must be the fall through at the bottom
7151      and the insn that sets the giv must be executed on every iteration
7152      (otherwise the giv may not have its final value when the loop exits).  */
7153
7154   /* ??? Can calculate the final giv value by subtracting off the
7155      extra biv increments times the giv's mult_val.  The loop must have
7156      only one exit for this to work, but the loop iterations does not need
7157      to be known.  */
7158
7159   if (n_iterations != 0
7160       && ! loop->exit_count
7161       && v->always_executed)
7162     {
7163       /* ?? It is tempting to use the biv's value here since these insns will
7164          be put after the loop, and hence the biv will have its final value
7165          then.  However, this fails if the biv is subsequently eliminated.
7166          Perhaps determine whether biv's are eliminable before trying to
7167          determine whether giv's are replaceable so that we can use the
7168          biv value here if it is not eliminable.  */
7169
7170       /* We are emitting code after the end of the loop, so we must make
7171          sure that bl->initial_value is still valid then.  It will still
7172          be valid if it is invariant.  */
7173
7174       increment = biv_total_increment (bl);
7175
7176       if (increment && loop_invariant_p (loop, increment)
7177           && loop_invariant_p (loop, bl->initial_value))
7178         {
7179           /* Can calculate the loop exit value of its biv as
7180              (n_iterations * increment) + initial_value */
7181
7182           /* The loop exit value of the giv is then
7183              (final_biv_value - extra increments) * mult_val + add_val.
7184              The extra increments are any increments to the biv which
7185              occur in the loop after the giv's value is calculated.
7186              We must search from the insn that sets the giv to the end
7187              of the loop to calculate this value.  */
7188
7189           /* Put the final biv value in tem.  */
7190           tem = gen_reg_rtx (v->mode);
7191           record_base_value (REGNO (tem), bl->biv->add_val, 0);
7192           loop_iv_add_mult_sink (loop, extend_value_for_giv (v, increment),
7193                                  GEN_INT (n_iterations),
7194                                  extend_value_for_giv (v, bl->initial_value),
7195                                  tem);
7196
7197           /* Subtract off extra increments as we find them.  */
7198           for (insn = NEXT_INSN (v->insn); insn != loop_end;
7199                insn = NEXT_INSN (insn))
7200             {
7201               struct induction *biv;
7202
7203               for (biv = bl->biv; biv; biv = biv->next_iv)
7204                 if (biv->insn == insn)
7205                   {
7206                     start_sequence ();
7207                     tem = expand_simple_binop (GET_MODE (tem), MINUS, tem,
7208                                                biv->add_val, NULL_RTX, 0,
7209                                                OPTAB_LIB_WIDEN);
7210                     seq = get_insns ();
7211                     end_sequence ();
7212                     loop_insn_sink (loop, seq);
7213                   }
7214             }
7215
7216           /* Now calculate the giv's final value.  */
7217           loop_iv_add_mult_sink (loop, tem, v->mult_val, v->add_val, tem);
7218
7219           if (loop_dump_stream)
7220             fprintf (loop_dump_stream,
7221                      "Final giv value for %d, calc from biv's value.\n",
7222                      REGNO (v->dest_reg));
7223
7224           return tem;
7225         }
7226     }
7227
7228   /* Replaceable giv's should never reach here.  */
7229   gcc_assert (!v->replaceable);
7230
7231   /* Check to see if the biv is dead at all loop exits.  */
7232   if (reg_dead_after_loop (loop, v->dest_reg))
7233     {
7234       if (loop_dump_stream)
7235         fprintf (loop_dump_stream,
7236                  "Final giv value for %d, giv dead after loop exit.\n",
7237                  REGNO (v->dest_reg));
7238
7239       return const0_rtx;
7240     }
7241
7242   return 0;
7243 }
7244
7245 /* All this does is determine whether a giv can be made replaceable because
7246    its final value can be calculated.  This code can not be part of record_giv
7247    above, because final_giv_value requires that the number of loop iterations
7248    be known, and that can not be accurately calculated until after all givs
7249    have been identified.  */
7250
7251 static void
7252 check_final_value (const struct loop *loop, struct induction *v)
7253 {
7254   rtx final_value = 0;
7255
7256   /* DEST_ADDR givs will never reach here, because they are always marked
7257      replaceable above in record_giv.  */
7258
7259   /* The giv can be replaced outright by the reduced register only if all
7260      of the following conditions are true:
7261      - the insn that sets the giv is always executed on any iteration
7262        on which the giv is used at all
7263        (there are two ways to deduce this:
7264         either the insn is executed on every iteration,
7265         or all uses follow that insn in the same basic block),
7266      - its final value can be calculated (this condition is different
7267        than the one above in record_giv)
7268      - it's not used before the it's set
7269      - no assignments to the biv occur during the giv's lifetime.  */
7270
7271 #if 0
7272   /* This is only called now when replaceable is known to be false.  */
7273   /* Clear replaceable, so that it won't confuse final_giv_value.  */
7274   v->replaceable = 0;
7275 #endif
7276
7277   if ((final_value = final_giv_value (loop, v))
7278       && (v->always_executed
7279           || last_use_this_basic_block (v->dest_reg, v->insn)))
7280     {
7281       int biv_increment_seen = 0, before_giv_insn = 0;
7282       rtx p = v->insn;
7283       rtx last_giv_use;
7284
7285       v->replaceable = 1;
7286       v->not_replaceable = 0;
7287
7288       /* When trying to determine whether or not a biv increment occurs
7289          during the lifetime of the giv, we can ignore uses of the variable
7290          outside the loop because final_value is true.  Hence we can not
7291          use regno_last_uid and regno_first_uid as above in record_giv.  */
7292
7293       /* Search the loop to determine whether any assignments to the
7294          biv occur during the giv's lifetime.  Start with the insn
7295          that sets the giv, and search around the loop until we come
7296          back to that insn again.
7297
7298          Also fail if there is a jump within the giv's lifetime that jumps
7299          to somewhere outside the lifetime but still within the loop.  This
7300          catches spaghetti code where the execution order is not linear, and
7301          hence the above test fails.  Here we assume that the giv lifetime
7302          does not extend from one iteration of the loop to the next, so as
7303          to make the test easier.  Since the lifetime isn't known yet,
7304          this requires two loops.  See also record_giv above.  */
7305
7306       last_giv_use = v->insn;
7307
7308       while (1)
7309         {
7310           p = NEXT_INSN (p);
7311           if (p == loop->end)
7312             {
7313               before_giv_insn = 1;
7314               p = NEXT_INSN (loop->start);
7315             }
7316           if (p == v->insn)
7317             break;
7318
7319           if (INSN_P (p))
7320             {
7321               /* It is possible for the BIV increment to use the GIV if we
7322                  have a cycle.  Thus we must be sure to check each insn for
7323                  both BIV and GIV uses, and we must check for BIV uses
7324                  first.  */
7325
7326               if (! biv_increment_seen
7327                   && reg_set_p (v->src_reg, PATTERN (p)))
7328                 biv_increment_seen = 1;
7329
7330               if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
7331                 {
7332                   if (biv_increment_seen || before_giv_insn)
7333                     {
7334                       v->replaceable = 0;
7335                       v->not_replaceable = 1;
7336                       break;
7337                     }
7338                   last_giv_use = p;
7339                 }
7340             }
7341         }
7342
7343       /* Now that the lifetime of the giv is known, check for branches
7344          from within the lifetime to outside the lifetime if it is still
7345          replaceable.  */
7346
7347       if (v->replaceable)
7348         {
7349           p = v->insn;
7350           while (1)
7351             {
7352               p = NEXT_INSN (p);
7353               if (p == loop->end)
7354                 p = NEXT_INSN (loop->start);
7355               if (p == last_giv_use)
7356                 break;
7357
7358               if (JUMP_P (p) && JUMP_LABEL (p)
7359                   && LABEL_NAME (JUMP_LABEL (p))
7360                   && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
7361                        && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
7362                       || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
7363                           && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
7364                 {
7365                   v->replaceable = 0;
7366                   v->not_replaceable = 1;
7367
7368                   if (loop_dump_stream)
7369                     fprintf (loop_dump_stream,
7370                              "Found branch outside giv lifetime.\n");
7371
7372                   break;
7373                 }
7374             }
7375         }
7376
7377       /* If it is replaceable, then save the final value.  */
7378       if (v->replaceable)
7379         v->final_value = final_value;
7380     }
7381
7382   if (loop_dump_stream && v->replaceable)
7383     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
7384              INSN_UID (v->insn), REGNO (v->dest_reg));
7385 }
7386 \f
7387 /* Update the status of whether a giv can derive other givs.
7388
7389    We need to do something special if there is or may be an update to the biv
7390    between the time the giv is defined and the time it is used to derive
7391    another giv.
7392
7393    In addition, a giv that is only conditionally set is not allowed to
7394    derive another giv once a label has been passed.
7395
7396    The cases we look at are when a label or an update to a biv is passed.  */
7397
7398 static void
7399 update_giv_derive (const struct loop *loop, rtx p)
7400 {
7401   struct loop_ivs *ivs = LOOP_IVS (loop);
7402   struct iv_class *bl;
7403   struct induction *biv, *giv;
7404   rtx tem;
7405   int dummy;
7406
7407   /* Search all IV classes, then all bivs, and finally all givs.
7408
7409      There are three cases we are concerned with.  First we have the situation
7410      of a giv that is only updated conditionally.  In that case, it may not
7411      derive any givs after a label is passed.
7412
7413      The second case is when a biv update occurs, or may occur, after the
7414      definition of a giv.  For certain biv updates (see below) that are
7415      known to occur between the giv definition and use, we can adjust the
7416      giv definition.  For others, or when the biv update is conditional,
7417      we must prevent the giv from deriving any other givs.  There are two
7418      sub-cases within this case.
7419
7420      If this is a label, we are concerned with any biv update that is done
7421      conditionally, since it may be done after the giv is defined followed by
7422      a branch here (actually, we need to pass both a jump and a label, but
7423      this extra tracking doesn't seem worth it).
7424
7425      If this is a jump, we are concerned about any biv update that may be
7426      executed multiple times.  We are actually only concerned about
7427      backward jumps, but it is probably not worth performing the test
7428      on the jump again here.
7429
7430      If this is a biv update, we must adjust the giv status to show that a
7431      subsequent biv update was performed.  If this adjustment cannot be done,
7432      the giv cannot derive further givs.  */
7433
7434   for (bl = ivs->list; bl; bl = bl->next)
7435     for (biv = bl->biv; biv; biv = biv->next_iv)
7436       if (LABEL_P (p) || JUMP_P (p)
7437           || biv->insn == p)
7438         {
7439           /* Skip if location is the same as a previous one.  */
7440           if (biv->same)
7441             continue;
7442
7443           for (giv = bl->giv; giv; giv = giv->next_iv)
7444             {
7445               /* If cant_derive is already true, there is no point in
7446                  checking all of these conditions again.  */
7447               if (giv->cant_derive)
7448                 continue;
7449
7450               /* If this giv is conditionally set and we have passed a label,
7451                  it cannot derive anything.  */
7452               if (LABEL_P (p) && ! giv->always_computable)
7453                 giv->cant_derive = 1;
7454
7455               /* Skip givs that have mult_val == 0, since
7456                  they are really invariants.  Also skip those that are
7457                  replaceable, since we know their lifetime doesn't contain
7458                  any biv update.  */
7459               else if (giv->mult_val == const0_rtx || giv->replaceable)
7460                 continue;
7461
7462               /* The only way we can allow this giv to derive another
7463                  is if this is a biv increment and we can form the product
7464                  of biv->add_val and giv->mult_val.  In this case, we will
7465                  be able to compute a compensation.  */
7466               else if (biv->insn == p)
7467                 {
7468                   rtx ext_val_dummy;
7469
7470                   tem = 0;
7471                   if (biv->mult_val == const1_rtx)
7472                     tem = simplify_giv_expr (loop,
7473                                              gen_rtx_MULT (giv->mode,
7474                                                            biv->add_val,
7475                                                            giv->mult_val),
7476                                              &ext_val_dummy, &dummy);
7477
7478                   if (tem && giv->derive_adjustment)
7479                     tem = simplify_giv_expr
7480                       (loop,
7481                        gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
7482                        &ext_val_dummy, &dummy);
7483
7484                   if (tem)
7485                     giv->derive_adjustment = tem;
7486                   else
7487                     giv->cant_derive = 1;
7488                 }
7489               else if ((LABEL_P (p) && ! biv->always_computable)
7490                        || (JUMP_P (p) && biv->maybe_multiple))
7491                 giv->cant_derive = 1;
7492             }
7493         }
7494 }
7495 \f
7496 /* Check whether an insn is an increment legitimate for a basic induction var.
7497    X is the source of insn P, or a part of it.
7498    MODE is the mode in which X should be interpreted.
7499
7500    DEST_REG is the putative biv, also the destination of the insn.
7501    We accept patterns of these forms:
7502      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
7503      REG = INVARIANT + REG
7504
7505    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
7506    store the additive term into *INC_VAL, and store the place where
7507    we found the additive term into *LOCATION.
7508
7509    If X is an assignment of an invariant into DEST_REG, we set
7510    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
7511
7512    We also want to detect a BIV when it corresponds to a variable
7513    whose mode was promoted.  In that case, an increment
7514    of the variable may be a PLUS that adds a SUBREG of that variable to
7515    an invariant and then sign- or zero-extends the result of the PLUS
7516    into the variable.
7517
7518    Most GIVs in such cases will be in the promoted mode, since that is the
7519    probably the natural computation mode (and almost certainly the mode
7520    used for addresses) on the machine.  So we view the pseudo-reg containing
7521    the variable as the BIV, as if it were simply incremented.
7522
7523    Note that treating the entire pseudo as a BIV will result in making
7524    simple increments to any GIVs based on it.  However, if the variable
7525    overflows in its declared mode but not its promoted mode, the result will
7526    be incorrect.  This is acceptable if the variable is signed, since
7527    overflows in such cases are undefined, but not if it is unsigned, since
7528    those overflows are defined.  So we only check for SIGN_EXTEND and
7529    not ZERO_EXTEND.
7530
7531    If we cannot find a biv, we return 0.  */
7532
7533 static int
7534 basic_induction_var (const struct loop *loop, rtx x, enum machine_mode mode,
7535                      rtx dest_reg, rtx p, rtx *inc_val, rtx *mult_val,
7536                      rtx **location)
7537 {
7538   enum rtx_code code;
7539   rtx *argp, arg;
7540   rtx insn, set = 0, last, inc;
7541
7542   code = GET_CODE (x);
7543   *location = NULL;
7544   switch (code)
7545     {
7546     case PLUS:
7547       if (rtx_equal_p (XEXP (x, 0), dest_reg)
7548           || (GET_CODE (XEXP (x, 0)) == SUBREG
7549               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
7550               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
7551         {
7552           argp = &XEXP (x, 1);
7553         }
7554       else if (rtx_equal_p (XEXP (x, 1), dest_reg)
7555                || (GET_CODE (XEXP (x, 1)) == SUBREG
7556                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
7557                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
7558         {
7559           argp = &XEXP (x, 0);
7560         }
7561       else
7562         return 0;
7563
7564       arg = *argp;
7565       if (loop_invariant_p (loop, arg) != 1)
7566         return 0;
7567
7568       /* convert_modes can emit new instructions, e.g. when arg is a loop
7569          invariant MEM and dest_reg has a different mode.
7570          These instructions would be emitted after the end of the function
7571          and then *inc_val would be an uninitialized pseudo.
7572          Detect this and bail in this case.
7573          Other alternatives to solve this can be introducing a convert_modes
7574          variant which is allowed to fail but not allowed to emit new
7575          instructions, emit these instructions before loop start and let
7576          it be garbage collected if *inc_val is never used or saving the
7577          *inc_val initialization sequence generated here and when *inc_val
7578          is going to be actually used, emit it at some suitable place.  */
7579       last = get_last_insn ();
7580       inc = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
7581       if (get_last_insn () != last)
7582         {
7583           delete_insns_since (last);
7584           return 0;
7585         }
7586
7587       *inc_val = inc;
7588       *mult_val = const1_rtx;
7589       *location = argp;
7590       return 1;
7591
7592     case SUBREG:
7593       /* If what's inside the SUBREG is a BIV, then the SUBREG.  This will
7594          handle addition of promoted variables.
7595          ??? The comment at the start of this function is wrong: promoted
7596          variable increments don't look like it says they do.  */
7597       return basic_induction_var (loop, SUBREG_REG (x),
7598                                   GET_MODE (SUBREG_REG (x)),
7599                                   dest_reg, p, inc_val, mult_val, location);
7600
7601     case REG:
7602       /* If this register is assigned in a previous insn, look at its
7603          source, but don't go outside the loop or past a label.  */
7604
7605       /* If this sets a register to itself, we would repeat any previous
7606          biv increment if we applied this strategy blindly.  */
7607       if (rtx_equal_p (dest_reg, x))
7608         return 0;
7609
7610       insn = p;
7611       while (1)
7612         {
7613           rtx dest;
7614           do
7615             {
7616               insn = PREV_INSN (insn);
7617             }
7618           while (insn && NOTE_P (insn)
7619                  && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
7620
7621           if (!insn)
7622             break;
7623           set = single_set (insn);
7624           if (set == 0)
7625             break;
7626           dest = SET_DEST (set);
7627           if (dest == x
7628               || (GET_CODE (dest) == SUBREG
7629                   && (GET_MODE_SIZE (GET_MODE (dest)) <= UNITS_PER_WORD)
7630                   && (GET_MODE_CLASS (GET_MODE (dest)) == MODE_INT)
7631                   && SUBREG_REG (dest) == x))
7632             return basic_induction_var (loop, SET_SRC (set),
7633                                         (GET_MODE (SET_SRC (set)) == VOIDmode
7634                                          ? GET_MODE (x)
7635                                          : GET_MODE (SET_SRC (set))),
7636                                         dest_reg, insn,
7637                                         inc_val, mult_val, location);
7638
7639           while (GET_CODE (dest) == SUBREG
7640                  || GET_CODE (dest) == ZERO_EXTRACT
7641                  || GET_CODE (dest) == STRICT_LOW_PART)
7642             dest = XEXP (dest, 0);
7643           if (dest == x)
7644             break;
7645         }
7646       /* Fall through.  */
7647
7648       /* Can accept constant setting of biv only when inside inner most loop.
7649          Otherwise, a biv of an inner loop may be incorrectly recognized
7650          as a biv of the outer loop,
7651          causing code to be moved INTO the inner loop.  */
7652     case MEM:
7653       if (loop_invariant_p (loop, x) != 1)
7654         return 0;
7655     case CONST_INT:
7656     case SYMBOL_REF:
7657     case CONST:
7658       /* convert_modes dies if we try to convert to or from CCmode, so just
7659          exclude that case.  It is very unlikely that a condition code value
7660          would be a useful iterator anyways.  convert_modes dies if we try to
7661          convert a float mode to non-float or vice versa too.  */
7662       if (loop->level == 1
7663           && GET_MODE_CLASS (mode) == GET_MODE_CLASS (GET_MODE (dest_reg))
7664           && GET_MODE_CLASS (mode) != MODE_CC)
7665         {
7666           /* Possible bug here?  Perhaps we don't know the mode of X.  */
7667           last = get_last_insn ();
7668           inc = convert_modes (GET_MODE (dest_reg), mode, x, 0);
7669           if (get_last_insn () != last)
7670             {
7671               delete_insns_since (last);
7672               return 0;
7673             }
7674
7675           *inc_val = inc;
7676           *mult_val = const0_rtx;
7677           return 1;
7678         }
7679       else
7680         return 0;
7681
7682     case SIGN_EXTEND:
7683       /* Ignore this BIV if signed arithmetic overflow is defined.  */
7684       if (flag_wrapv)
7685         return 0;
7686       return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
7687                                   dest_reg, p, inc_val, mult_val, location);
7688
7689     case ASHIFTRT:
7690       /* Similar, since this can be a sign extension.  */
7691       for (insn = PREV_INSN (p);
7692            (insn && NOTE_P (insn)
7693             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
7694            insn = PREV_INSN (insn))
7695         ;
7696
7697       if (insn)
7698         set = single_set (insn);
7699
7700       if (! rtx_equal_p (dest_reg, XEXP (x, 0))
7701           && set && SET_DEST (set) == XEXP (x, 0)
7702           && GET_CODE (XEXP (x, 1)) == CONST_INT
7703           && INTVAL (XEXP (x, 1)) >= 0
7704           && GET_CODE (SET_SRC (set)) == ASHIFT
7705           && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
7706         return basic_induction_var (loop, XEXP (SET_SRC (set), 0),
7707                                     GET_MODE (XEXP (x, 0)),
7708                                     dest_reg, insn, inc_val, mult_val,
7709                                     location);
7710       return 0;
7711
7712     default:
7713       return 0;
7714     }
7715 }
7716 \f
7717 /* A general induction variable (giv) is any quantity that is a linear
7718    function   of a basic induction variable,
7719    i.e. giv = biv * mult_val + add_val.
7720    The coefficients can be any loop invariant quantity.
7721    A giv need not be computed directly from the biv;
7722    it can be computed by way of other givs.  */
7723
7724 /* Determine whether X computes a giv.
7725    If it does, return a nonzero value
7726      which is the benefit from eliminating the computation of X;
7727    set *SRC_REG to the register of the biv that it is computed from;
7728    set *ADD_VAL and *MULT_VAL to the coefficients,
7729      such that the value of X is biv * mult + add;  */
7730
7731 static int
7732 general_induction_var (const struct loop *loop, rtx x, rtx *src_reg,
7733                        rtx *add_val, rtx *mult_val, rtx *ext_val,
7734                        int is_addr, int *pbenefit,
7735                        enum machine_mode addr_mode)
7736 {
7737   struct loop_ivs *ivs = LOOP_IVS (loop);
7738   rtx orig_x = x;
7739
7740   /* If this is an invariant, forget it, it isn't a giv.  */
7741   if (loop_invariant_p (loop, x) == 1)
7742     return 0;
7743
7744   *pbenefit = 0;
7745   *ext_val = NULL_RTX;
7746   x = simplify_giv_expr (loop, x, ext_val, pbenefit);
7747   if (x == 0)
7748     return 0;
7749
7750   switch (GET_CODE (x))
7751     {
7752     case USE:
7753     case CONST_INT:
7754       /* Since this is now an invariant and wasn't before, it must be a giv
7755          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
7756          with.  */
7757       *src_reg = ivs->list->biv->dest_reg;
7758       *mult_val = const0_rtx;
7759       *add_val = x;
7760       break;
7761
7762     case REG:
7763       /* This is equivalent to a BIV.  */
7764       *src_reg = x;
7765       *mult_val = const1_rtx;
7766       *add_val = const0_rtx;
7767       break;
7768
7769     case PLUS:
7770       /* Either (plus (biv) (invar)) or
7771          (plus (mult (biv) (invar_1)) (invar_2)).  */
7772       if (GET_CODE (XEXP (x, 0)) == MULT)
7773         {
7774           *src_reg = XEXP (XEXP (x, 0), 0);
7775           *mult_val = XEXP (XEXP (x, 0), 1);
7776         }
7777       else
7778         {
7779           *src_reg = XEXP (x, 0);
7780           *mult_val = const1_rtx;
7781         }
7782       *add_val = XEXP (x, 1);
7783       break;
7784
7785     case MULT:
7786       /* ADD_VAL is zero.  */
7787       *src_reg = XEXP (x, 0);
7788       *mult_val = XEXP (x, 1);
7789       *add_val = const0_rtx;
7790       break;
7791
7792     default:
7793       gcc_unreachable ();
7794     }
7795
7796   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
7797      unless they are CONST_INT).  */
7798   if (GET_CODE (*add_val) == USE)
7799     *add_val = XEXP (*add_val, 0);
7800   if (GET_CODE (*mult_val) == USE)
7801     *mult_val = XEXP (*mult_val, 0);
7802
7803   if (is_addr)
7804     *pbenefit += address_cost (orig_x, addr_mode) - reg_address_cost;
7805   else
7806     *pbenefit += rtx_cost (orig_x, SET);
7807
7808   /* Always return true if this is a giv so it will be detected as such,
7809      even if the benefit is zero or negative.  This allows elimination
7810      of bivs that might otherwise not be eliminated.  */
7811   return 1;
7812 }
7813 \f
7814 /* Given an expression, X, try to form it as a linear function of a biv.
7815    We will canonicalize it to be of the form
7816         (plus (mult (BIV) (invar_1))
7817               (invar_2))
7818    with possible degeneracies.
7819
7820    The invariant expressions must each be of a form that can be used as a
7821    machine operand.  We surround then with a USE rtx (a hack, but localized
7822    and certainly unambiguous!) if not a CONST_INT for simplicity in this
7823    routine; it is the caller's responsibility to strip them.
7824
7825    If no such canonicalization is possible (i.e., two biv's are used or an
7826    expression that is neither invariant nor a biv or giv), this routine
7827    returns 0.
7828
7829    For a nonzero return, the result will have a code of CONST_INT, USE,
7830    REG (for a BIV), PLUS, or MULT.  No other codes will occur.
7831
7832    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
7833
7834 static rtx sge_plus (enum machine_mode, rtx, rtx);
7835 static rtx sge_plus_constant (rtx, rtx);
7836
7837 static rtx
7838 simplify_giv_expr (const struct loop *loop, rtx x, rtx *ext_val, int *benefit)
7839 {
7840   struct loop_ivs *ivs = LOOP_IVS (loop);
7841   struct loop_regs *regs = LOOP_REGS (loop);
7842   enum machine_mode mode = GET_MODE (x);
7843   rtx arg0, arg1;
7844   rtx tem;
7845
7846   /* If this is not an integer mode, or if we cannot do arithmetic in this
7847      mode, this can't be a giv.  */
7848   if (mode != VOIDmode
7849       && (GET_MODE_CLASS (mode) != MODE_INT
7850           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
7851     return NULL_RTX;
7852
7853   switch (GET_CODE (x))
7854     {
7855     case PLUS:
7856       arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
7857       arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
7858       if (arg0 == 0 || arg1 == 0)
7859         return NULL_RTX;
7860
7861       /* Put constant last, CONST_INT last if both constant.  */
7862       if ((GET_CODE (arg0) == USE
7863            || GET_CODE (arg0) == CONST_INT)
7864           && ! ((GET_CODE (arg0) == USE
7865                  && GET_CODE (arg1) == USE)
7866                 || GET_CODE (arg1) == CONST_INT))
7867         tem = arg0, arg0 = arg1, arg1 = tem;
7868
7869       /* Handle addition of zero, then addition of an invariant.  */
7870       if (arg1 == const0_rtx)
7871         return arg0;
7872       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
7873         switch (GET_CODE (arg0))
7874           {
7875           case CONST_INT:
7876           case USE:
7877             /* Adding two invariants must result in an invariant, so enclose
7878                addition operation inside a USE and return it.  */
7879             if (GET_CODE (arg0) == USE)
7880               arg0 = XEXP (arg0, 0);
7881             if (GET_CODE (arg1) == USE)
7882               arg1 = XEXP (arg1, 0);
7883
7884             if (GET_CODE (arg0) == CONST_INT)
7885               tem = arg0, arg0 = arg1, arg1 = tem;
7886             if (GET_CODE (arg1) == CONST_INT)
7887               tem = sge_plus_constant (arg0, arg1);
7888             else
7889               tem = sge_plus (mode, arg0, arg1);
7890
7891             if (GET_CODE (tem) != CONST_INT)
7892               tem = gen_rtx_USE (mode, tem);
7893             return tem;
7894
7895           case REG:
7896           case MULT:
7897             /* biv + invar or mult + invar.  Return sum.  */
7898             return gen_rtx_PLUS (mode, arg0, arg1);
7899
7900           case PLUS:
7901             /* (a + invar_1) + invar_2.  Associate.  */
7902             return
7903               simplify_giv_expr (loop,
7904                                  gen_rtx_PLUS (mode,
7905                                                XEXP (arg0, 0),
7906                                                gen_rtx_PLUS (mode,
7907                                                              XEXP (arg0, 1),
7908                                                              arg1)),
7909                                  ext_val, benefit);
7910
7911           default:
7912             gcc_unreachable ();
7913           }
7914
7915       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
7916          MULT to reduce cases.  */
7917       if (REG_P (arg0))
7918         arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
7919       if (REG_P (arg1))
7920         arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
7921
7922       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
7923          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
7924          Recurse to associate the second PLUS.  */
7925       if (GET_CODE (arg1) == MULT)
7926         tem = arg0, arg0 = arg1, arg1 = tem;
7927
7928       if (GET_CODE (arg1) == PLUS)
7929         return
7930           simplify_giv_expr (loop,
7931                              gen_rtx_PLUS (mode,
7932                                            gen_rtx_PLUS (mode, arg0,
7933                                                          XEXP (arg1, 0)),
7934                                            XEXP (arg1, 1)),
7935                              ext_val, benefit);
7936
7937       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
7938       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
7939         return NULL_RTX;
7940
7941       if (!rtx_equal_p (arg0, arg1))
7942         return NULL_RTX;
7943
7944       return simplify_giv_expr (loop,
7945                                 gen_rtx_MULT (mode,
7946                                               XEXP (arg0, 0),
7947                                               gen_rtx_PLUS (mode,
7948                                                             XEXP (arg0, 1),
7949                                                             XEXP (arg1, 1))),
7950                                 ext_val, benefit);
7951
7952     case MINUS:
7953       /* Handle "a - b" as "a + b * (-1)".  */
7954       return simplify_giv_expr (loop,
7955                                 gen_rtx_PLUS (mode,
7956                                               XEXP (x, 0),
7957                                               gen_rtx_MULT (mode,
7958                                                             XEXP (x, 1),
7959                                                             constm1_rtx)),
7960                                 ext_val, benefit);
7961
7962     case MULT:
7963       arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
7964       arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
7965       if (arg0 == 0 || arg1 == 0)
7966         return NULL_RTX;
7967
7968       /* Put constant last, CONST_INT last if both constant.  */
7969       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
7970           && GET_CODE (arg1) != CONST_INT)
7971         tem = arg0, arg0 = arg1, arg1 = tem;
7972
7973       /* If second argument is not now constant, not giv.  */
7974       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
7975         return NULL_RTX;
7976
7977       /* Handle multiply by 0 or 1.  */
7978       if (arg1 == const0_rtx)
7979         return const0_rtx;
7980
7981       else if (arg1 == const1_rtx)
7982         return arg0;
7983
7984       switch (GET_CODE (arg0))
7985         {
7986         case REG:
7987           /* biv * invar.  Done.  */
7988           return gen_rtx_MULT (mode, arg0, arg1);
7989
7990         case CONST_INT:
7991           /* Product of two constants.  */
7992           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
7993
7994         case USE:
7995           /* invar * invar is a giv, but attempt to simplify it somehow.  */
7996           if (GET_CODE (arg1) != CONST_INT)
7997             return NULL_RTX;
7998
7999           arg0 = XEXP (arg0, 0);
8000           if (GET_CODE (arg0) == MULT)
8001             {
8002               /* (invar_0 * invar_1) * invar_2.  Associate.  */
8003               return simplify_giv_expr (loop,
8004                                         gen_rtx_MULT (mode,
8005                                                       XEXP (arg0, 0),
8006                                                       gen_rtx_MULT (mode,
8007                                                                     XEXP (arg0,
8008                                                                           1),
8009                                                                     arg1)),
8010                                         ext_val, benefit);
8011             }
8012           /* Propagate the MULT expressions to the innermost nodes.  */
8013           else if (GET_CODE (arg0) == PLUS)
8014             {
8015               /* (invar_0 + invar_1) * invar_2.  Distribute.  */
8016               return simplify_giv_expr (loop,
8017                                         gen_rtx_PLUS (mode,
8018                                                       gen_rtx_MULT (mode,
8019                                                                     XEXP (arg0,
8020                                                                           0),
8021                                                                     arg1),
8022                                                       gen_rtx_MULT (mode,
8023                                                                     XEXP (arg0,
8024                                                                           1),
8025                                                                     arg1)),
8026                                         ext_val, benefit);
8027             }
8028           return gen_rtx_USE (mode, gen_rtx_MULT (mode, arg0, arg1));
8029
8030         case MULT:
8031           /* (a * invar_1) * invar_2.  Associate.  */
8032           return simplify_giv_expr (loop,
8033                                     gen_rtx_MULT (mode,
8034                                                   XEXP (arg0, 0),
8035                                                   gen_rtx_MULT (mode,
8036                                                                 XEXP (arg0, 1),
8037                                                                 arg1)),
8038                                     ext_val, benefit);
8039
8040         case PLUS:
8041           /* (a + invar_1) * invar_2.  Distribute.  */
8042           return simplify_giv_expr (loop,
8043                                     gen_rtx_PLUS (mode,
8044                                                   gen_rtx_MULT (mode,
8045                                                                 XEXP (arg0, 0),
8046                                                                 arg1),
8047                                                   gen_rtx_MULT (mode,
8048                                                                 XEXP (arg0, 1),
8049                                                                 arg1)),
8050                                     ext_val, benefit);
8051
8052         default:
8053           gcc_unreachable ();
8054         }
8055
8056     case ASHIFT:
8057       /* Shift by constant is multiply by power of two.  */
8058       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
8059         return 0;
8060
8061       return
8062         simplify_giv_expr (loop,
8063                            gen_rtx_MULT (mode,
8064                                          XEXP (x, 0),
8065                                          GEN_INT ((HOST_WIDE_INT) 1
8066                                                   << INTVAL (XEXP (x, 1)))),
8067                            ext_val, benefit);
8068
8069     case NEG:
8070       /* "-a" is "a * (-1)" */
8071       return simplify_giv_expr (loop,
8072                                 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
8073                                 ext_val, benefit);
8074
8075     case NOT:
8076       /* "~a" is "-a - 1". Silly, but easy.  */
8077       return simplify_giv_expr (loop,
8078                                 gen_rtx_MINUS (mode,
8079                                                gen_rtx_NEG (mode, XEXP (x, 0)),
8080                                                const1_rtx),
8081                                 ext_val, benefit);
8082
8083     case USE:
8084       /* Already in proper form for invariant.  */
8085       return x;
8086
8087     case SIGN_EXTEND:
8088     case ZERO_EXTEND:
8089     case TRUNCATE:
8090       /* Conditionally recognize extensions of simple IVs.  After we've
8091          computed loop traversal counts and verified the range of the
8092          source IV, we'll reevaluate this as a GIV.  */
8093       if (*ext_val == NULL_RTX)
8094         {
8095           arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
8096           if (arg0 && *ext_val == NULL_RTX && REG_P (arg0))
8097             {
8098               *ext_val = gen_rtx_fmt_e (GET_CODE (x), mode, arg0);
8099               return arg0;
8100             }
8101         }
8102       goto do_default;
8103
8104     case REG:
8105       /* If this is a new register, we can't deal with it.  */
8106       if (REGNO (x) >= max_reg_before_loop)
8107         return 0;
8108
8109       /* Check for biv or giv.  */
8110       switch (REG_IV_TYPE (ivs, REGNO (x)))
8111         {
8112         case BASIC_INDUCT:
8113           return x;
8114         case GENERAL_INDUCT:
8115           {
8116             struct induction *v = REG_IV_INFO (ivs, REGNO (x));
8117
8118             /* Form expression from giv and add benefit.  Ensure this giv
8119                can derive another and subtract any needed adjustment if so.  */
8120
8121             /* Increasing the benefit here is risky.  The only case in which it
8122                is arguably correct is if this is the only use of V.  In other
8123                cases, this will artificially inflate the benefit of the current
8124                giv, and lead to suboptimal code.  Thus, it is disabled, since
8125                potentially not reducing an only marginally beneficial giv is
8126                less harmful than reducing many givs that are not really
8127                beneficial.  */
8128             {
8129               rtx single_use = regs->array[REGNO (x)].single_usage;
8130               if (single_use && single_use != const0_rtx)
8131                 *benefit += v->benefit;
8132             }
8133
8134             if (v->cant_derive)
8135               return 0;
8136
8137             tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
8138                                                     v->src_reg, v->mult_val),
8139                                 v->add_val);
8140
8141             if (v->derive_adjustment)
8142               tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
8143             arg0 = simplify_giv_expr (loop, tem, ext_val, benefit);
8144             if (*ext_val)
8145               {
8146                 if (!v->ext_dependent)
8147                   return arg0;
8148               }
8149             else
8150               {
8151                 *ext_val = v->ext_dependent;
8152                 return arg0;
8153               }
8154             return 0;
8155           }
8156
8157         default:
8158         do_default:
8159           /* If it isn't an induction variable, and it is invariant, we
8160              may be able to simplify things further by looking through
8161              the bits we just moved outside the loop.  */
8162           if (loop_invariant_p (loop, x) == 1)
8163             {
8164               struct movable *m;
8165               struct loop_movables *movables = LOOP_MOVABLES (loop);
8166
8167               for (m = movables->head; m; m = m->next)
8168                 if (rtx_equal_p (x, m->set_dest))
8169                   {
8170                     /* Ok, we found a match.  Substitute and simplify.  */
8171
8172                     /* If we match another movable, we must use that, as
8173                        this one is going away.  */
8174                     if (m->match)
8175                       return simplify_giv_expr (loop, m->match->set_dest,
8176                                                 ext_val, benefit);
8177
8178                     /* If consec is nonzero, this is a member of a group of
8179                        instructions that were moved together.  We handle this
8180                        case only to the point of seeking to the last insn and
8181                        looking for a REG_EQUAL.  Fail if we don't find one.  */
8182                     if (m->consec != 0)
8183                       {
8184                         int i = m->consec;
8185                         tem = m->insn;
8186                         do
8187                           {
8188                             tem = NEXT_INSN (tem);
8189                           }
8190                         while (--i > 0);
8191
8192                         tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
8193                         if (tem)
8194                           tem = XEXP (tem, 0);
8195                       }
8196                     else
8197                       {
8198                         tem = single_set (m->insn);
8199                         if (tem)
8200                           tem = SET_SRC (tem);
8201                       }
8202
8203                     if (tem)
8204                       {
8205                         /* What we are most interested in is pointer
8206                            arithmetic on invariants -- only take
8207                            patterns we may be able to do something with.  */
8208                         if (GET_CODE (tem) == PLUS
8209                             || GET_CODE (tem) == MULT
8210                             || GET_CODE (tem) == ASHIFT
8211                             || GET_CODE (tem) == CONST_INT
8212                             || GET_CODE (tem) == SYMBOL_REF)
8213                           {
8214                             tem = simplify_giv_expr (loop, tem, ext_val,
8215                                                      benefit);
8216                             if (tem)
8217                               return tem;
8218                           }
8219                         else if (GET_CODE (tem) == CONST
8220                                  && GET_CODE (XEXP (tem, 0)) == PLUS
8221                                  && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
8222                                  && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
8223                           {
8224                             tem = simplify_giv_expr (loop, XEXP (tem, 0),
8225                                                      ext_val, benefit);
8226                             if (tem)
8227                               return tem;
8228                           }
8229                       }
8230                     break;
8231                   }
8232             }
8233           break;
8234         }
8235
8236       /* Fall through to general case.  */
8237     default:
8238       /* If invariant, return as USE (unless CONST_INT).
8239          Otherwise, not giv.  */
8240       if (GET_CODE (x) == USE)
8241         x = XEXP (x, 0);
8242
8243       if (loop_invariant_p (loop, x) == 1)
8244         {
8245           if (GET_CODE (x) == CONST_INT)
8246             return x;
8247           if (GET_CODE (x) == CONST
8248               && GET_CODE (XEXP (x, 0)) == PLUS
8249               && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
8250               && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
8251             x = XEXP (x, 0);
8252           return gen_rtx_USE (mode, x);
8253         }
8254       else
8255         return 0;
8256     }
8257 }
8258
8259 /* This routine folds invariants such that there is only ever one
8260    CONST_INT in the summation.  It is only used by simplify_giv_expr.  */
8261
8262 static rtx
8263 sge_plus_constant (rtx x, rtx c)
8264 {
8265   if (GET_CODE (x) == CONST_INT)
8266     return GEN_INT (INTVAL (x) + INTVAL (c));
8267   else if (GET_CODE (x) != PLUS)
8268     return gen_rtx_PLUS (GET_MODE (x), x, c);
8269   else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
8270     {
8271       return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
8272                            GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
8273     }
8274   else if (GET_CODE (XEXP (x, 0)) == PLUS
8275            || GET_CODE (XEXP (x, 1)) != PLUS)
8276     {
8277       return gen_rtx_PLUS (GET_MODE (x),
8278                            sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
8279     }
8280   else
8281     {
8282       return gen_rtx_PLUS (GET_MODE (x),
8283                            sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
8284     }
8285 }
8286
8287 static rtx
8288 sge_plus (enum machine_mode mode, rtx x, rtx y)
8289 {
8290   while (GET_CODE (y) == PLUS)
8291     {
8292       rtx a = XEXP (y, 0);
8293       if (GET_CODE (a) == CONST_INT)
8294         x = sge_plus_constant (x, a);
8295       else
8296         x = gen_rtx_PLUS (mode, x, a);
8297       y = XEXP (y, 1);
8298     }
8299   if (GET_CODE (y) == CONST_INT)
8300     x = sge_plus_constant (x, y);
8301   else
8302     x = gen_rtx_PLUS (mode, x, y);
8303   return x;
8304 }
8305 \f
8306 /* Help detect a giv that is calculated by several consecutive insns;
8307    for example,
8308       giv = biv * M
8309       giv = giv + A
8310    The caller has already identified the first insn P as having a giv as dest;
8311    we check that all other insns that set the same register follow
8312    immediately after P, that they alter nothing else,
8313    and that the result of the last is still a giv.
8314
8315    The value is 0 if the reg set in P is not really a giv.
8316    Otherwise, the value is the amount gained by eliminating
8317    all the consecutive insns that compute the value.
8318
8319    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
8320    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
8321
8322    The coefficients of the ultimate giv value are stored in
8323    *MULT_VAL and *ADD_VAL.  */
8324
8325 static int
8326 consec_sets_giv (const struct loop *loop, int first_benefit, rtx p,
8327                  rtx src_reg, rtx dest_reg, rtx *add_val, rtx *mult_val,
8328                  rtx *ext_val, rtx *last_consec_insn)
8329 {
8330   struct loop_ivs *ivs = LOOP_IVS (loop);
8331   struct loop_regs *regs = LOOP_REGS (loop);
8332   int count;
8333   enum rtx_code code;
8334   int benefit;
8335   rtx temp;
8336   rtx set;
8337
8338   /* Indicate that this is a giv so that we can update the value produced in
8339      each insn of the multi-insn sequence.
8340
8341      This induction structure will be used only by the call to
8342      general_induction_var below, so we can allocate it on our stack.
8343      If this is a giv, our caller will replace the induct var entry with
8344      a new induction structure.  */
8345   struct induction *v;
8346
8347   if (REG_IV_TYPE (ivs, REGNO (dest_reg)) != UNKNOWN_INDUCT)
8348     return 0;
8349
8350   v = alloca (sizeof (struct induction));
8351   v->src_reg = src_reg;
8352   v->mult_val = *mult_val;
8353   v->add_val = *add_val;
8354   v->benefit = first_benefit;
8355   v->cant_derive = 0;
8356   v->derive_adjustment = 0;
8357   v->ext_dependent = NULL_RTX;
8358
8359   REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
8360   REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
8361
8362   count = regs->array[REGNO (dest_reg)].n_times_set - 1;
8363
8364   while (count > 0)
8365     {
8366       p = NEXT_INSN (p);
8367       code = GET_CODE (p);
8368
8369       /* If libcall, skip to end of call sequence.  */
8370       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
8371         p = XEXP (temp, 0);
8372
8373       if (code == INSN
8374           && (set = single_set (p))
8375           && REG_P (SET_DEST (set))
8376           && SET_DEST (set) == dest_reg
8377           && (general_induction_var (loop, SET_SRC (set), &src_reg,
8378                                      add_val, mult_val, ext_val, 0,
8379                                      &benefit, VOIDmode)
8380               /* Giv created by equivalent expression.  */
8381               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
8382                   && general_induction_var (loop, XEXP (temp, 0), &src_reg,
8383                                             add_val, mult_val, ext_val, 0,
8384                                             &benefit, VOIDmode)))
8385           && src_reg == v->src_reg)
8386         {
8387           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
8388             benefit += libcall_benefit (p);
8389
8390           count--;
8391           v->mult_val = *mult_val;
8392           v->add_val = *add_val;
8393           v->benefit += benefit;
8394         }
8395       else if (code != NOTE)
8396         {
8397           /* Allow insns that set something other than this giv to a
8398              constant.  Such insns are needed on machines which cannot
8399              include long constants and should not disqualify a giv.  */
8400           if (code == INSN
8401               && (set = single_set (p))
8402               && SET_DEST (set) != dest_reg
8403               && CONSTANT_P (SET_SRC (set)))
8404             continue;
8405
8406           REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
8407           return 0;
8408         }
8409     }
8410
8411   REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
8412   *last_consec_insn = p;
8413   return v->benefit;
8414 }
8415 \f
8416 /* Return an rtx, if any, that expresses giv G2 as a function of the register
8417    represented by G1.  If no such expression can be found, or it is clear that
8418    it cannot possibly be a valid address, 0 is returned.
8419
8420    To perform the computation, we note that
8421         G1 = x * v + a          and
8422         G2 = y * v + b
8423    where `v' is the biv.
8424
8425    So G2 = (y/b) * G1 + (b - a*y/x).
8426
8427    Note that MULT = y/x.
8428
8429    Update: A and B are now allowed to be additive expressions such that
8430    B contains all variables in A.  That is, computing B-A will not require
8431    subtracting variables.  */
8432
8433 static rtx
8434 express_from_1 (rtx a, rtx b, rtx mult)
8435 {
8436   /* If MULT is zero, then A*MULT is zero, and our expression is B.  */
8437
8438   if (mult == const0_rtx)
8439     return b;
8440
8441   /* If MULT is not 1, we cannot handle A with non-constants, since we
8442      would then be required to subtract multiples of the registers in A.
8443      This is theoretically possible, and may even apply to some Fortran
8444      constructs, but it is a lot of work and we do not attempt it here.  */
8445
8446   if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
8447     return NULL_RTX;
8448
8449   /* In general these structures are sorted top to bottom (down the PLUS
8450      chain), but not left to right across the PLUS.  If B is a higher
8451      order giv than A, we can strip one level and recurse.  If A is higher
8452      order, we'll eventually bail out, but won't know that until the end.
8453      If they are the same, we'll strip one level around this loop.  */
8454
8455   while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
8456     {
8457       rtx ra, rb, oa, ob, tmp;
8458
8459       ra = XEXP (a, 0), oa = XEXP (a, 1);
8460       if (GET_CODE (ra) == PLUS)
8461         tmp = ra, ra = oa, oa = tmp;
8462
8463       rb = XEXP (b, 0), ob = XEXP (b, 1);
8464       if (GET_CODE (rb) == PLUS)
8465         tmp = rb, rb = ob, ob = tmp;
8466
8467       if (rtx_equal_p (ra, rb))
8468         /* We matched: remove one reg completely.  */
8469         a = oa, b = ob;
8470       else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
8471         /* An alternate match.  */
8472         a = oa, b = rb;
8473       else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
8474         /* An alternate match.  */
8475         a = ra, b = ob;
8476       else
8477         {
8478           /* Indicates an extra register in B.  Strip one level from B and
8479              recurse, hoping B was the higher order expression.  */
8480           ob = express_from_1 (a, ob, mult);
8481           if (ob == NULL_RTX)
8482             return NULL_RTX;
8483           return gen_rtx_PLUS (GET_MODE (b), rb, ob);
8484         }
8485     }
8486
8487   /* Here we are at the last level of A, go through the cases hoping to
8488      get rid of everything but a constant.  */
8489
8490   if (GET_CODE (a) == PLUS)
8491     {
8492       rtx ra, oa;
8493
8494       ra = XEXP (a, 0), oa = XEXP (a, 1);
8495       if (rtx_equal_p (oa, b))
8496         oa = ra;
8497       else if (!rtx_equal_p (ra, b))
8498         return NULL_RTX;
8499
8500       if (GET_CODE (oa) != CONST_INT)
8501         return NULL_RTX;
8502
8503       return GEN_INT (-INTVAL (oa) * INTVAL (mult));
8504     }
8505   else if (GET_CODE (a) == CONST_INT)
8506     {
8507       return plus_constant (b, -INTVAL (a) * INTVAL (mult));
8508     }
8509   else if (CONSTANT_P (a))
8510     {
8511       enum machine_mode mode_a = GET_MODE (a);
8512       enum machine_mode mode_b = GET_MODE (b);
8513       enum machine_mode mode = mode_b == VOIDmode ? mode_a : mode_b;
8514       return simplify_gen_binary (MINUS, mode, b, a);
8515     }
8516   else if (GET_CODE (b) == PLUS)
8517     {
8518       if (rtx_equal_p (a, XEXP (b, 0)))
8519         return XEXP (b, 1);
8520       else if (rtx_equal_p (a, XEXP (b, 1)))
8521         return XEXP (b, 0);
8522       else
8523         return NULL_RTX;
8524     }
8525   else if (rtx_equal_p (a, b))
8526     return const0_rtx;
8527
8528   return NULL_RTX;
8529 }
8530
8531 static rtx
8532 express_from (struct induction *g1, struct induction *g2)
8533 {
8534   rtx mult, add;
8535
8536   /* The value that G1 will be multiplied by must be a constant integer.  Also,
8537      the only chance we have of getting a valid address is if b*c/a (see above
8538      for notation) is also an integer.  */
8539   if (GET_CODE (g1->mult_val) == CONST_INT
8540       && GET_CODE (g2->mult_val) == CONST_INT)
8541     {
8542       if (g1->mult_val == const0_rtx
8543           || (g1->mult_val == constm1_rtx
8544               && INTVAL (g2->mult_val)
8545                  == (HOST_WIDE_INT) 1 << (HOST_BITS_PER_WIDE_INT - 1))
8546           || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
8547         return NULL_RTX;
8548       mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
8549     }
8550   else if (rtx_equal_p (g1->mult_val, g2->mult_val))
8551     mult = const1_rtx;
8552   else
8553     {
8554       /* ??? Find out if the one is a multiple of the other?  */
8555       return NULL_RTX;
8556     }
8557
8558   add = express_from_1 (g1->add_val, g2->add_val, mult);
8559   if (add == NULL_RTX)
8560     {
8561       /* Failed.  If we've got a multiplication factor between G1 and G2,
8562          scale G1's addend and try again.  */
8563       if (INTVAL (mult) > 1)
8564         {
8565           rtx g1_add_val = g1->add_val;
8566           if (GET_CODE (g1_add_val) == MULT
8567               && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
8568             {
8569               HOST_WIDE_INT m;
8570               m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
8571               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
8572                                          XEXP (g1_add_val, 0), GEN_INT (m));
8573             }
8574           else
8575             {
8576               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
8577                                          mult);
8578             }
8579
8580           add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
8581         }
8582     }
8583   if (add == NULL_RTX)
8584     return NULL_RTX;
8585
8586   /* Form simplified final result.  */
8587   if (mult == const0_rtx)
8588     return add;
8589   else if (mult == const1_rtx)
8590     mult = g1->dest_reg;
8591   else
8592     mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
8593
8594   if (add == const0_rtx)
8595     return mult;
8596   else
8597     {
8598       if (GET_CODE (add) == PLUS
8599           && CONSTANT_P (XEXP (add, 1)))
8600         {
8601           rtx tem = XEXP (add, 1);
8602           mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
8603           add = tem;
8604         }
8605
8606       return gen_rtx_PLUS (g2->mode, mult, add);
8607     }
8608 }
8609 \f
8610 /* Return an rtx, if any, that expresses giv G2 as a function of the register
8611    represented by G1.  This indicates that G2 should be combined with G1 and
8612    that G2 can use (either directly or via an address expression) a register
8613    used to represent G1.  */
8614
8615 static rtx
8616 combine_givs_p (struct induction *g1, struct induction *g2)
8617 {
8618   rtx comb, ret;
8619
8620   /* With the introduction of ext dependent givs, we must care for modes.
8621      G2 must not use a wider mode than G1.  */
8622   if (GET_MODE_SIZE (g1->mode) < GET_MODE_SIZE (g2->mode))
8623     return NULL_RTX;
8624
8625   ret = comb = express_from (g1, g2);
8626   if (comb == NULL_RTX)
8627     return NULL_RTX;
8628   if (g1->mode != g2->mode)
8629     ret = gen_lowpart (g2->mode, comb);
8630
8631   /* If these givs are identical, they can be combined.  We use the results
8632      of express_from because the addends are not in a canonical form, so
8633      rtx_equal_p is a weaker test.  */
8634   /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
8635      combination to be the other way round.  */
8636   if (comb == g1->dest_reg
8637       && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
8638     {
8639       return ret;
8640     }
8641
8642   /* If G2 can be expressed as a function of G1 and that function is valid
8643      as an address and no more expensive than using a register for G2,
8644      the expression of G2 in terms of G1 can be used.  */
8645   if (ret != NULL_RTX
8646       && g2->giv_type == DEST_ADDR
8647       && memory_address_p (GET_MODE (g2->mem), ret))
8648     return ret;
8649
8650   return NULL_RTX;
8651 }
8652 \f
8653 /* See if BL is monotonic and has a constant per-iteration increment.
8654    Return the increment if so, otherwise return 0.  */
8655
8656 static HOST_WIDE_INT
8657 get_monotonic_increment (struct iv_class *bl)
8658 {
8659   struct induction *v;
8660   rtx incr;
8661
8662   /* Get the total increment and check that it is constant.  */
8663   incr = biv_total_increment (bl);
8664   if (incr == 0 || GET_CODE (incr) != CONST_INT)
8665     return 0;
8666
8667   for (v = bl->biv; v != 0; v = v->next_iv)
8668     {
8669       if (GET_CODE (v->add_val) != CONST_INT)
8670         return 0;
8671
8672       if (INTVAL (v->add_val) < 0 && INTVAL (incr) >= 0)
8673         return 0;
8674
8675       if (INTVAL (v->add_val) > 0 && INTVAL (incr) <= 0)
8676         return 0;
8677     }
8678   return INTVAL (incr);
8679 }
8680
8681
8682 /* Subroutine of biv_fits_mode_p.  Return true if biv BL, when biased by
8683    BIAS, will never exceed the unsigned range of MODE.  LOOP is the loop
8684    to which the biv belongs and INCR is its per-iteration increment.  */
8685
8686 static bool
8687 biased_biv_fits_mode_p (const struct loop *loop, struct iv_class *bl,
8688                         HOST_WIDE_INT incr, enum machine_mode mode,
8689                         unsigned HOST_WIDE_INT bias)
8690 {
8691   unsigned HOST_WIDE_INT initial, maximum, span, delta;
8692
8693   /* We need to be able to manipulate MODE-size constants.  */
8694   if (HOST_BITS_PER_WIDE_INT < GET_MODE_BITSIZE (mode))
8695     return false;
8696
8697   /* The number of loop iterations must be constant.  */
8698   if (LOOP_INFO (loop)->n_iterations == 0)
8699     return false;
8700
8701   /* So must the biv's initial value.  */
8702   if (bl->initial_value == 0 || GET_CODE (bl->initial_value) != CONST_INT)
8703     return false;
8704
8705   initial = bias + INTVAL (bl->initial_value);
8706   maximum = GET_MODE_MASK (mode);
8707
8708   /* Make sure that the initial value is within range.  */
8709   if (initial > maximum)
8710     return false;
8711
8712   /* Set up DELTA and SPAN such that the number of iterations * DELTA
8713      (calculated to arbitrary precision) must be <= SPAN.  */
8714   if (incr < 0)
8715     {
8716       delta = -incr;
8717       span = initial;
8718     }
8719   else
8720     {
8721       delta = incr;
8722       /* Handle the special case in which MAXIMUM is the largest
8723          unsigned HOST_WIDE_INT and INITIAL is 0.  */
8724       if (maximum + 1 == initial)
8725         span = LOOP_INFO (loop)->n_iterations * delta;
8726       else
8727         span = maximum + 1 - initial;
8728     }
8729   return (span / LOOP_INFO (loop)->n_iterations >= delta);
8730 }
8731
8732
8733 /* Return true if biv BL will never exceed the bounds of MODE.  LOOP is
8734    the loop to which BL belongs and INCR is its per-iteration increment.
8735    UNSIGNEDP is true if the biv should be treated as unsigned.  */
8736
8737 static bool
8738 biv_fits_mode_p (const struct loop *loop, struct iv_class *bl,
8739                  HOST_WIDE_INT incr, enum machine_mode mode, bool unsignedp)
8740 {
8741   struct loop_info *loop_info;
8742   unsigned HOST_WIDE_INT bias;
8743
8744   /* A biv's value will always be limited to its natural mode.
8745      Larger modes will observe the same wrap-around.  */
8746   if (GET_MODE_SIZE (mode) > GET_MODE_SIZE (GET_MODE (bl->biv->src_reg)))
8747     mode = GET_MODE (bl->biv->src_reg);
8748
8749   loop_info = LOOP_INFO (loop);
8750
8751   bias = (unsignedp ? 0 : (GET_MODE_MASK (mode) >> 1) + 1);
8752   if (biased_biv_fits_mode_p (loop, bl, incr, mode, bias))
8753     return true;
8754
8755   if (mode == GET_MODE (bl->biv->src_reg)
8756       && bl->biv->src_reg == loop_info->iteration_var
8757       && loop_info->comparison_value
8758       && loop_invariant_p (loop, loop_info->comparison_value))
8759     {
8760       /* If the increment is +1, and the exit test is a <, the BIV
8761          cannot overflow.  (For <=, we have the problematic case that
8762          the comparison value might be the maximum value of the range.)  */
8763       if (incr == 1)
8764         {
8765           if (loop_info->comparison_code == LT)
8766             return true;
8767           if (loop_info->comparison_code == LTU && unsignedp)
8768             return true;
8769         }
8770
8771       /* Likewise for increment -1 and exit test >.  */
8772       if (incr == -1)
8773         {
8774           if (loop_info->comparison_code == GT)
8775             return true;
8776           if (loop_info->comparison_code == GTU && unsignedp)
8777             return true;
8778         }
8779     }
8780   return false;
8781 }
8782
8783
8784 /* Given that X is an extension or truncation of BL, return true
8785    if it is unaffected by overflow.  LOOP is the loop to which
8786    BL belongs and INCR is its per-iteration increment.  */
8787
8788 static bool
8789 extension_within_bounds_p (const struct loop *loop, struct iv_class *bl,
8790                            HOST_WIDE_INT incr, rtx x)
8791 {
8792   enum machine_mode mode;
8793   bool signedp, unsignedp;
8794
8795   switch (GET_CODE (x))
8796     {
8797     case SIGN_EXTEND:
8798     case ZERO_EXTEND:
8799       mode = GET_MODE (XEXP (x, 0));
8800       signedp = (GET_CODE (x) == SIGN_EXTEND);
8801       unsignedp = (GET_CODE (x) == ZERO_EXTEND);
8802       break;
8803
8804     case TRUNCATE:
8805       /* We don't know whether this value is being used as signed
8806          or unsigned, so check the conditions for both.  */
8807       mode = GET_MODE (x);
8808       signedp = unsignedp = true;
8809       break;
8810
8811     default:
8812       gcc_unreachable ();
8813     }
8814
8815   return ((!signedp || biv_fits_mode_p (loop, bl, incr, mode, false))
8816           && (!unsignedp || biv_fits_mode_p (loop, bl, incr, mode, true)));
8817 }
8818
8819
8820 /* Check each extension dependent giv in this class to see if its
8821    root biv is safe from wrapping in the interior mode, which would
8822    make the giv illegal.  */
8823
8824 static void
8825 check_ext_dependent_givs (const struct loop *loop, struct iv_class *bl)
8826 {
8827   struct induction *v;
8828   HOST_WIDE_INT incr;
8829
8830   incr = get_monotonic_increment (bl);
8831
8832   /* Invalidate givs that fail the tests.  */
8833   for (v = bl->giv; v; v = v->next_iv)
8834     if (v->ext_dependent)
8835       {
8836         if (incr != 0
8837             && extension_within_bounds_p (loop, bl, incr, v->ext_dependent))
8838           {
8839             if (loop_dump_stream)
8840               fprintf (loop_dump_stream,
8841                        "Verified ext dependent giv at %d of reg %d\n",
8842                        INSN_UID (v->insn), bl->regno);
8843           }
8844         else
8845           {
8846             if (loop_dump_stream)
8847               fprintf (loop_dump_stream,
8848                        "Failed ext dependent giv at %d\n",
8849                        INSN_UID (v->insn));
8850
8851             v->ignore = 1;
8852             bl->all_reduced = 0;
8853           }
8854       }
8855 }
8856
8857 /* Generate a version of VALUE in a mode appropriate for initializing V.  */
8858
8859 static rtx
8860 extend_value_for_giv (struct induction *v, rtx value)
8861 {
8862   rtx ext_dep = v->ext_dependent;
8863
8864   if (! ext_dep)
8865     return value;
8866
8867   /* Recall that check_ext_dependent_givs verified that the known bounds
8868      of a biv did not overflow or wrap with respect to the extension for
8869      the giv.  Therefore, constants need no additional adjustment.  */
8870   if (CONSTANT_P (value) && GET_MODE (value) == VOIDmode)
8871     return value;
8872
8873   /* Otherwise, we must adjust the value to compensate for the
8874      differing modes of the biv and the giv.  */
8875   return gen_rtx_fmt_e (GET_CODE (ext_dep), GET_MODE (ext_dep), value);
8876 }
8877 \f
8878 struct combine_givs_stats
8879 {
8880   int giv_number;
8881   int total_benefit;
8882 };
8883
8884 static int
8885 cmp_combine_givs_stats (const void *xp, const void *yp)
8886 {
8887   const struct combine_givs_stats * const x =
8888     (const struct combine_givs_stats *) xp;
8889   const struct combine_givs_stats * const y =
8890     (const struct combine_givs_stats *) yp;
8891   int d;
8892   d = y->total_benefit - x->total_benefit;
8893   /* Stabilize the sort.  */
8894   if (!d)
8895     d = x->giv_number - y->giv_number;
8896   return d;
8897 }
8898
8899 /* Check all pairs of givs for iv_class BL and see if any can be combined with
8900    any other.  If so, point SAME to the giv combined with and set NEW_REG to
8901    be an expression (in terms of the other giv's DEST_REG) equivalent to the
8902    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
8903
8904 static void
8905 combine_givs (struct loop_regs *regs, struct iv_class *bl)
8906 {
8907   /* Additional benefit to add for being combined multiple times.  */
8908   const int extra_benefit = 3;
8909
8910   struct induction *g1, *g2, **giv_array;
8911   int i, j, k, giv_count;
8912   struct combine_givs_stats *stats;
8913   rtx *can_combine;
8914
8915   /* Count givs, because bl->giv_count is incorrect here.  */
8916   giv_count = 0;
8917   for (g1 = bl->giv; g1; g1 = g1->next_iv)
8918     if (!g1->ignore)
8919       giv_count++;
8920
8921   giv_array = alloca (giv_count * sizeof (struct induction *));
8922   i = 0;
8923   for (g1 = bl->giv; g1; g1 = g1->next_iv)
8924     if (!g1->ignore)
8925       giv_array[i++] = g1;
8926
8927   stats = xcalloc (giv_count, sizeof (*stats));
8928   can_combine = xcalloc (giv_count, giv_count * sizeof (rtx));
8929
8930   for (i = 0; i < giv_count; i++)
8931     {
8932       int this_benefit;
8933       rtx single_use;
8934
8935       g1 = giv_array[i];
8936       stats[i].giv_number = i;
8937
8938       /* If a DEST_REG GIV is used only once, do not allow it to combine
8939          with anything, for in doing so we will gain nothing that cannot
8940          be had by simply letting the GIV with which we would have combined
8941          to be reduced on its own.  The lossage shows up in particular with
8942          DEST_ADDR targets on hosts with reg+reg addressing, though it can
8943          be seen elsewhere as well.  */
8944       if (g1->giv_type == DEST_REG
8945           && (single_use = regs->array[REGNO (g1->dest_reg)].single_usage)
8946           && single_use != const0_rtx)
8947         continue;
8948
8949       this_benefit = g1->benefit;
8950       /* Add an additional weight for zero addends.  */
8951       if (g1->no_const_addval)
8952         this_benefit += 1;
8953
8954       for (j = 0; j < giv_count; j++)
8955         {
8956           rtx this_combine;
8957
8958           g2 = giv_array[j];
8959           if (g1 != g2
8960               && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
8961             {
8962               can_combine[i * giv_count + j] = this_combine;
8963               this_benefit += g2->benefit + extra_benefit;
8964             }
8965         }
8966       stats[i].total_benefit = this_benefit;
8967     }
8968
8969   /* Iterate, combining until we can't.  */
8970 restart:
8971   qsort (stats, giv_count, sizeof (*stats), cmp_combine_givs_stats);
8972
8973   if (loop_dump_stream)
8974     {
8975       fprintf (loop_dump_stream, "Sorted combine statistics:\n");
8976       for (k = 0; k < giv_count; k++)
8977         {
8978           g1 = giv_array[stats[k].giv_number];
8979           if (!g1->combined_with && !g1->same)
8980             fprintf (loop_dump_stream, " {%d, %d}",
8981                      INSN_UID (giv_array[stats[k].giv_number]->insn),
8982                      stats[k].total_benefit);
8983         }
8984       putc ('\n', loop_dump_stream);
8985     }
8986
8987   for (k = 0; k < giv_count; k++)
8988     {
8989       int g1_add_benefit = 0;
8990
8991       i = stats[k].giv_number;
8992       g1 = giv_array[i];
8993
8994       /* If it has already been combined, skip.  */
8995       if (g1->combined_with || g1->same)
8996         continue;
8997
8998       for (j = 0; j < giv_count; j++)
8999         {
9000           g2 = giv_array[j];
9001           if (g1 != g2 && can_combine[i * giv_count + j]
9002               /* If it has already been combined, skip.  */
9003               && ! g2->same && ! g2->combined_with)
9004             {
9005               int l;
9006
9007               g2->new_reg = can_combine[i * giv_count + j];
9008               g2->same = g1;
9009               /* For destination, we now may replace by mem expression instead
9010                  of register.  This changes the costs considerably, so add the
9011                  compensation.  */
9012               if (g2->giv_type == DEST_ADDR)
9013                 g2->benefit = (g2->benefit + reg_address_cost
9014                                - address_cost (g2->new_reg,
9015                                GET_MODE (g2->mem)));
9016               g1->combined_with++;
9017               g1->lifetime += g2->lifetime;
9018
9019               g1_add_benefit += g2->benefit;
9020
9021               /* ??? The new final_[bg]iv_value code does a much better job
9022                  of finding replaceable giv's, and hence this code may no
9023                  longer be necessary.  */
9024               if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
9025                 g1_add_benefit -= copy_cost;
9026
9027               /* To help optimize the next set of combinations, remove
9028                  this giv from the benefits of other potential mates.  */
9029               for (l = 0; l < giv_count; ++l)
9030                 {
9031                   int m = stats[l].giv_number;
9032                   if (can_combine[m * giv_count + j])
9033                     stats[l].total_benefit -= g2->benefit + extra_benefit;
9034                 }
9035
9036               if (loop_dump_stream)
9037                 fprintf (loop_dump_stream,
9038                          "giv at %d combined with giv at %d; new benefit %d + %d, lifetime %d\n",
9039                          INSN_UID (g2->insn), INSN_UID (g1->insn),
9040                          g1->benefit, g1_add_benefit, g1->lifetime);
9041             }
9042         }
9043
9044       /* To help optimize the next set of combinations, remove
9045          this giv from the benefits of other potential mates.  */
9046       if (g1->combined_with)
9047         {
9048           for (j = 0; j < giv_count; ++j)
9049             {
9050               int m = stats[j].giv_number;
9051               if (can_combine[m * giv_count + i])
9052                 stats[j].total_benefit -= g1->benefit + extra_benefit;
9053             }
9054
9055           g1->benefit += g1_add_benefit;
9056
9057           /* We've finished with this giv, and everything it touched.
9058              Restart the combination so that proper weights for the
9059              rest of the givs are properly taken into account.  */
9060           /* ??? Ideally we would compact the arrays at this point, so
9061              as to not cover old ground.  But sanely compacting
9062              can_combine is tricky.  */
9063           goto restart;
9064         }
9065     }
9066
9067   /* Clean up.  */
9068   free (stats);
9069   free (can_combine);
9070 }
9071 \f
9072 /* Generate sequence for REG = B * M + A.  B is the initial value of
9073    the basic induction variable, M a multiplicative constant, A an
9074    additive constant and REG the destination register.  */
9075
9076 static rtx
9077 gen_add_mult (rtx b,  rtx m, rtx a, rtx reg)
9078 {
9079   rtx seq;
9080   rtx result;
9081
9082   start_sequence ();
9083   /* Use unsigned arithmetic.  */
9084   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
9085   if (reg != result)
9086     emit_move_insn (reg, result);
9087   seq = get_insns ();
9088   end_sequence ();
9089
9090   return seq;
9091 }
9092
9093
9094 /* Update registers created in insn sequence SEQ.  */
9095
9096 static void
9097 loop_regs_update (const struct loop *loop ATTRIBUTE_UNUSED, rtx seq)
9098 {
9099   rtx insn;
9100
9101   /* Update register info for alias analysis.  */
9102
9103   insn = seq;
9104   while (insn != NULL_RTX)
9105     {
9106       rtx set = single_set (insn);
9107
9108       if (set && REG_P (SET_DEST (set)))
9109         record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
9110
9111       insn = NEXT_INSN (insn);
9112     }
9113 }
9114
9115
9116 /* EMIT code before BEFORE_BB/BEFORE_INSN to set REG = B * M + A.  B
9117    is the initial value of the basic induction variable, M a
9118    multiplicative constant, A an additive constant and REG the
9119    destination register.  */
9120
9121 static void
9122 loop_iv_add_mult_emit_before (const struct loop *loop, rtx b, rtx m, rtx a,
9123                               rtx reg, basic_block before_bb, rtx before_insn)
9124 {
9125   rtx seq;
9126
9127   if (! before_insn)
9128     {
9129       loop_iv_add_mult_hoist (loop, b, m, a, reg);
9130       return;
9131     }
9132
9133   /* Use copy_rtx to prevent unexpected sharing of these rtx.  */
9134   seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
9135
9136   /* Increase the lifetime of any invariants moved further in code.  */
9137   update_reg_last_use (a, before_insn);
9138   update_reg_last_use (b, before_insn);
9139   update_reg_last_use (m, before_insn);
9140
9141   /* It is possible that the expansion created lots of new registers.
9142      Iterate over the sequence we just created and record them all.  We
9143      must do this before inserting the sequence.  */
9144   loop_regs_update (loop, seq);
9145
9146   loop_insn_emit_before (loop, before_bb, before_insn, seq);
9147 }
9148
9149
9150 /* Emit insns in loop pre-header to set REG = B * M + A.  B is the
9151    initial value of the basic induction variable, M a multiplicative
9152    constant, A an additive constant and REG the destination
9153    register.  */
9154
9155 static void
9156 loop_iv_add_mult_sink (const struct loop *loop, rtx b, rtx m, rtx a, rtx reg)
9157 {
9158   rtx seq;
9159
9160   /* Use copy_rtx to prevent unexpected sharing of these rtx.  */
9161   seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
9162
9163   /* Increase the lifetime of any invariants moved further in code.
9164      ???? Is this really necessary?  */
9165   update_reg_last_use (a, loop->sink);
9166   update_reg_last_use (b, loop->sink);
9167   update_reg_last_use (m, loop->sink);
9168
9169   /* It is possible that the expansion created lots of new registers.
9170      Iterate over the sequence we just created and record them all.  We
9171      must do this before inserting the sequence.  */
9172   loop_regs_update (loop, seq);
9173
9174   loop_insn_sink (loop, seq);
9175 }
9176
9177
9178 /* Emit insns after loop to set REG = B * M + A.  B is the initial
9179    value of the basic induction variable, M a multiplicative constant,
9180    A an additive constant and REG the destination register.  */
9181
9182 static void
9183 loop_iv_add_mult_hoist (const struct loop *loop, rtx b, rtx m, rtx a, rtx reg)
9184 {
9185   rtx seq;
9186
9187   /* Use copy_rtx to prevent unexpected sharing of these rtx.  */
9188   seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
9189
9190   /* It is possible that the expansion created lots of new registers.
9191      Iterate over the sequence we just created and record them all.  We
9192      must do this before inserting the sequence.  */
9193   loop_regs_update (loop, seq);
9194
9195   loop_insn_hoist (loop, seq);
9196 }
9197
9198
9199
9200 /* Similar to gen_add_mult, but compute cost rather than generating
9201    sequence.  */
9202
9203 static int
9204 iv_add_mult_cost (rtx b, rtx m, rtx a, rtx reg)
9205 {
9206   int cost = 0;
9207   rtx last, result;
9208
9209   start_sequence ();
9210   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
9211   if (reg != result)
9212     emit_move_insn (reg, result);
9213   last = get_last_insn ();
9214   while (last)
9215     {
9216       rtx t = single_set (last);
9217       if (t)
9218         cost += rtx_cost (SET_SRC (t), SET);
9219       last = PREV_INSN (last);
9220     }
9221   end_sequence ();
9222   return cost;
9223 }
9224 \f
9225 /* Test whether A * B can be computed without
9226    an actual multiply insn.  Value is 1 if so.
9227
9228   ??? This function stinks because it generates a ton of wasted RTL
9229   ??? and as a result fragments GC memory to no end.  There are other
9230   ??? places in the compiler which are invoked a lot and do the same
9231   ??? thing, generate wasted RTL just to see if something is possible.  */
9232
9233 static int
9234 product_cheap_p (rtx a, rtx b)
9235 {
9236   rtx tmp;
9237   int win, n_insns;
9238
9239   /* If only one is constant, make it B.  */
9240   if (GET_CODE (a) == CONST_INT)
9241     tmp = a, a = b, b = tmp;
9242
9243   /* If first constant, both constant, so don't need multiply.  */
9244   if (GET_CODE (a) == CONST_INT)
9245     return 1;
9246
9247   /* If second not constant, neither is constant, so would need multiply.  */
9248   if (GET_CODE (b) != CONST_INT)
9249     return 0;
9250
9251   /* One operand is constant, so might not need multiply insn.  Generate the
9252      code for the multiply and see if a call or multiply, or long sequence
9253      of insns is generated.  */
9254
9255   start_sequence ();
9256   expand_mult (GET_MODE (a), a, b, NULL_RTX, 1);
9257   tmp = get_insns ();
9258   end_sequence ();
9259
9260   win = 1;
9261   if (tmp == NULL_RTX)
9262     ;
9263   else if (INSN_P (tmp))
9264     {
9265       n_insns = 0;
9266       while (tmp != NULL_RTX)
9267         {
9268           rtx next = NEXT_INSN (tmp);
9269
9270           if (++n_insns > 3
9271               || !NONJUMP_INSN_P (tmp)
9272               || (GET_CODE (PATTERN (tmp)) == SET
9273                   && GET_CODE (SET_SRC (PATTERN (tmp))) == MULT)
9274               || (GET_CODE (PATTERN (tmp)) == PARALLEL
9275                   && GET_CODE (XVECEXP (PATTERN (tmp), 0, 0)) == SET
9276                   && GET_CODE (SET_SRC (XVECEXP (PATTERN (tmp), 0, 0))) == MULT))
9277             {
9278               win = 0;
9279               break;
9280             }
9281
9282           tmp = next;
9283         }
9284     }
9285   else if (GET_CODE (tmp) == SET
9286            && GET_CODE (SET_SRC (tmp)) == MULT)
9287     win = 0;
9288   else if (GET_CODE (tmp) == PARALLEL
9289            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
9290            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
9291     win = 0;
9292
9293   return win;
9294 }
9295 \f
9296 /* Check to see if loop can be terminated by a "decrement and branch until
9297    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
9298    Also try reversing an increment loop to a decrement loop
9299    to see if the optimization can be performed.
9300    Value is nonzero if optimization was performed.  */
9301
9302 /* This is useful even if the architecture doesn't have such an insn,
9303    because it might change a loops which increments from 0 to n to a loop
9304    which decrements from n to 0.  A loop that decrements to zero is usually
9305    faster than one that increments from zero.  */
9306
9307 /* ??? This could be rewritten to use some of the loop unrolling procedures,
9308    such as approx_final_value, biv_total_increment, loop_iterations, and
9309    final_[bg]iv_value.  */
9310
9311 static int
9312 check_dbra_loop (struct loop *loop, int insn_count)
9313 {
9314   struct loop_info *loop_info = LOOP_INFO (loop);
9315   struct loop_regs *regs = LOOP_REGS (loop);
9316   struct loop_ivs *ivs = LOOP_IVS (loop);
9317   struct iv_class *bl;
9318   rtx reg;
9319   enum machine_mode mode;
9320   rtx jump_label;
9321   rtx final_value;
9322   rtx start_value;
9323   rtx new_add_val;
9324   rtx comparison;
9325   rtx before_comparison;
9326   rtx p;
9327   rtx jump;
9328   rtx first_compare;
9329   int compare_and_branch;
9330   rtx loop_start = loop->start;
9331   rtx loop_end = loop->end;
9332
9333   /* If last insn is a conditional branch, and the insn before tests a
9334      register value, try to optimize it.  Otherwise, we can't do anything.  */
9335
9336   jump = PREV_INSN (loop_end);
9337   comparison = get_condition_for_loop (loop, jump);
9338   if (comparison == 0)
9339     return 0;
9340   if (!onlyjump_p (jump))
9341     return 0;
9342
9343   /* Try to compute whether the compare/branch at the loop end is one or
9344      two instructions.  */
9345   get_condition (jump, &first_compare, false, true);
9346   if (first_compare == jump)
9347     compare_and_branch = 1;
9348   else if (first_compare == prev_nonnote_insn (jump))
9349     compare_and_branch = 2;
9350   else
9351     return 0;
9352
9353   {
9354     /* If more than one condition is present to control the loop, then
9355        do not proceed, as this function does not know how to rewrite
9356        loop tests with more than one condition.
9357
9358        Look backwards from the first insn in the last comparison
9359        sequence and see if we've got another comparison sequence.  */
9360
9361     rtx jump1;
9362     if ((jump1 = prev_nonnote_insn (first_compare))
9363         && JUMP_P (jump1))
9364         return 0;
9365   }
9366
9367   /* Check all of the bivs to see if the compare uses one of them.
9368      Skip biv's set more than once because we can't guarantee that
9369      it will be zero on the last iteration.  Also skip if the biv is
9370      used between its update and the test insn.  */
9371
9372   for (bl = ivs->list; bl; bl = bl->next)
9373     {
9374       if (bl->biv_count == 1
9375           && ! bl->biv->maybe_multiple
9376           && bl->biv->dest_reg == XEXP (comparison, 0)
9377           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
9378                                    first_compare))
9379         break;
9380     }
9381
9382   /* Try swapping the comparison to identify a suitable biv.  */
9383   if (!bl)
9384     for (bl = ivs->list; bl; bl = bl->next)
9385       if (bl->biv_count == 1
9386           && ! bl->biv->maybe_multiple
9387           && bl->biv->dest_reg == XEXP (comparison, 1)
9388           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
9389                                    first_compare))
9390         {
9391           comparison = gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)),
9392                                        VOIDmode,
9393                                        XEXP (comparison, 1),
9394                                        XEXP (comparison, 0));
9395           break;
9396         }
9397
9398   if (! bl)
9399     return 0;
9400
9401   /* Look for the case where the basic induction variable is always
9402      nonnegative, and equals zero on the last iteration.
9403      In this case, add a reg_note REG_NONNEG, which allows the
9404      m68k DBRA instruction to be used.  */
9405
9406   if (((GET_CODE (comparison) == GT && XEXP (comparison, 1) == constm1_rtx)
9407        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
9408       && GET_CODE (bl->biv->add_val) == CONST_INT
9409       && INTVAL (bl->biv->add_val) < 0)
9410     {
9411       /* Initial value must be greater than 0,
9412          init_val % -dec_value == 0 to ensure that it equals zero on
9413          the last iteration */
9414
9415       if (GET_CODE (bl->initial_value) == CONST_INT
9416           && INTVAL (bl->initial_value) > 0
9417           && (INTVAL (bl->initial_value)
9418               % (-INTVAL (bl->biv->add_val))) == 0)
9419         {
9420           /* Register always nonnegative, add REG_NOTE to branch.  */
9421           if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
9422             REG_NOTES (jump)
9423               = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
9424                                    REG_NOTES (jump));
9425           bl->nonneg = 1;
9426
9427           return 1;
9428         }
9429
9430       /* If the decrement is 1 and the value was tested as >= 0 before
9431          the loop, then we can safely optimize.  */
9432       for (p = loop_start; p; p = PREV_INSN (p))
9433         {
9434           if (LABEL_P (p))
9435             break;
9436           if (!JUMP_P (p))
9437             continue;
9438
9439           before_comparison = get_condition_for_loop (loop, p);
9440           if (before_comparison
9441               && XEXP (before_comparison, 0) == bl->biv->dest_reg
9442               && (GET_CODE (before_comparison) == LT
9443                   || GET_CODE (before_comparison) == LTU)
9444               && XEXP (before_comparison, 1) == const0_rtx
9445               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
9446               && INTVAL (bl->biv->add_val) == -1)
9447             {
9448               if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
9449                 REG_NOTES (jump)
9450                   = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
9451                                        REG_NOTES (jump));
9452               bl->nonneg = 1;
9453
9454               return 1;
9455             }
9456         }
9457     }
9458   else if (GET_CODE (bl->biv->add_val) == CONST_INT
9459            && INTVAL (bl->biv->add_val) > 0)
9460     {
9461       /* Try to change inc to dec, so can apply above optimization.  */
9462       /* Can do this if:
9463          all registers modified are induction variables or invariant,
9464          all memory references have non-overlapping addresses
9465          (obviously true if only one write)
9466          allow 2 insns for the compare/jump at the end of the loop.  */
9467       /* Also, we must avoid any instructions which use both the reversed
9468          biv and another biv.  Such instructions will fail if the loop is
9469          reversed.  We meet this condition by requiring that either
9470          no_use_except_counting is true, or else that there is only
9471          one biv.  */
9472       int num_nonfixed_reads = 0;
9473       /* 1 if the iteration var is used only to count iterations.  */
9474       int no_use_except_counting = 0;
9475       /* 1 if the loop has no memory store, or it has a single memory store
9476          which is reversible.  */
9477       int reversible_mem_store = 1;
9478
9479       if (bl->giv_count == 0
9480           && !loop->exit_count
9481           && !loop_info->has_multiple_exit_targets)
9482         {
9483           rtx bivreg = regno_reg_rtx[bl->regno];
9484           struct iv_class *blt;
9485
9486           /* If there are no givs for this biv, and the only exit is the
9487              fall through at the end of the loop, then
9488              see if perhaps there are no uses except to count.  */
9489           no_use_except_counting = 1;
9490           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
9491             if (INSN_P (p))
9492               {
9493                 rtx set = single_set (p);
9494
9495                 if (set && REG_P (SET_DEST (set))
9496                     && REGNO (SET_DEST (set)) == bl->regno)
9497                   /* An insn that sets the biv is okay.  */
9498                   ;
9499                 else if (!reg_mentioned_p (bivreg, PATTERN (p)))
9500                   /* An insn that doesn't mention the biv is okay.  */
9501                   ;
9502                 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
9503                          || p == prev_nonnote_insn (loop_end))
9504                   {
9505                     /* If either of these insns uses the biv and sets a pseudo
9506                        that has more than one usage, then the biv has uses
9507                        other than counting since it's used to derive a value
9508                        that is used more than one time.  */
9509                     note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
9510                                  regs);
9511                     if (regs->multiple_uses)
9512                       {
9513                         no_use_except_counting = 0;
9514                         break;
9515                       }
9516                   }
9517                 else
9518                   {
9519                     no_use_except_counting = 0;
9520                     break;
9521                   }
9522               }
9523
9524           /* A biv has uses besides counting if it is used to set
9525              another biv.  */
9526           for (blt = ivs->list; blt; blt = blt->next)
9527             if (blt->init_set
9528                 && reg_mentioned_p (bivreg, SET_SRC (blt->init_set)))
9529               {
9530                 no_use_except_counting = 0;
9531                 break;
9532               }
9533         }
9534
9535       if (no_use_except_counting)
9536         /* No need to worry about MEMs.  */
9537         ;
9538       else if (loop_info->num_mem_sets <= 1)
9539         {
9540           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
9541             if (INSN_P (p))
9542               num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
9543
9544           /* If the loop has a single store, and the destination address is
9545              invariant, then we can't reverse the loop, because this address
9546              might then have the wrong value at loop exit.
9547              This would work if the source was invariant also, however, in that
9548              case, the insn should have been moved out of the loop.  */
9549
9550           if (loop_info->num_mem_sets == 1)
9551             {
9552               struct induction *v;
9553
9554               /* If we could prove that each of the memory locations
9555                  written to was different, then we could reverse the
9556                  store -- but we don't presently have any way of
9557                  knowing that.  */
9558               reversible_mem_store = 0;
9559
9560               /* If the store depends on a register that is set after the
9561                  store, it depends on the initial value, and is thus not
9562                  reversible.  */
9563               for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
9564                 {
9565                   if (v->giv_type == DEST_REG
9566                       && reg_mentioned_p (v->dest_reg,
9567                                           PATTERN (loop_info->first_loop_store_insn))
9568                       && loop_insn_first_p (loop_info->first_loop_store_insn,
9569                                             v->insn))
9570                     reversible_mem_store = 0;
9571                 }
9572             }
9573         }
9574       else
9575         return 0;
9576
9577       /* This code only acts for innermost loops.  Also it simplifies
9578          the memory address check by only reversing loops with
9579          zero or one memory access.
9580          Two memory accesses could involve parts of the same array,
9581          and that can't be reversed.
9582          If the biv is used only for counting, than we don't need to worry
9583          about all these things.  */
9584
9585       if ((num_nonfixed_reads <= 1
9586            && ! loop_info->has_nonconst_call
9587            && ! loop_info->has_prefetch
9588            && ! loop_info->has_volatile
9589            && reversible_mem_store
9590            && (bl->giv_count + bl->biv_count + loop_info->num_mem_sets
9591                + num_unmoved_movables (loop) + compare_and_branch == insn_count)
9592            && (bl == ivs->list && bl->next == 0))
9593           || (no_use_except_counting && ! loop_info->has_prefetch))
9594         {
9595           rtx tem;
9596
9597           /* Loop can be reversed.  */
9598           if (loop_dump_stream)
9599             fprintf (loop_dump_stream, "Can reverse loop\n");
9600
9601           /* Now check other conditions:
9602
9603              The increment must be a constant, as must the initial value,
9604              and the comparison code must be LT.
9605
9606              This test can probably be improved since +/- 1 in the constant
9607              can be obtained by changing LT to LE and vice versa; this is
9608              confusing.  */
9609
9610           if (comparison
9611               /* for constants, LE gets turned into LT */
9612               && (GET_CODE (comparison) == LT
9613                   || (GET_CODE (comparison) == LE
9614                       && no_use_except_counting) 
9615                   || GET_CODE (comparison) == LTU))
9616             {
9617               HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
9618               rtx initial_value, comparison_value;
9619               int nonneg = 0;
9620               enum rtx_code cmp_code;
9621               int comparison_const_width;
9622               unsigned HOST_WIDE_INT comparison_sign_mask;
9623               bool keep_first_compare;
9624
9625               add_val = INTVAL (bl->biv->add_val);
9626               comparison_value = XEXP (comparison, 1);
9627               if (GET_MODE (comparison_value) == VOIDmode)
9628                 comparison_const_width
9629                   = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
9630               else
9631                 comparison_const_width
9632                   = GET_MODE_BITSIZE (GET_MODE (comparison_value));
9633               if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
9634                 comparison_const_width = HOST_BITS_PER_WIDE_INT;
9635               comparison_sign_mask
9636                 = (unsigned HOST_WIDE_INT) 1 << (comparison_const_width - 1);
9637
9638               /* If the comparison value is not a loop invariant, then we
9639                  can not reverse this loop.
9640
9641                  ??? If the insns which initialize the comparison value as
9642                  a whole compute an invariant result, then we could move
9643                  them out of the loop and proceed with loop reversal.  */
9644               if (! loop_invariant_p (loop, comparison_value))
9645                 return 0;
9646
9647               if (GET_CODE (comparison_value) == CONST_INT)
9648                 comparison_val = INTVAL (comparison_value);
9649               initial_value = bl->initial_value;
9650
9651               /* Normalize the initial value if it is an integer and
9652                  has no other use except as a counter.  This will allow
9653                  a few more loops to be reversed.  */
9654               if (no_use_except_counting
9655                   && GET_CODE (comparison_value) == CONST_INT
9656                   && GET_CODE (initial_value) == CONST_INT)
9657                 {
9658                   comparison_val = comparison_val - INTVAL (bl->initial_value);
9659                   /* The code below requires comparison_val to be a multiple
9660                      of add_val in order to do the loop reversal, so
9661                      round up comparison_val to a multiple of add_val.
9662                      Since comparison_value is constant, we know that the
9663                      current comparison code is LT.  */
9664                   comparison_val = comparison_val + add_val - 1;
9665                   comparison_val
9666                     -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
9667                   /* We postpone overflow checks for COMPARISON_VAL here;
9668                      even if there is an overflow, we might still be able to
9669                      reverse the loop, if converting the loop exit test to
9670                      NE is possible.  */
9671                   initial_value = const0_rtx;
9672                 }
9673
9674               /* First check if we can do a vanilla loop reversal.  */
9675               if (initial_value == const0_rtx
9676                   && GET_CODE (comparison_value) == CONST_INT
9677                      /* Now do postponed overflow checks on COMPARISON_VAL.  */
9678                   && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
9679                         & comparison_sign_mask))
9680                 {
9681                   /* Register will always be nonnegative, with value
9682                      0 on last iteration */
9683                   add_adjust = add_val;
9684                   nonneg = 1;
9685                   cmp_code = GE;
9686                 }
9687               else
9688                 return 0;
9689
9690               if (GET_CODE (comparison) == LE)
9691                 add_adjust -= add_val;
9692
9693               /* If the initial value is not zero, or if the comparison
9694                  value is not an exact multiple of the increment, then we
9695                  can not reverse this loop.  */
9696               if (initial_value == const0_rtx
9697                   && GET_CODE (comparison_value) == CONST_INT)
9698                 {
9699                   if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
9700                     return 0;
9701                 }
9702               else
9703                 {
9704                   if (! no_use_except_counting || add_val != 1)
9705                     return 0;
9706                 }
9707
9708               final_value = comparison_value;
9709
9710               /* Reset these in case we normalized the initial value
9711                  and comparison value above.  */
9712               if (GET_CODE (comparison_value) == CONST_INT
9713                   && GET_CODE (initial_value) == CONST_INT)
9714                 {
9715                   comparison_value = GEN_INT (comparison_val);
9716                   final_value
9717                     = GEN_INT (comparison_val + INTVAL (bl->initial_value));
9718                 }
9719               bl->initial_value = initial_value;
9720
9721               /* Save some info needed to produce the new insns.  */
9722               reg = bl->biv->dest_reg;
9723               mode = GET_MODE (reg);
9724               jump_label = condjump_label (PREV_INSN (loop_end));
9725               new_add_val = GEN_INT (-INTVAL (bl->biv->add_val));
9726
9727               /* Set start_value; if this is not a CONST_INT, we need
9728                  to generate a SUB.
9729                  Initialize biv to start_value before loop start.
9730                  The old initializing insn will be deleted as a
9731                  dead store by flow.c.  */
9732               if (initial_value == const0_rtx
9733                   && GET_CODE (comparison_value) == CONST_INT)
9734                 {
9735                   start_value
9736                     = gen_int_mode (comparison_val - add_adjust, mode);
9737                   loop_insn_hoist (loop, gen_move_insn (reg, start_value));
9738                 }
9739               else if (GET_CODE (initial_value) == CONST_INT)
9740                 {
9741                   rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
9742                   rtx add_insn = gen_add3_insn (reg, comparison_value, offset);
9743
9744                   if (add_insn == 0)
9745                     return 0;
9746
9747                   start_value
9748                     = gen_rtx_PLUS (mode, comparison_value, offset);
9749                   loop_insn_hoist (loop, add_insn);
9750                   if (GET_CODE (comparison) == LE)
9751                     final_value = gen_rtx_PLUS (mode, comparison_value,
9752                                                 GEN_INT (add_val));
9753                 }
9754               else if (! add_adjust)
9755                 {
9756                   rtx sub_insn = gen_sub3_insn (reg, comparison_value,
9757                                                 initial_value);
9758
9759                   if (sub_insn == 0)
9760                     return 0;
9761                   start_value
9762                     = gen_rtx_MINUS (mode, comparison_value, initial_value);
9763                   loop_insn_hoist (loop, sub_insn);
9764                 }
9765               else
9766                 /* We could handle the other cases too, but it'll be
9767                    better to have a testcase first.  */
9768                 return 0;
9769
9770               /* We may not have a single insn which can increment a reg, so
9771                  create a sequence to hold all the insns from expand_inc.  */
9772               start_sequence ();
9773               expand_inc (reg, new_add_val);
9774               tem = get_insns ();
9775               end_sequence ();
9776
9777               p = loop_insn_emit_before (loop, 0, bl->biv->insn, tem);
9778               delete_insn (bl->biv->insn);
9779
9780               /* Update biv info to reflect its new status.  */
9781               bl->biv->insn = p;
9782               bl->initial_value = start_value;
9783               bl->biv->add_val = new_add_val;
9784
9785               /* Update loop info.  */
9786               loop_info->initial_value = reg;
9787               loop_info->initial_equiv_value = reg;
9788               loop_info->final_value = const0_rtx;
9789               loop_info->final_equiv_value = const0_rtx;
9790               loop_info->comparison_value = const0_rtx;
9791               loop_info->comparison_code = cmp_code;
9792               loop_info->increment = new_add_val;
9793
9794               /* Inc LABEL_NUSES so that delete_insn will
9795                  not delete the label.  */
9796               LABEL_NUSES (XEXP (jump_label, 0))++;
9797
9798               /* If we have a separate comparison insn that does more
9799                  than just set cc0, the result of the comparison might
9800                  be used outside the loop.  */
9801               keep_first_compare = (compare_and_branch == 2
9802 #ifdef HAVE_CC0
9803                                     && sets_cc0_p (first_compare) <= 0
9804 #endif
9805                                     );
9806
9807               /* Emit an insn after the end of the loop to set the biv's
9808                  proper exit value if it is used anywhere outside the loop.  */
9809               if (keep_first_compare
9810                   || (REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
9811                   || ! bl->init_insn
9812                   || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
9813                 loop_insn_sink (loop, gen_load_of_final_value (reg, final_value));
9814
9815               if (keep_first_compare)
9816                 loop_insn_sink (loop, PATTERN (first_compare));
9817
9818               /* Delete compare/branch at end of loop.  */
9819               delete_related_insns (PREV_INSN (loop_end));
9820               if (compare_and_branch == 2)
9821                 delete_related_insns (first_compare);
9822
9823               /* Add new compare/branch insn at end of loop.  */
9824               start_sequence ();
9825               emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
9826                                        mode, 0,
9827                                        XEXP (jump_label, 0));
9828               tem = get_insns ();
9829               end_sequence ();
9830               emit_jump_insn_before (tem, loop_end);
9831
9832               for (tem = PREV_INSN (loop_end);
9833                    tem && !JUMP_P (tem);
9834                    tem = PREV_INSN (tem))
9835                 ;
9836
9837               if (tem)
9838                 JUMP_LABEL (tem) = XEXP (jump_label, 0);
9839
9840               if (nonneg)
9841                 {
9842                   if (tem)
9843                     {
9844                       /* Increment of LABEL_NUSES done above.  */
9845                       /* Register is now always nonnegative,
9846                          so add REG_NONNEG note to the branch.  */
9847                       REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, reg,
9848                                                            REG_NOTES (tem));
9849                     }
9850                   bl->nonneg = 1;
9851                 }
9852
9853               /* No insn may reference both the reversed and another biv or it
9854                  will fail (see comment near the top of the loop reversal
9855                  code).
9856                  Earlier on, we have verified that the biv has no use except
9857                  counting, or it is the only biv in this function.
9858                  However, the code that computes no_use_except_counting does
9859                  not verify reg notes.  It's possible to have an insn that
9860                  references another biv, and has a REG_EQUAL note with an
9861                  expression based on the reversed biv.  To avoid this case,
9862                  remove all REG_EQUAL notes based on the reversed biv
9863                  here.  */
9864               for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
9865                 if (INSN_P (p))
9866                   {
9867                     rtx *pnote;
9868                     rtx set = single_set (p);
9869                     /* If this is a set of a GIV based on the reversed biv, any
9870                        REG_EQUAL notes should still be correct.  */
9871                     if (! set
9872                         || !REG_P (SET_DEST (set))
9873                         || (size_t) REGNO (SET_DEST (set)) >= ivs->n_regs
9874                         || REG_IV_TYPE (ivs, REGNO (SET_DEST (set))) != GENERAL_INDUCT
9875                         || REG_IV_INFO (ivs, REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
9876                       for (pnote = &REG_NOTES (p); *pnote;)
9877                         {
9878                           if (REG_NOTE_KIND (*pnote) == REG_EQUAL
9879                               && reg_mentioned_p (regno_reg_rtx[bl->regno],
9880                                                   XEXP (*pnote, 0)))
9881                             *pnote = XEXP (*pnote, 1);
9882                           else
9883                             pnote = &XEXP (*pnote, 1);
9884                         }
9885                   }
9886
9887               /* Mark that this biv has been reversed.  Each giv which depends
9888                  on this biv, and which is also live past the end of the loop
9889                  will have to be fixed up.  */
9890
9891               bl->reversed = 1;
9892
9893               if (loop_dump_stream)
9894                 {
9895                   fprintf (loop_dump_stream, "Reversed loop");
9896                   if (bl->nonneg)
9897                     fprintf (loop_dump_stream, " and added reg_nonneg\n");
9898                   else
9899                     fprintf (loop_dump_stream, "\n");
9900                 }
9901
9902               return 1;
9903             }
9904         }
9905     }
9906
9907   return 0;
9908 }
9909 \f
9910 /* Verify whether the biv BL appears to be eliminable,
9911    based on the insns in the loop that refer to it.
9912
9913    If ELIMINATE_P is nonzero, actually do the elimination.
9914
9915    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
9916    determine whether invariant insns should be placed inside or at the
9917    start of the loop.  */
9918
9919 static int
9920 maybe_eliminate_biv (const struct loop *loop, struct iv_class *bl,
9921                      int eliminate_p, int threshold, int insn_count)
9922 {
9923   struct loop_ivs *ivs = LOOP_IVS (loop);
9924   rtx reg = bl->biv->dest_reg;
9925   rtx p;
9926
9927   /* Scan all insns in the loop, stopping if we find one that uses the
9928      biv in a way that we cannot eliminate.  */
9929
9930   for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
9931     {
9932       enum rtx_code code = GET_CODE (p);
9933       basic_block where_bb = 0;
9934       rtx where_insn = threshold >= insn_count ? 0 : p;
9935       rtx note;
9936
9937       /* If this is a libcall that sets a giv, skip ahead to its end.  */
9938       if (INSN_P (p))
9939         {
9940           note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
9941
9942           if (note)
9943             {
9944               rtx last = XEXP (note, 0);
9945               rtx set = single_set (last);
9946
9947               if (set && REG_P (SET_DEST (set)))
9948                 {
9949                   unsigned int regno = REGNO (SET_DEST (set));
9950
9951                   if (regno < ivs->n_regs
9952                       && REG_IV_TYPE (ivs, regno) == GENERAL_INDUCT
9953                       && REG_IV_INFO (ivs, regno)->src_reg == bl->biv->src_reg)
9954                     p = last;
9955                 }
9956             }
9957         }
9958
9959       /* Closely examine the insn if the biv is mentioned.  */
9960       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
9961           && reg_mentioned_p (reg, PATTERN (p))
9962           && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
9963                                       eliminate_p, where_bb, where_insn))
9964         {
9965           if (loop_dump_stream)
9966             fprintf (loop_dump_stream,
9967                      "Cannot eliminate biv %d: biv used in insn %d.\n",
9968                      bl->regno, INSN_UID (p));
9969           break;
9970         }
9971
9972       /* If we are eliminating, kill REG_EQUAL notes mentioning the biv.  */
9973       if (eliminate_p
9974           && (note = find_reg_note (p, REG_EQUAL, NULL_RTX)) != NULL_RTX
9975           && reg_mentioned_p (reg, XEXP (note, 0)))
9976         remove_note (p, note);
9977     }
9978
9979   if (p == loop->end)
9980     {
9981       if (loop_dump_stream)
9982         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
9983                  bl->regno, eliminate_p ? "was" : "can be");
9984       return 1;
9985     }
9986
9987   return 0;
9988 }
9989 \f
9990 /* INSN and REFERENCE are instructions in the same insn chain.
9991    Return nonzero if INSN is first.  */
9992
9993 static int
9994 loop_insn_first_p (rtx insn, rtx reference)
9995 {
9996   rtx p, q;
9997
9998   for (p = insn, q = reference;;)
9999     {
10000       /* Start with test for not first so that INSN == REFERENCE yields not
10001          first.  */
10002       if (q == insn || ! p)
10003         return 0;
10004       if (p == reference || ! q)
10005         return 1;
10006
10007       /* Either of P or Q might be a NOTE.  Notes have the same LUID as the
10008          previous insn, hence the <= comparison below does not work if
10009          P is a note.  */
10010       if (INSN_UID (p) < max_uid_for_loop
10011           && INSN_UID (q) < max_uid_for_loop
10012           && !NOTE_P (p))
10013         return INSN_LUID (p) <= INSN_LUID (q);
10014
10015       if (INSN_UID (p) >= max_uid_for_loop
10016           || NOTE_P (p))
10017         p = NEXT_INSN (p);
10018       if (INSN_UID (q) >= max_uid_for_loop)
10019         q = NEXT_INSN (q);
10020     }
10021 }
10022
10023 /* We are trying to eliminate BIV in INSN using GIV.  Return nonzero if
10024    the offset that we have to take into account due to auto-increment /
10025    div derivation is zero.  */
10026 static int
10027 biv_elimination_giv_has_0_offset (struct induction *biv,
10028                                   struct induction *giv, rtx insn)
10029 {
10030   /* If the giv V had the auto-inc address optimization applied
10031      to it, and INSN occurs between the giv insn and the biv
10032      insn, then we'd have to adjust the value used here.
10033      This is rare, so we don't bother to make this possible.  */
10034   if (giv->auto_inc_opt
10035       && ((loop_insn_first_p (giv->insn, insn)
10036            && loop_insn_first_p (insn, biv->insn))
10037           || (loop_insn_first_p (biv->insn, insn)
10038               && loop_insn_first_p (insn, giv->insn))))
10039     return 0;
10040
10041   return 1;
10042 }
10043
10044 /* If BL appears in X (part of the pattern of INSN), see if we can
10045    eliminate its use.  If so, return 1.  If not, return 0.
10046
10047    If BIV does not appear in X, return 1.
10048
10049    If ELIMINATE_P is nonzero, actually do the elimination.
10050    WHERE_INSN/WHERE_BB indicate where extra insns should be added.
10051    Depending on how many items have been moved out of the loop, it
10052    will either be before INSN (when WHERE_INSN is nonzero) or at the
10053    start of the loop (when WHERE_INSN is zero).  */
10054
10055 static int
10056 maybe_eliminate_biv_1 (const struct loop *loop, rtx x, rtx insn,
10057                        struct iv_class *bl, int eliminate_p,
10058                        basic_block where_bb, rtx where_insn)
10059 {
10060   enum rtx_code code = GET_CODE (x);
10061   rtx reg = bl->biv->dest_reg;
10062   enum machine_mode mode = GET_MODE (reg);
10063   struct induction *v;
10064   rtx arg, tem;
10065 #ifdef HAVE_cc0
10066   rtx new;
10067 #endif
10068   int arg_operand;
10069   const char *fmt;
10070   int i, j;
10071
10072   switch (code)
10073     {
10074     case REG:
10075       /* If we haven't already been able to do something with this BIV,
10076          we can't eliminate it.  */
10077       if (x == reg)
10078         return 0;
10079       return 1;
10080
10081     case SET:
10082       /* If this sets the BIV, it is not a problem.  */
10083       if (SET_DEST (x) == reg)
10084         return 1;
10085
10086       /* If this is an insn that defines a giv, it is also ok because
10087          it will go away when the giv is reduced.  */
10088       for (v = bl->giv; v; v = v->next_iv)
10089         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
10090           return 1;
10091
10092 #ifdef HAVE_cc0
10093       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
10094         {
10095           /* Can replace with any giv that was reduced and
10096              that has (MULT_VAL != 0) and (ADD_VAL == 0).
10097              Require a constant for MULT_VAL, so we know it's nonzero.
10098              ??? We disable this optimization to avoid potential
10099              overflows.  */
10100
10101           for (v = bl->giv; v; v = v->next_iv)
10102             if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
10103                 && v->add_val == const0_rtx
10104                 && ! v->ignore && ! v->maybe_dead && v->always_computable
10105                 && v->mode == mode
10106                 && 0)
10107               {
10108                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10109                   continue;
10110
10111                 if (! eliminate_p)
10112                   return 1;
10113
10114                 /* If the giv has the opposite direction of change,
10115                    then reverse the comparison.  */
10116                 if (INTVAL (v->mult_val) < 0)
10117                   new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
10118                                          const0_rtx, v->new_reg);
10119                 else
10120                   new = v->new_reg;
10121
10122                 /* We can probably test that giv's reduced reg.  */
10123                 if (validate_change (insn, &SET_SRC (x), new, 0))
10124                   return 1;
10125               }
10126
10127           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
10128              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
10129              Require a constant for MULT_VAL, so we know it's nonzero.
10130              ??? Do this only if ADD_VAL is a pointer to avoid a potential
10131              overflow problem.  */
10132
10133           for (v = bl->giv; v; v = v->next_iv)
10134             if (GET_CODE (v->mult_val) == CONST_INT
10135                 && v->mult_val != const0_rtx
10136                 && ! v->ignore && ! v->maybe_dead && v->always_computable
10137                 && v->mode == mode
10138                 && (GET_CODE (v->add_val) == SYMBOL_REF
10139                     || GET_CODE (v->add_val) == LABEL_REF
10140                     || GET_CODE (v->add_val) == CONST
10141                     || (REG_P (v->add_val)
10142                         && REG_POINTER (v->add_val))))
10143               {
10144                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10145                   continue;
10146
10147                 if (! eliminate_p)
10148                   return 1;
10149
10150                 /* If the giv has the opposite direction of change,
10151                    then reverse the comparison.  */
10152                 if (INTVAL (v->mult_val) < 0)
10153                   new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
10154                                          v->new_reg);
10155                 else
10156                   new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
10157                                          copy_rtx (v->add_val));
10158
10159                 /* Replace biv with the giv's reduced register.  */
10160                 update_reg_last_use (v->add_val, insn);
10161                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
10162                   return 1;
10163
10164                 /* Insn doesn't support that constant or invariant.  Copy it
10165                    into a register (it will be a loop invariant.)  */
10166                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
10167
10168                 loop_insn_emit_before (loop, 0, where_insn,
10169                                        gen_move_insn (tem,
10170                                                       copy_rtx (v->add_val)));
10171
10172                 /* Substitute the new register for its invariant value in
10173                    the compare expression.  */
10174                 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
10175                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
10176                   return 1;
10177               }
10178         }
10179 #endif
10180       break;
10181
10182     case COMPARE:
10183     case EQ:  case NE:
10184     case GT:  case GE:  case GTU:  case GEU:
10185     case LT:  case LE:  case LTU:  case LEU:
10186       /* See if either argument is the biv.  */
10187       if (XEXP (x, 0) == reg)
10188         arg = XEXP (x, 1), arg_operand = 1;
10189       else if (XEXP (x, 1) == reg)
10190         arg = XEXP (x, 0), arg_operand = 0;
10191       else
10192         break;
10193
10194       if (CONSTANT_P (arg))
10195         {
10196           /* First try to replace with any giv that has constant positive
10197              mult_val and constant add_val.  We might be able to support
10198              negative mult_val, but it seems complex to do it in general.  */
10199
10200           for (v = bl->giv; v; v = v->next_iv)
10201             if (GET_CODE (v->mult_val) == CONST_INT
10202                 && INTVAL (v->mult_val) > 0
10203                 && (GET_CODE (v->add_val) == SYMBOL_REF
10204                     || GET_CODE (v->add_val) == LABEL_REF
10205                     || GET_CODE (v->add_val) == CONST
10206                     || (REG_P (v->add_val)
10207                         && REG_POINTER (v->add_val)))
10208                 && ! v->ignore && ! v->maybe_dead && v->always_computable
10209                 && v->mode == mode)
10210               {
10211                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10212                   continue;
10213
10214                 /* Don't eliminate if the linear combination that makes up
10215                    the giv overflows when it is applied to ARG.  */
10216                 if (GET_CODE (arg) == CONST_INT)
10217                   {
10218                     rtx add_val;
10219
10220                     if (GET_CODE (v->add_val) == CONST_INT)
10221                       add_val = v->add_val;
10222                     else
10223                       add_val = const0_rtx;
10224
10225                     if (const_mult_add_overflow_p (arg, v->mult_val,
10226                                                    add_val, mode, 1))
10227                       continue;
10228                   }
10229
10230                 if (! eliminate_p)
10231                   return 1;
10232
10233                 /* Replace biv with the giv's reduced reg.  */
10234                 validate_change (insn, &XEXP (x, 1 - arg_operand), v->new_reg, 1);
10235
10236                 /* If all constants are actually constant integers and
10237                    the derived constant can be directly placed in the COMPARE,
10238                    do so.  */
10239                 if (GET_CODE (arg) == CONST_INT
10240                     && GET_CODE (v->add_val) == CONST_INT)
10241                   {
10242                     tem = expand_mult_add (arg, NULL_RTX, v->mult_val,
10243                                            v->add_val, mode, 1);
10244                   }
10245                 else
10246                   {
10247                     /* Otherwise, load it into a register.  */
10248                     tem = gen_reg_rtx (mode);
10249                     loop_iv_add_mult_emit_before (loop, arg,
10250                                                   v->mult_val, v->add_val,
10251                                                   tem, where_bb, where_insn);
10252                   }
10253
10254                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
10255
10256                 if (apply_change_group ())
10257                   return 1;
10258               }
10259
10260           /* Look for giv with positive constant mult_val and nonconst add_val.
10261              Insert insns to calculate new compare value.
10262              ??? Turn this off due to possible overflow.  */
10263
10264           for (v = bl->giv; v; v = v->next_iv)
10265             if (GET_CODE (v->mult_val) == CONST_INT
10266                 && INTVAL (v->mult_val) > 0
10267                 && ! v->ignore && ! v->maybe_dead && v->always_computable
10268                 && v->mode == mode
10269                 && 0)
10270               {
10271                 rtx tem;
10272
10273                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10274                   continue;
10275
10276                 if (! eliminate_p)
10277                   return 1;
10278
10279                 tem = gen_reg_rtx (mode);
10280
10281                 /* Replace biv with giv's reduced register.  */
10282                 validate_change (insn, &XEXP (x, 1 - arg_operand),
10283                                  v->new_reg, 1);
10284
10285                 /* Compute value to compare against.  */
10286                 loop_iv_add_mult_emit_before (loop, arg,
10287                                               v->mult_val, v->add_val,
10288                                               tem, where_bb, where_insn);
10289                 /* Use it in this insn.  */
10290                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
10291                 if (apply_change_group ())
10292                   return 1;
10293               }
10294         }
10295       else if (REG_P (arg) || MEM_P (arg))
10296         {
10297           if (loop_invariant_p (loop, arg) == 1)
10298             {
10299               /* Look for giv with constant positive mult_val and nonconst
10300                  add_val. Insert insns to compute new compare value.
10301                  ??? Turn this off due to possible overflow.  */
10302
10303               for (v = bl->giv; v; v = v->next_iv)
10304                 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
10305                     && ! v->ignore && ! v->maybe_dead && v->always_computable
10306                     && v->mode == mode
10307                     && 0)
10308                   {
10309                     rtx tem;
10310
10311                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10312                       continue;
10313
10314                     if (! eliminate_p)
10315                       return 1;
10316
10317                     tem = gen_reg_rtx (mode);
10318
10319                     /* Replace biv with giv's reduced register.  */
10320                     validate_change (insn, &XEXP (x, 1 - arg_operand),
10321                                      v->new_reg, 1);
10322
10323                     /* Compute value to compare against.  */
10324                     loop_iv_add_mult_emit_before (loop, arg,
10325                                                   v->mult_val, v->add_val,
10326                                                   tem, where_bb, where_insn);
10327                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
10328                     if (apply_change_group ())
10329                       return 1;
10330                   }
10331             }
10332
10333           /* This code has problems.  Basically, you can't know when
10334              seeing if we will eliminate BL, whether a particular giv
10335              of ARG will be reduced.  If it isn't going to be reduced,
10336              we can't eliminate BL.  We can try forcing it to be reduced,
10337              but that can generate poor code.
10338
10339              The problem is that the benefit of reducing TV, below should
10340              be increased if BL can actually be eliminated, but this means
10341              we might have to do a topological sort of the order in which
10342              we try to process biv.  It doesn't seem worthwhile to do
10343              this sort of thing now.  */
10344
10345 #if 0
10346           /* Otherwise the reg compared with had better be a biv.  */
10347           if (!REG_P (arg)
10348               || REG_IV_TYPE (ivs, REGNO (arg)) != BASIC_INDUCT)
10349             return 0;
10350
10351           /* Look for a pair of givs, one for each biv,
10352              with identical coefficients.  */
10353           for (v = bl->giv; v; v = v->next_iv)
10354             {
10355               struct induction *tv;
10356
10357               if (v->ignore || v->maybe_dead || v->mode != mode)
10358                 continue;
10359
10360               for (tv = REG_IV_CLASS (ivs, REGNO (arg))->giv; tv;
10361                    tv = tv->next_iv)
10362                 if (! tv->ignore && ! tv->maybe_dead
10363                     && rtx_equal_p (tv->mult_val, v->mult_val)
10364                     && rtx_equal_p (tv->add_val, v->add_val)
10365                     && tv->mode == mode)
10366                   {
10367                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
10368                       continue;
10369
10370                     if (! eliminate_p)
10371                       return 1;
10372
10373                     /* Replace biv with its giv's reduced reg.  */
10374                     XEXP (x, 1 - arg_operand) = v->new_reg;
10375                     /* Replace other operand with the other giv's
10376                        reduced reg.  */
10377                     XEXP (x, arg_operand) = tv->new_reg;
10378                     return 1;
10379                   }
10380             }
10381 #endif
10382         }
10383
10384       /* If we get here, the biv can't be eliminated.  */
10385       return 0;
10386
10387     case MEM:
10388       /* If this address is a DEST_ADDR giv, it doesn't matter if the
10389          biv is used in it, since it will be replaced.  */
10390       for (v = bl->giv; v; v = v->next_iv)
10391         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
10392           return 1;
10393       break;
10394
10395     default:
10396       break;
10397     }
10398
10399   /* See if any subexpression fails elimination.  */
10400   fmt = GET_RTX_FORMAT (code);
10401   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
10402     {
10403       switch (fmt[i])
10404         {
10405         case 'e':
10406           if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl,
10407                                        eliminate_p, where_bb, where_insn))
10408             return 0;
10409           break;
10410
10411         case 'E':
10412           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
10413             if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
10414                                          eliminate_p, where_bb, where_insn))
10415               return 0;
10416           break;
10417         }
10418     }
10419
10420   return 1;
10421 }
10422 \f
10423 /* Return nonzero if the last use of REG
10424    is in an insn following INSN in the same basic block.  */
10425
10426 static int
10427 last_use_this_basic_block (rtx reg, rtx insn)
10428 {
10429   rtx n;
10430   for (n = insn;
10431        n && !LABEL_P (n) && !JUMP_P (n);
10432        n = NEXT_INSN (n))
10433     {
10434       if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
10435         return 1;
10436     }
10437   return 0;
10438 }
10439 \f
10440 /* Called via `note_stores' to record the initial value of a biv.  Here we
10441    just record the location of the set and process it later.  */
10442
10443 static void
10444 record_initial (rtx dest, rtx set, void *data ATTRIBUTE_UNUSED)
10445 {
10446   struct loop_ivs *ivs = (struct loop_ivs *) data;
10447   struct iv_class *bl;
10448
10449   if (!REG_P (dest)
10450       || REGNO (dest) >= ivs->n_regs
10451       || REG_IV_TYPE (ivs, REGNO (dest)) != BASIC_INDUCT)
10452     return;
10453
10454   bl = REG_IV_CLASS (ivs, REGNO (dest));
10455
10456   /* If this is the first set found, record it.  */
10457   if (bl->init_insn == 0)
10458     {
10459       bl->init_insn = note_insn;
10460       bl->init_set = set;
10461     }
10462 }
10463 \f
10464 /* If any of the registers in X are "old" and currently have a last use earlier
10465    than INSN, update them to have a last use of INSN.  Their actual last use
10466    will be the previous insn but it will not have a valid uid_luid so we can't
10467    use it.  X must be a source expression only.  */
10468
10469 static void
10470 update_reg_last_use (rtx x, rtx insn)
10471 {
10472   /* Check for the case where INSN does not have a valid luid.  In this case,
10473      there is no need to modify the regno_last_uid, as this can only happen
10474      when code is inserted after the loop_end to set a pseudo's final value,
10475      and hence this insn will never be the last use of x.
10476      ???? This comment is not correct.  See for example loop_givs_reduce.
10477      This may insert an insn before another new insn.  */
10478   if (REG_P (x) && REGNO (x) < max_reg_before_loop
10479       && INSN_UID (insn) < max_uid_for_loop
10480       && REGNO_LAST_LUID (REGNO (x)) < INSN_LUID (insn))
10481     {
10482       REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
10483     }
10484   else
10485     {
10486       int i, j;
10487       const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
10488       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
10489         {
10490           if (fmt[i] == 'e')
10491             update_reg_last_use (XEXP (x, i), insn);
10492           else if (fmt[i] == 'E')
10493             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
10494               update_reg_last_use (XVECEXP (x, i, j), insn);
10495         }
10496     }
10497 }
10498 \f
10499 /* Similar to rtlanal.c:get_condition, except that we also put an
10500    invariant last unless both operands are invariants.  */
10501
10502 static rtx
10503 get_condition_for_loop (const struct loop *loop, rtx x)
10504 {
10505   rtx comparison = get_condition (x, (rtx*) 0, false, true);
10506
10507   if (comparison == 0
10508       || ! loop_invariant_p (loop, XEXP (comparison, 0))
10509       || loop_invariant_p (loop, XEXP (comparison, 1)))
10510     return comparison;
10511
10512   return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
10513                          XEXP (comparison, 1), XEXP (comparison, 0));
10514 }
10515
10516 /* Scan the function and determine whether it has indirect (computed) jumps.
10517
10518    This is taken mostly from flow.c; similar code exists elsewhere
10519    in the compiler.  It may be useful to put this into rtlanal.c.  */
10520 static int
10521 indirect_jump_in_function_p (rtx start)
10522 {
10523   rtx insn;
10524
10525   for (insn = start; insn; insn = NEXT_INSN (insn))
10526     if (computed_jump_p (insn))
10527       return 1;
10528
10529   return 0;
10530 }
10531
10532 /* Add MEM to the LOOP_MEMS array, if appropriate.  See the
10533    documentation for LOOP_MEMS for the definition of `appropriate'.
10534    This function is called from prescan_loop via for_each_rtx.  */
10535
10536 static int
10537 insert_loop_mem (rtx *mem, void *data ATTRIBUTE_UNUSED)
10538 {
10539   struct loop_info *loop_info = data;
10540   int i;
10541   rtx m = *mem;
10542
10543   if (m == NULL_RTX)
10544     return 0;
10545
10546   switch (GET_CODE (m))
10547     {
10548     case MEM:
10549       break;
10550
10551     case CLOBBER:
10552       /* We're not interested in MEMs that are only clobbered.  */
10553       return -1;
10554
10555     case CONST_DOUBLE:
10556       /* We're not interested in the MEM associated with a
10557          CONST_DOUBLE, so there's no need to traverse into this.  */
10558       return -1;
10559
10560     case EXPR_LIST:
10561       /* We're not interested in any MEMs that only appear in notes.  */
10562       return -1;
10563
10564     default:
10565       /* This is not a MEM.  */
10566       return 0;
10567     }
10568
10569   /* See if we've already seen this MEM.  */
10570   for (i = 0; i < loop_info->mems_idx; ++i)
10571     if (rtx_equal_p (m, loop_info->mems[i].mem))
10572       {
10573         if (MEM_VOLATILE_P (m) && !MEM_VOLATILE_P (loop_info->mems[i].mem))
10574           loop_info->mems[i].mem = m;
10575         if (GET_MODE (m) != GET_MODE (loop_info->mems[i].mem))
10576           /* The modes of the two memory accesses are different.  If
10577              this happens, something tricky is going on, and we just
10578              don't optimize accesses to this MEM.  */
10579           loop_info->mems[i].optimize = 0;
10580
10581         return 0;
10582       }
10583
10584   /* Resize the array, if necessary.  */
10585   if (loop_info->mems_idx == loop_info->mems_allocated)
10586     {
10587       if (loop_info->mems_allocated != 0)
10588         loop_info->mems_allocated *= 2;
10589       else
10590         loop_info->mems_allocated = 32;
10591
10592       loop_info->mems = xrealloc (loop_info->mems,
10593                                   loop_info->mems_allocated * sizeof (loop_mem_info));
10594     }
10595
10596   /* Actually insert the MEM.  */
10597   loop_info->mems[loop_info->mems_idx].mem = m;
10598   /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
10599      because we can't put it in a register.  We still store it in the
10600      table, though, so that if we see the same address later, but in a
10601      non-BLK mode, we'll not think we can optimize it at that point.  */
10602   loop_info->mems[loop_info->mems_idx].optimize = (GET_MODE (m) != BLKmode);
10603   loop_info->mems[loop_info->mems_idx].reg = NULL_RTX;
10604   ++loop_info->mems_idx;
10605
10606   return 0;
10607 }
10608
10609
10610 /* Allocate REGS->ARRAY or reallocate it if it is too small.
10611
10612    Increment REGS->ARRAY[I].SET_IN_LOOP at the index I of each
10613    register that is modified by an insn between FROM and TO.  If the
10614    value of an element of REGS->array[I].SET_IN_LOOP becomes 127 or
10615    more, stop incrementing it, to avoid overflow.
10616
10617    Store in REGS->ARRAY[I].SINGLE_USAGE the single insn in which
10618    register I is used, if it is only used once.  Otherwise, it is set
10619    to 0 (for no uses) or const0_rtx for more than one use.  This
10620    parameter may be zero, in which case this processing is not done.
10621
10622    Set REGS->ARRAY[I].MAY_NOT_OPTIMIZE nonzero if we should not
10623    optimize register I.  */
10624
10625 static void
10626 loop_regs_scan (const struct loop *loop, int extra_size)
10627 {
10628   struct loop_regs *regs = LOOP_REGS (loop);
10629   int old_nregs;
10630   /* last_set[n] is nonzero iff reg n has been set in the current
10631    basic block.  In that case, it is the insn that last set reg n.  */
10632   rtx *last_set;
10633   rtx insn;
10634   int i;
10635
10636   old_nregs = regs->num;
10637   regs->num = max_reg_num ();
10638
10639   /* Grow the regs array if not allocated or too small.  */
10640   if (regs->num >= regs->size)
10641     {
10642       regs->size = regs->num + extra_size;
10643
10644       regs->array = xrealloc (regs->array, regs->size * sizeof (*regs->array));
10645
10646       /* Zero the new elements.  */
10647       memset (regs->array + old_nregs, 0,
10648               (regs->size - old_nregs) * sizeof (*regs->array));
10649     }
10650
10651   /* Clear previously scanned fields but do not clear n_times_set.  */
10652   for (i = 0; i < old_nregs; i++)
10653     {
10654       regs->array[i].set_in_loop = 0;
10655       regs->array[i].may_not_optimize = 0;
10656       regs->array[i].single_usage = NULL_RTX;
10657     }
10658
10659   last_set = xcalloc (regs->num, sizeof (rtx));
10660
10661   /* Scan the loop, recording register usage.  */
10662   for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
10663        insn = NEXT_INSN (insn))
10664     {
10665       if (INSN_P (insn))
10666         {
10667           /* Record registers that have exactly one use.  */
10668           find_single_use_in_loop (regs, insn, PATTERN (insn));
10669
10670           /* Include uses in REG_EQUAL notes.  */
10671           if (REG_NOTES (insn))
10672             find_single_use_in_loop (regs, insn, REG_NOTES (insn));
10673
10674           if (GET_CODE (PATTERN (insn)) == SET
10675               || GET_CODE (PATTERN (insn)) == CLOBBER)
10676             count_one_set (regs, insn, PATTERN (insn), last_set);
10677           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
10678             {
10679               int i;
10680               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
10681                 count_one_set (regs, insn, XVECEXP (PATTERN (insn), 0, i),
10682                                last_set);
10683             }
10684         }
10685
10686       if (LABEL_P (insn) || JUMP_P (insn))
10687         memset (last_set, 0, regs->num * sizeof (rtx));
10688
10689       /* Invalidate all registers used for function argument passing.
10690          We check rtx_varies_p for the same reason as below, to allow
10691          optimizing PIC calculations.  */
10692       if (CALL_P (insn))
10693         {
10694           rtx link;
10695           for (link = CALL_INSN_FUNCTION_USAGE (insn);
10696                link;
10697                link = XEXP (link, 1))
10698             {
10699               rtx op, reg;
10700
10701               if (GET_CODE (op = XEXP (link, 0)) == USE
10702                   && REG_P (reg = XEXP (op, 0))
10703                   && rtx_varies_p (reg, 1))
10704                 regs->array[REGNO (reg)].may_not_optimize = 1;
10705             }
10706         }
10707     }
10708
10709   /* Invalidate all hard registers clobbered by calls.  With one exception:
10710      a call-clobbered PIC register is still function-invariant for our
10711      purposes, since we can hoist any PIC calculations out of the loop.
10712      Thus the call to rtx_varies_p.  */
10713   if (LOOP_INFO (loop)->has_call)
10714     for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
10715       if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i)
10716           && rtx_varies_p (regno_reg_rtx[i], 1))
10717         {
10718           regs->array[i].may_not_optimize = 1;
10719           regs->array[i].set_in_loop = 1;
10720         }
10721
10722 #ifdef AVOID_CCMODE_COPIES
10723   /* Don't try to move insns which set CC registers if we should not
10724      create CCmode register copies.  */
10725   for (i = regs->num - 1; i >= FIRST_PSEUDO_REGISTER; i--)
10726     if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
10727       regs->array[i].may_not_optimize = 1;
10728 #endif
10729
10730   /* Set regs->array[I].n_times_set for the new registers.  */
10731   for (i = old_nregs; i < regs->num; i++)
10732     regs->array[i].n_times_set = regs->array[i].set_in_loop;
10733
10734   free (last_set);
10735 }
10736
10737 /* Returns the number of real INSNs in the LOOP.  */
10738
10739 static int
10740 count_insns_in_loop (const struct loop *loop)
10741 {
10742   int count = 0;
10743   rtx insn;
10744
10745   for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
10746        insn = NEXT_INSN (insn))
10747     if (INSN_P (insn))
10748       ++count;
10749
10750   return count;
10751 }
10752
10753 /* Move MEMs into registers for the duration of the loop.  */
10754
10755 static void
10756 load_mems (const struct loop *loop)
10757 {
10758   struct loop_info *loop_info = LOOP_INFO (loop);
10759   struct loop_regs *regs = LOOP_REGS (loop);
10760   int maybe_never = 0;
10761   int i;
10762   rtx p, prev_ebb_head;
10763   rtx label = NULL_RTX;
10764   rtx end_label;
10765   /* Nonzero if the next instruction may never be executed.  */
10766   int next_maybe_never = 0;
10767   unsigned int last_max_reg = max_reg_num ();
10768
10769   if (loop_info->mems_idx == 0)
10770     return;
10771
10772   /* We cannot use next_label here because it skips over normal insns.  */
10773   end_label = next_nonnote_insn (loop->end);
10774   if (end_label && !LABEL_P (end_label))
10775     end_label = NULL_RTX;
10776
10777   /* Check to see if it's possible that some instructions in the loop are
10778      never executed.  Also check if there is a goto out of the loop other
10779      than right after the end of the loop.  */
10780   for (p = next_insn_in_loop (loop, loop->scan_start);
10781        p != NULL_RTX;
10782        p = next_insn_in_loop (loop, p))
10783     {
10784       if (LABEL_P (p))
10785         maybe_never = 1;
10786       else if (JUMP_P (p)
10787                /* If we enter the loop in the middle, and scan
10788                   around to the beginning, don't set maybe_never
10789                   for that.  This must be an unconditional jump,
10790                   otherwise the code at the top of the loop might
10791                   never be executed.  Unconditional jumps are
10792                   followed a by barrier then loop end.  */
10793                && ! (JUMP_P (p)
10794                      && JUMP_LABEL (p) == loop->top
10795                      && NEXT_INSN (NEXT_INSN (p)) == loop->end
10796                      && any_uncondjump_p (p)))
10797         {
10798           /* If this is a jump outside of the loop but not right
10799              after the end of the loop, we would have to emit new fixup
10800              sequences for each such label.  */
10801           if (/* If we can't tell where control might go when this
10802                  JUMP_INSN is executed, we must be conservative.  */
10803               !JUMP_LABEL (p)
10804               || (JUMP_LABEL (p) != end_label
10805                   && (INSN_UID (JUMP_LABEL (p)) >= max_uid_for_loop
10806                       || INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop->start)
10807                       || INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop->end))))
10808             return;
10809
10810           if (!any_condjump_p (p))
10811             /* Something complicated.  */
10812             maybe_never = 1;
10813           else
10814             /* If there are any more instructions in the loop, they
10815                might not be reached.  */
10816             next_maybe_never = 1;
10817         }
10818       else if (next_maybe_never)
10819         maybe_never = 1;
10820     }
10821
10822   /* Find start of the extended basic block that enters the loop.  */
10823   for (p = loop->start;
10824        PREV_INSN (p) && !LABEL_P (p);
10825        p = PREV_INSN (p))
10826     ;
10827   prev_ebb_head = p;
10828
10829   cselib_init (true);
10830
10831   /* Build table of mems that get set to constant values before the
10832      loop.  */
10833   for (; p != loop->start; p = NEXT_INSN (p))
10834     cselib_process_insn (p);
10835
10836   /* Actually move the MEMs.  */
10837   for (i = 0; i < loop_info->mems_idx; ++i)
10838     {
10839       regset_head load_copies;
10840       regset_head store_copies;
10841       int written = 0;
10842       rtx reg;
10843       rtx mem = loop_info->mems[i].mem;
10844       rtx mem_list_entry;
10845
10846       if (MEM_VOLATILE_P (mem)
10847           || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
10848         /* There's no telling whether or not MEM is modified.  */
10849         loop_info->mems[i].optimize = 0;
10850
10851       /* Go through the MEMs written to in the loop to see if this
10852          one is aliased by one of them.  */
10853       mem_list_entry = loop_info->store_mems;
10854       while (mem_list_entry)
10855         {
10856           if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
10857             written = 1;
10858           else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
10859                                     mem, rtx_varies_p))
10860             {
10861               /* MEM is indeed aliased by this store.  */
10862               loop_info->mems[i].optimize = 0;
10863               break;
10864             }
10865           mem_list_entry = XEXP (mem_list_entry, 1);
10866         }
10867
10868       if (flag_float_store && written
10869           && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
10870         loop_info->mems[i].optimize = 0;
10871
10872       /* If this MEM is written to, we must be sure that there
10873          are no reads from another MEM that aliases this one.  */
10874       if (loop_info->mems[i].optimize && written)
10875         {
10876           int j;
10877
10878           for (j = 0; j < loop_info->mems_idx; ++j)
10879             {
10880               if (j == i)
10881                 continue;
10882               else if (true_dependence (mem,
10883                                         VOIDmode,
10884                                         loop_info->mems[j].mem,
10885                                         rtx_varies_p))
10886                 {
10887                   /* It's not safe to hoist loop_info->mems[i] out of
10888                      the loop because writes to it might not be
10889                      seen by reads from loop_info->mems[j].  */
10890                   loop_info->mems[i].optimize = 0;
10891                   break;
10892                 }
10893             }
10894         }
10895
10896       if (maybe_never && may_trap_p (mem))
10897         /* We can't access the MEM outside the loop; it might
10898            cause a trap that wouldn't have happened otherwise.  */
10899         loop_info->mems[i].optimize = 0;
10900
10901       if (!loop_info->mems[i].optimize)
10902         /* We thought we were going to lift this MEM out of the
10903            loop, but later discovered that we could not.  */
10904         continue;
10905
10906       INIT_REG_SET (&load_copies);
10907       INIT_REG_SET (&store_copies);
10908
10909       /* Allocate a pseudo for this MEM.  We set REG_USERVAR_P in
10910          order to keep scan_loop from moving stores to this MEM
10911          out of the loop just because this REG is neither a
10912          user-variable nor used in the loop test.  */
10913       reg = gen_reg_rtx (GET_MODE (mem));
10914       REG_USERVAR_P (reg) = 1;
10915       loop_info->mems[i].reg = reg;
10916
10917       /* Now, replace all references to the MEM with the
10918          corresponding pseudos.  */
10919       maybe_never = 0;
10920       for (p = next_insn_in_loop (loop, loop->scan_start);
10921            p != NULL_RTX;
10922            p = next_insn_in_loop (loop, p))
10923         {
10924           if (INSN_P (p))
10925             {
10926               rtx set;
10927
10928               set = single_set (p);
10929
10930               /* See if this copies the mem into a register that isn't
10931                  modified afterwards.  We'll try to do copy propagation
10932                  a little further on.  */
10933               if (set
10934                   /* @@@ This test is _way_ too conservative.  */
10935                   && ! maybe_never
10936                   && REG_P (SET_DEST (set))
10937                   && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
10938                   && REGNO (SET_DEST (set)) < last_max_reg
10939                   && regs->array[REGNO (SET_DEST (set))].n_times_set == 1
10940                   && rtx_equal_p (SET_SRC (set), mem))
10941                 SET_REGNO_REG_SET (&load_copies, REGNO (SET_DEST (set)));
10942
10943               /* See if this copies the mem from a register that isn't
10944                  modified afterwards.  We'll try to remove the
10945                  redundant copy later on by doing a little register
10946                  renaming and copy propagation.   This will help
10947                  to untangle things for the BIV detection code.  */
10948               if (set
10949                   && ! maybe_never
10950                   && REG_P (SET_SRC (set))
10951                   && REGNO (SET_SRC (set)) >= FIRST_PSEUDO_REGISTER
10952                   && REGNO (SET_SRC (set)) < last_max_reg
10953                   && regs->array[REGNO (SET_SRC (set))].n_times_set == 1
10954                   && rtx_equal_p (SET_DEST (set), mem))
10955                 SET_REGNO_REG_SET (&store_copies, REGNO (SET_SRC (set)));
10956
10957               /* If this is a call which uses / clobbers this memory
10958                  location, we must not change the interface here.  */
10959               if (CALL_P (p)
10960                   && reg_mentioned_p (loop_info->mems[i].mem,
10961                                       CALL_INSN_FUNCTION_USAGE (p)))
10962                 {
10963                   cancel_changes (0);
10964                   loop_info->mems[i].optimize = 0;
10965                   break;
10966                 }
10967               else
10968                 /* Replace the memory reference with the shadow register.  */
10969                 replace_loop_mems (p, loop_info->mems[i].mem,
10970                                    loop_info->mems[i].reg, written);
10971             }
10972
10973           if (LABEL_P (p)
10974               || JUMP_P (p))
10975             maybe_never = 1;
10976         }
10977
10978       if (! loop_info->mems[i].optimize)
10979         ; /* We found we couldn't do the replacement, so do nothing.  */
10980       else if (! apply_change_group ())
10981         /* We couldn't replace all occurrences of the MEM.  */
10982         loop_info->mems[i].optimize = 0;
10983       else
10984         {
10985           /* Load the memory immediately before LOOP->START, which is
10986              the NOTE_LOOP_BEG.  */
10987           cselib_val *e = cselib_lookup (mem, VOIDmode, 0);
10988           rtx set;
10989           rtx best = mem;
10990           unsigned j;
10991           struct elt_loc_list *const_equiv = 0;
10992           reg_set_iterator rsi;
10993
10994           if (e)
10995             {
10996               struct elt_loc_list *equiv;
10997               struct elt_loc_list *best_equiv = 0;
10998               for (equiv = e->locs; equiv; equiv = equiv->next)
10999                 {
11000                   if (CONSTANT_P (equiv->loc))
11001                     const_equiv = equiv;
11002                   else if (REG_P (equiv->loc)
11003                            /* Extending hard register lifetimes causes crash
11004                               on SRC targets.  Doing so on non-SRC is
11005                               probably also not good idea, since we most
11006                               probably have pseudoregister equivalence as
11007                               well.  */
11008                            && REGNO (equiv->loc) >= FIRST_PSEUDO_REGISTER)
11009                     best_equiv = equiv;
11010                 }
11011               /* Use the constant equivalence if that is cheap enough.  */
11012               if (! best_equiv)
11013                 best_equiv = const_equiv;
11014               else if (const_equiv
11015                        && (rtx_cost (const_equiv->loc, SET)
11016                            <= rtx_cost (best_equiv->loc, SET)))
11017                 {
11018                   best_equiv = const_equiv;
11019                   const_equiv = 0;
11020                 }
11021
11022               /* If best_equiv is nonzero, we know that MEM is set to a
11023                  constant or register before the loop.  We will use this
11024                  knowledge to initialize the shadow register with that
11025                  constant or reg rather than by loading from MEM.  */
11026               if (best_equiv)
11027                 best = copy_rtx (best_equiv->loc);
11028             }
11029
11030           set = gen_move_insn (reg, best);
11031           set = loop_insn_hoist (loop, set);
11032           if (REG_P (best))
11033             {
11034               for (p = prev_ebb_head; p != loop->start; p = NEXT_INSN (p))
11035                 if (REGNO_LAST_UID (REGNO (best)) == INSN_UID (p))
11036                   {
11037                     REGNO_LAST_UID (REGNO (best)) = INSN_UID (set);
11038                     break;
11039                   }
11040             }
11041
11042           if (const_equiv)
11043             set_unique_reg_note (set, REG_EQUAL, copy_rtx (const_equiv->loc));
11044
11045           if (written)
11046             {
11047               if (label == NULL_RTX)
11048                 {
11049                   label = gen_label_rtx ();
11050                   emit_label_after (label, loop->end);
11051                 }
11052
11053               /* Store the memory immediately after END, which is
11054                  the NOTE_LOOP_END.  */
11055               set = gen_move_insn (copy_rtx (mem), reg);
11056               loop_insn_emit_after (loop, 0, label, set);
11057             }
11058
11059           if (loop_dump_stream)
11060             {
11061               fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
11062                        REGNO (reg), (written ? "r/w" : "r/o"));
11063               print_rtl (loop_dump_stream, mem);
11064               fputc ('\n', loop_dump_stream);
11065             }
11066
11067           /* Attempt a bit of copy propagation.  This helps untangle the
11068              data flow, and enables {basic,general}_induction_var to find
11069              more bivs/givs.  */
11070           EXECUTE_IF_SET_IN_REG_SET
11071             (&load_copies, FIRST_PSEUDO_REGISTER, j, rsi)
11072             {
11073               try_copy_prop (loop, reg, j);
11074             }
11075           CLEAR_REG_SET (&load_copies);
11076
11077           EXECUTE_IF_SET_IN_REG_SET
11078             (&store_copies, FIRST_PSEUDO_REGISTER, j, rsi)
11079             {
11080               try_swap_copy_prop (loop, reg, j);
11081             }
11082           CLEAR_REG_SET (&store_copies);
11083         }
11084     }
11085
11086   /* Now, we need to replace all references to the previous exit
11087      label with the new one.  */
11088   if (label != NULL_RTX && end_label != NULL_RTX)
11089     for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
11090       if (JUMP_P (p) && JUMP_LABEL (p) == end_label)
11091         redirect_jump (p, label, false);
11092
11093   cselib_finish ();
11094 }
11095
11096 /* For communication between note_reg_stored and its caller.  */
11097 struct note_reg_stored_arg
11098 {
11099   int set_seen;
11100   rtx reg;
11101 };
11102
11103 /* Called via note_stores, record in SET_SEEN whether X, which is written,
11104    is equal to ARG.  */
11105 static void
11106 note_reg_stored (rtx x, rtx setter ATTRIBUTE_UNUSED, void *arg)
11107 {
11108   struct note_reg_stored_arg *t = (struct note_reg_stored_arg *) arg;
11109   if (t->reg == x)
11110     t->set_seen = 1;
11111 }
11112
11113 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
11114    There must be exactly one insn that sets this pseudo; it will be
11115    deleted if all replacements succeed and we can prove that the register
11116    is not used after the loop.  */
11117
11118 static void
11119 try_copy_prop (const struct loop *loop, rtx replacement, unsigned int regno)
11120 {
11121   /* This is the reg that we are copying from.  */
11122   rtx reg_rtx = regno_reg_rtx[regno];
11123   rtx init_insn = 0;
11124   rtx insn;
11125   /* These help keep track of whether we replaced all uses of the reg.  */
11126   int replaced_last = 0;
11127   int store_is_first = 0;
11128
11129   for (insn = next_insn_in_loop (loop, loop->scan_start);
11130        insn != NULL_RTX;
11131        insn = next_insn_in_loop (loop, insn))
11132     {
11133       rtx set;
11134
11135       /* Only substitute within one extended basic block from the initializing
11136          insn.  */
11137       if (LABEL_P (insn) && init_insn)
11138         break;
11139
11140       if (! INSN_P (insn))
11141         continue;
11142
11143       /* Is this the initializing insn?  */
11144       set = single_set (insn);
11145       if (set
11146           && REG_P (SET_DEST (set))
11147           && REGNO (SET_DEST (set)) == regno)
11148         {
11149           gcc_assert (!init_insn);
11150
11151           init_insn = insn;
11152           if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
11153             store_is_first = 1;
11154         }
11155
11156       /* Only substitute after seeing the initializing insn.  */
11157       if (init_insn && insn != init_insn)
11158         {
11159           struct note_reg_stored_arg arg;
11160
11161           replace_loop_regs (insn, reg_rtx, replacement);
11162           if (REGNO_LAST_UID (regno) == INSN_UID (insn))
11163             replaced_last = 1;
11164
11165           /* Stop replacing when REPLACEMENT is modified.  */
11166           arg.reg = replacement;
11167           arg.set_seen = 0;
11168           note_stores (PATTERN (insn), note_reg_stored, &arg);
11169           if (arg.set_seen)
11170             {
11171               rtx note = find_reg_note (insn, REG_EQUAL, NULL);
11172
11173               /* It is possible that we've turned previously valid REG_EQUAL to
11174                  invalid, as we change the REGNO to REPLACEMENT and unlike REGNO,
11175                  REPLACEMENT is modified, we get different meaning.  */
11176               if (note && reg_mentioned_p (replacement, XEXP (note, 0)))
11177                 remove_note (insn, note);
11178               break;
11179             }
11180         }
11181     }
11182   gcc_assert (init_insn);
11183   if (apply_change_group ())
11184     {
11185       if (loop_dump_stream)
11186         fprintf (loop_dump_stream, "  Replaced reg %d", regno);
11187       if (store_is_first && replaced_last)
11188         {
11189           rtx first;
11190           rtx retval_note;
11191
11192           /* Assume we're just deleting INIT_INSN.  */
11193           first = init_insn;
11194           /* Look for REG_RETVAL note.  If we're deleting the end of
11195              the libcall sequence, the whole sequence can go.  */
11196           retval_note = find_reg_note (init_insn, REG_RETVAL, NULL_RTX);
11197           /* If we found a REG_RETVAL note, find the first instruction
11198              in the sequence.  */
11199           if (retval_note)
11200             first = XEXP (retval_note, 0);
11201
11202           /* Delete the instructions.  */
11203           loop_delete_insns (first, init_insn);
11204         }
11205       if (loop_dump_stream)
11206         fprintf (loop_dump_stream, ".\n");
11207     }
11208 }
11209
11210 /* Replace all the instructions from FIRST up to and including LAST
11211    with NOTE_INSN_DELETED notes.  */
11212
11213 static void
11214 loop_delete_insns (rtx first, rtx last)
11215 {
11216   while (1)
11217     {
11218       if (loop_dump_stream)
11219         fprintf (loop_dump_stream, ", deleting init_insn (%d)",
11220                  INSN_UID (first));
11221       delete_insn (first);
11222
11223       /* If this was the LAST instructions we're supposed to delete,
11224          we're done.  */
11225       if (first == last)
11226         break;
11227
11228       first = NEXT_INSN (first);
11229     }
11230 }
11231
11232 /* Try to replace occurrences of pseudo REGNO with REPLACEMENT within
11233    loop LOOP if the order of the sets of these registers can be
11234    swapped.  There must be exactly one insn within the loop that sets
11235    this pseudo followed immediately by a move insn that sets
11236    REPLACEMENT with REGNO.  */
11237 static void
11238 try_swap_copy_prop (const struct loop *loop, rtx replacement,
11239                     unsigned int regno)
11240 {
11241   rtx insn;
11242   rtx set = NULL_RTX;
11243   unsigned int new_regno;
11244
11245   new_regno = REGNO (replacement);
11246
11247   for (insn = next_insn_in_loop (loop, loop->scan_start);
11248        insn != NULL_RTX;
11249        insn = next_insn_in_loop (loop, insn))
11250     {
11251       /* Search for the insn that copies REGNO to NEW_REGNO?  */
11252       if (INSN_P (insn)
11253           && (set = single_set (insn))
11254           && REG_P (SET_DEST (set))
11255           && REGNO (SET_DEST (set)) == new_regno
11256           && REG_P (SET_SRC (set))
11257           && REGNO (SET_SRC (set)) == regno)
11258         break;
11259     }
11260
11261   if (insn != NULL_RTX)
11262     {
11263       rtx prev_insn;
11264       rtx prev_set;
11265
11266       /* Some DEF-USE info would come in handy here to make this
11267          function more general.  For now, just check the previous insn
11268          which is the most likely candidate for setting REGNO.  */
11269
11270       prev_insn = PREV_INSN (insn);
11271
11272       if (INSN_P (insn)
11273           && (prev_set = single_set (prev_insn))
11274           && REG_P (SET_DEST (prev_set))
11275           && REGNO (SET_DEST (prev_set)) == regno)
11276         {
11277           /* We have:
11278              (set (reg regno) (expr))
11279              (set (reg new_regno) (reg regno))
11280
11281              so try converting this to:
11282              (set (reg new_regno) (expr))
11283              (set (reg regno) (reg new_regno))
11284
11285              The former construct is often generated when a global
11286              variable used for an induction variable is shadowed by a
11287              register (NEW_REGNO).  The latter construct improves the
11288              chances of GIV replacement and BIV elimination.  */
11289
11290           validate_change (prev_insn, &SET_DEST (prev_set),
11291                            replacement, 1);
11292           validate_change (insn, &SET_DEST (set),
11293                            SET_SRC (set), 1);
11294           validate_change (insn, &SET_SRC (set),
11295                            replacement, 1);
11296
11297           if (apply_change_group ())
11298             {
11299               if (loop_dump_stream)
11300                 fprintf (loop_dump_stream,
11301                          "  Swapped set of reg %d at %d with reg %d at %d.\n",
11302                          regno, INSN_UID (insn),
11303                          new_regno, INSN_UID (prev_insn));
11304
11305               /* Update first use of REGNO.  */
11306               if (REGNO_FIRST_UID (regno) == INSN_UID (prev_insn))
11307                 REGNO_FIRST_UID (regno) = INSN_UID (insn);
11308
11309               /* Now perform copy propagation to hopefully
11310                  remove all uses of REGNO within the loop.  */
11311               try_copy_prop (loop, replacement, regno);
11312             }
11313         }
11314     }
11315 }
11316
11317 /* Worker function for find_mem_in_note, called via for_each_rtx.  */
11318
11319 static int
11320 find_mem_in_note_1 (rtx *x, void *data)
11321 {
11322   if (*x != NULL_RTX && MEM_P (*x))
11323     {
11324       rtx *res = (rtx *) data;
11325       *res = *x;
11326       return 1;
11327     }
11328   return 0;
11329 }
11330
11331 /* Returns the first MEM found in NOTE by depth-first search.  */
11332
11333 static rtx
11334 find_mem_in_note (rtx note)
11335 {
11336   if (note && for_each_rtx (&note, find_mem_in_note_1, &note))
11337     return note;
11338   return NULL_RTX;
11339 }
11340
11341 /* Replace MEM with its associated pseudo register.  This function is
11342    called from load_mems via for_each_rtx.  DATA is actually a pointer
11343    to a structure describing the instruction currently being scanned
11344    and the MEM we are currently replacing.  */
11345
11346 static int
11347 replace_loop_mem (rtx *mem, void *data)
11348 {
11349   loop_replace_args *args = (loop_replace_args *) data;
11350   rtx m = *mem;
11351
11352   if (m == NULL_RTX)
11353     return 0;
11354
11355   switch (GET_CODE (m))
11356     {
11357     case MEM:
11358       break;
11359
11360     case CONST_DOUBLE:
11361       /* We're not interested in the MEM associated with a
11362          CONST_DOUBLE, so there's no need to traverse into one.  */
11363       return -1;
11364
11365     default:
11366       /* This is not a MEM.  */
11367       return 0;
11368     }
11369
11370   if (!rtx_equal_p (args->match, m))
11371     /* This is not the MEM we are currently replacing.  */
11372     return 0;
11373
11374   /* Actually replace the MEM.  */
11375   validate_change (args->insn, mem, args->replacement, 1);
11376
11377   return 0;
11378 }
11379
11380 static void
11381 replace_loop_mems (rtx insn, rtx mem, rtx reg, int written)
11382 {
11383   loop_replace_args args;
11384
11385   args.insn = insn;
11386   args.match = mem;
11387   args.replacement = reg;
11388
11389   for_each_rtx (&insn, replace_loop_mem, &args);
11390
11391   /* If we hoist a mem write out of the loop, then REG_EQUAL
11392      notes referring to the mem are no longer valid.  */
11393   if (written)
11394     {
11395       rtx note, sub;
11396       rtx *link;
11397
11398       for (link = &REG_NOTES (insn); (note = *link); link = &XEXP (note, 1))
11399         {
11400           if (REG_NOTE_KIND (note) == REG_EQUAL
11401               && (sub = find_mem_in_note (note))
11402               && true_dependence (mem, VOIDmode, sub, rtx_varies_p))
11403             {
11404               /* Remove the note.  */
11405               validate_change (NULL_RTX, link, XEXP (note, 1), 1);
11406               break;
11407             }
11408         }
11409     }
11410 }
11411
11412 /* Replace one register with another.  Called through for_each_rtx; PX points
11413    to the rtx being scanned.  DATA is actually a pointer to
11414    a structure of arguments.  */
11415
11416 static int
11417 replace_loop_reg (rtx *px, void *data)
11418 {
11419   rtx x = *px;
11420   loop_replace_args *args = (loop_replace_args *) data;
11421
11422   if (x == NULL_RTX)
11423     return 0;
11424
11425   if (x == args->match)
11426     validate_change (args->insn, px, args->replacement, 1);
11427
11428   return 0;
11429 }
11430
11431 static void
11432 replace_loop_regs (rtx insn, rtx reg, rtx replacement)
11433 {
11434   loop_replace_args args;
11435
11436   args.insn = insn;
11437   args.match = reg;
11438   args.replacement = replacement;
11439
11440   for_each_rtx (&insn, replace_loop_reg, &args);
11441 }
11442 \f
11443 /* Emit insn for PATTERN after WHERE_INSN in basic block WHERE_BB
11444    (ignored in the interim).  */
11445
11446 static rtx
11447 loop_insn_emit_after (const struct loop *loop ATTRIBUTE_UNUSED,
11448                       basic_block where_bb ATTRIBUTE_UNUSED, rtx where_insn,
11449                       rtx pattern)
11450 {
11451   return emit_insn_after (pattern, where_insn);
11452 }
11453
11454
11455 /* If WHERE_INSN is nonzero emit insn for PATTERN before WHERE_INSN
11456    in basic block WHERE_BB (ignored in the interim) within the loop
11457    otherwise hoist PATTERN into the loop pre-header.  */
11458
11459 static rtx
11460 loop_insn_emit_before (const struct loop *loop,
11461                        basic_block where_bb ATTRIBUTE_UNUSED,
11462                        rtx where_insn, rtx pattern)
11463 {
11464   if (! where_insn)
11465     return loop_insn_hoist (loop, pattern);
11466   return emit_insn_before (pattern, where_insn);
11467 }
11468
11469
11470 /* Emit call insn for PATTERN before WHERE_INSN in basic block
11471    WHERE_BB (ignored in the interim) within the loop.  */
11472
11473 static rtx
11474 loop_call_insn_emit_before (const struct loop *loop ATTRIBUTE_UNUSED,
11475                             basic_block where_bb ATTRIBUTE_UNUSED,
11476                             rtx where_insn, rtx pattern)
11477 {
11478   return emit_call_insn_before (pattern, where_insn);
11479 }
11480
11481
11482 /* Hoist insn for PATTERN into the loop pre-header.  */
11483
11484 static rtx
11485 loop_insn_hoist (const struct loop *loop, rtx pattern)
11486 {
11487   return loop_insn_emit_before (loop, 0, loop->start, pattern);
11488 }
11489
11490
11491 /* Hoist call insn for PATTERN into the loop pre-header.  */
11492
11493 static rtx
11494 loop_call_insn_hoist (const struct loop *loop, rtx pattern)
11495 {
11496   return loop_call_insn_emit_before (loop, 0, loop->start, pattern);
11497 }
11498
11499
11500 /* Sink insn for PATTERN after the loop end.  */
11501
11502 static rtx
11503 loop_insn_sink (const struct loop *loop, rtx pattern)
11504 {
11505   return loop_insn_emit_before (loop, 0, loop->sink, pattern);
11506 }
11507
11508 /* bl->final_value can be either general_operand or PLUS of general_operand
11509    and constant.  Emit sequence of instructions to load it into REG.  */
11510 static rtx
11511 gen_load_of_final_value (rtx reg, rtx final_value)
11512 {
11513   rtx seq;
11514   start_sequence ();
11515   final_value = force_operand (final_value, reg);
11516   if (final_value != reg)
11517     emit_move_insn (reg, final_value);
11518   seq = get_insns ();
11519   end_sequence ();
11520   return seq;
11521 }
11522
11523 /* If the loop has multiple exits, emit insn for PATTERN before the
11524    loop to ensure that it will always be executed no matter how the
11525    loop exits.  Otherwise, emit the insn for PATTERN after the loop,
11526    since this is slightly more efficient.  */
11527
11528 static rtx
11529 loop_insn_sink_or_swim (const struct loop *loop, rtx pattern)
11530 {
11531   if (loop->exit_count)
11532     return loop_insn_hoist (loop, pattern);
11533   else
11534     return loop_insn_sink (loop, pattern);
11535 }
11536 \f
11537 static void
11538 loop_ivs_dump (const struct loop *loop, FILE *file, int verbose)
11539 {
11540   struct iv_class *bl;
11541   int iv_num = 0;
11542
11543   if (! loop || ! file)
11544     return;
11545
11546   for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
11547     iv_num++;
11548
11549   fprintf (file, "Loop %d: %d IV classes\n", loop->num, iv_num);
11550
11551   for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
11552     {
11553       loop_iv_class_dump (bl, file, verbose);
11554       fputc ('\n', file);
11555     }
11556 }
11557
11558
11559 static void
11560 loop_iv_class_dump (const struct iv_class *bl, FILE *file,
11561                     int verbose ATTRIBUTE_UNUSED)
11562 {
11563   struct induction *v;
11564   rtx incr;
11565   int i;
11566
11567   if (! bl || ! file)
11568     return;
11569
11570   fprintf (file, "IV class for reg %d, benefit %d\n",
11571            bl->regno, bl->total_benefit);
11572
11573   fprintf (file, " Init insn %d", INSN_UID (bl->init_insn));
11574   if (bl->initial_value)
11575     {
11576       fprintf (file, ", init val: ");
11577       print_simple_rtl (file, bl->initial_value);
11578     }
11579   if (bl->initial_test)
11580     {
11581       fprintf (file, ", init test: ");
11582       print_simple_rtl (file, bl->initial_test);
11583     }
11584   fputc ('\n', file);
11585
11586   if (bl->final_value)
11587     {
11588       fprintf (file, " Final val: ");
11589       print_simple_rtl (file, bl->final_value);
11590       fputc ('\n', file);
11591     }
11592
11593   if ((incr = biv_total_increment (bl)))
11594     {
11595       fprintf (file, " Total increment: ");
11596       print_simple_rtl (file, incr);
11597       fputc ('\n', file);
11598     }
11599
11600   /* List the increments.  */
11601   for (i = 0, v = bl->biv; v; v = v->next_iv, i++)
11602     {
11603       fprintf (file, " Inc%d: insn %d, incr: ", i, INSN_UID (v->insn));
11604       print_simple_rtl (file, v->add_val);
11605       fputc ('\n', file);
11606     }
11607
11608   /* List the givs.  */
11609   for (i = 0, v = bl->giv; v; v = v->next_iv, i++)
11610     {
11611       fprintf (file, " Giv%d: insn %d, benefit %d, ",
11612                i, INSN_UID (v->insn), v->benefit);
11613       if (v->giv_type == DEST_ADDR)
11614         print_simple_rtl (file, v->mem);
11615       else
11616         print_simple_rtl (file, single_set (v->insn));
11617       fputc ('\n', file);
11618     }
11619 }
11620
11621
11622 static void
11623 loop_biv_dump (const struct induction *v, FILE *file, int verbose)
11624 {
11625   if (! v || ! file)
11626     return;
11627
11628   fprintf (file,
11629            "Biv %d: insn %d",
11630            REGNO (v->dest_reg), INSN_UID (v->insn));
11631   fprintf (file, " const ");
11632   print_simple_rtl (file, v->add_val);
11633
11634   if (verbose && v->final_value)
11635     {
11636       fputc ('\n', file);
11637       fprintf (file, " final ");
11638       print_simple_rtl (file, v->final_value);
11639     }
11640
11641   fputc ('\n', file);
11642 }
11643
11644
11645 static void
11646 loop_giv_dump (const struct induction *v, FILE *file, int verbose)
11647 {
11648   if (! v || ! file)
11649     return;
11650
11651   if (v->giv_type == DEST_REG)
11652     fprintf (file, "Giv %d: insn %d",
11653              REGNO (v->dest_reg), INSN_UID (v->insn));
11654   else
11655     fprintf (file, "Dest address: insn %d",
11656              INSN_UID (v->insn));
11657
11658   fprintf (file, " src reg %d benefit %d",
11659            REGNO (v->src_reg), v->benefit);
11660   fprintf (file, " lifetime %d",
11661            v->lifetime);
11662
11663   if (v->replaceable)
11664     fprintf (file, " replaceable");
11665
11666   if (v->no_const_addval)
11667     fprintf (file, " ncav");
11668
11669   if (v->ext_dependent)
11670     {
11671       switch (GET_CODE (v->ext_dependent))
11672         {
11673         case SIGN_EXTEND:
11674           fprintf (file, " ext se");
11675           break;
11676         case ZERO_EXTEND:
11677           fprintf (file, " ext ze");
11678           break;
11679         case TRUNCATE:
11680           fprintf (file, " ext tr");
11681           break;
11682         default:
11683           gcc_unreachable ();
11684         }
11685     }
11686
11687   fputc ('\n', file);
11688   fprintf (file, " mult ");
11689   print_simple_rtl (file, v->mult_val);
11690
11691   fputc ('\n', file);
11692   fprintf (file, " add  ");
11693   print_simple_rtl (file, v->add_val);
11694
11695   if (verbose && v->final_value)
11696     {
11697       fputc ('\n', file);
11698       fprintf (file, " final ");
11699       print_simple_rtl (file, v->final_value);
11700     }
11701
11702   fputc ('\n', file);
11703 }
11704
11705
11706 void
11707 debug_ivs (const struct loop *loop)
11708 {
11709   loop_ivs_dump (loop, stderr, 1);
11710 }
11711
11712
11713 void
11714 debug_iv_class (const struct iv_class *bl)
11715 {
11716   loop_iv_class_dump (bl, stderr, 1);
11717 }
11718
11719
11720 void
11721 debug_biv (const struct induction *v)
11722 {
11723   loop_biv_dump (v, stderr, 1);
11724 }
11725
11726
11727 void
11728 debug_giv (const struct induction *v)
11729 {
11730   loop_giv_dump (v, stderr, 1);
11731 }
11732
11733
11734 #define LOOP_BLOCK_NUM_1(INSN) \
11735 ((INSN) ? (BLOCK_FOR_INSN (INSN) ? BLOCK_NUM (INSN) : - 1) : -1)
11736
11737 /* The notes do not have an assigned block, so look at the next insn.  */
11738 #define LOOP_BLOCK_NUM(INSN) \
11739 ((INSN) ? (NOTE_P (INSN) \
11740             ? LOOP_BLOCK_NUM_1 (next_nonnote_insn (INSN)) \
11741             : LOOP_BLOCK_NUM_1 (INSN)) \
11742         : -1)
11743
11744 #define LOOP_INSN_UID(INSN) ((INSN) ? INSN_UID (INSN) : -1)
11745
11746 static void
11747 loop_dump_aux (const struct loop *loop, FILE *file,
11748                int verbose ATTRIBUTE_UNUSED)
11749 {
11750   rtx label;
11751
11752   if (! loop || ! file || !BB_HEAD (loop->first))
11753     return;
11754
11755   /* Print diagnostics to compare our concept of a loop with
11756      what the loop notes say.  */
11757   if (! PREV_INSN (BB_HEAD (loop->first))
11758       || !NOTE_P (PREV_INSN (BB_HEAD (loop->first)))
11759       || NOTE_LINE_NUMBER (PREV_INSN (BB_HEAD (loop->first)))
11760       != NOTE_INSN_LOOP_BEG)
11761     fprintf (file, ";;  No NOTE_INSN_LOOP_BEG at %d\n",
11762              INSN_UID (PREV_INSN (BB_HEAD (loop->first))));
11763   if (! NEXT_INSN (BB_END (loop->last))
11764       || !NOTE_P (NEXT_INSN (BB_END (loop->last)))
11765       || NOTE_LINE_NUMBER (NEXT_INSN (BB_END (loop->last)))
11766       != NOTE_INSN_LOOP_END)
11767     fprintf (file, ";;  No NOTE_INSN_LOOP_END at %d\n",
11768              INSN_UID (NEXT_INSN (BB_END (loop->last))));
11769
11770   if (loop->start)
11771     {
11772       fprintf (file,
11773                ";;  start %d (%d), end %d (%d)\n",
11774                LOOP_BLOCK_NUM (loop->start),
11775                LOOP_INSN_UID (loop->start),
11776                LOOP_BLOCK_NUM (loop->end),
11777                LOOP_INSN_UID (loop->end));
11778       fprintf (file, ";;  top %d (%d), scan start %d (%d)\n",
11779                LOOP_BLOCK_NUM (loop->top),
11780                LOOP_INSN_UID (loop->top),
11781                LOOP_BLOCK_NUM (loop->scan_start),
11782                LOOP_INSN_UID (loop->scan_start));
11783       fprintf (file, ";;  exit_count %d", loop->exit_count);
11784       if (loop->exit_count)
11785         {
11786           fputs (", labels:", file);
11787           for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
11788             {
11789               fprintf (file, " %d ",
11790                        LOOP_INSN_UID (XEXP (label, 0)));
11791             }
11792         }
11793       fputs ("\n", file);
11794     }
11795 }
11796
11797 /* Call this function from the debugger to dump LOOP.  */
11798
11799 void
11800 debug_loop (const struct loop *loop)
11801 {
11802   flow_loop_dump (loop, stderr, loop_dump_aux, 1);
11803 }
11804
11805 /* Call this function from the debugger to dump LOOPS.  */
11806
11807 void
11808 debug_loops (const struct loops *loops)
11809 {
11810   flow_loops_dump (loops, stderr, loop_dump_aux, 1);
11811 }
11812 \f
11813 static bool
11814 gate_handle_loop_optimize (void)
11815 {
11816   return (optimize > 0 && flag_loop_optimize);
11817 }
11818
11819 /* Move constant computations out of loops.  */
11820 static void
11821 rest_of_handle_loop_optimize (void)
11822 {
11823   int do_prefetch;
11824
11825   /* CFG is no longer maintained up-to-date.  */
11826   free_bb_for_insn ();
11827   profile_status = PROFILE_ABSENT;
11828   
11829   do_prefetch = flag_prefetch_loop_arrays ? LOOP_PREFETCH : 0;
11830   
11831   if (flag_rerun_loop_opt)
11832     {
11833       cleanup_barriers ();
11834       
11835       /* We only want to perform unrolling once.  */
11836       loop_optimize (get_insns (), dump_file, 0);
11837       
11838       /* The first call to loop_optimize makes some instructions
11839          trivially dead.  We delete those instructions now in the
11840          hope that doing so will make the heuristics in loop work
11841          better and possibly speed up compilation.  */
11842       delete_trivially_dead_insns (get_insns (), max_reg_num ());
11843   
11844       /* The regscan pass is currently necessary as the alias
11845          analysis code depends on this information.  */
11846       reg_scan (get_insns (), max_reg_num ());
11847     } 
11848   cleanup_barriers ();
11849   loop_optimize (get_insns (), dump_file, do_prefetch);
11850       
11851   /* Loop can create trivially dead instructions.  */
11852   delete_trivially_dead_insns (get_insns (), max_reg_num ());
11853   find_basic_blocks (get_insns ());
11854 }
11855
11856 struct tree_opt_pass pass_loop_optimize =
11857 {
11858   "old-loop",                           /* name */
11859   gate_handle_loop_optimize,            /* gate */   
11860   rest_of_handle_loop_optimize,         /* execute */       
11861   NULL,                                 /* sub */
11862   NULL,                                 /* next */
11863   0,                                    /* static_pass_number */
11864   TV_LOOP,                              /* tv_id */
11865   0,                                    /* properties_required */
11866   0,                                    /* properties_provided */
11867   0,                                    /* properties_destroyed */
11868   0,                                    /* todo_flags_start */
11869   TODO_dump_func |
11870   TODO_ggc_collect,                     /* todo_flags_finish */
11871   'L'                                   /* letter */
11872 };
11873
11874