OSDN Git Service

* loop.c (basic_induction_var): A non-integer variable which is
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Perform various loop optimizations, including strength reduction.
2    Copyright (C) 1987, 88, 89, 91-98, 1999 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21
22 /* This is the loop optimization pass of the compiler.
23    It finds invariant computations within loops and moves them
24    to the beginning of the loop.  Then it identifies basic and 
25    general induction variables.  Strength reduction is applied to the general
26    induction variables, and induction variable elimination is applied to
27    the basic induction variables.
28
29    It also finds cases where
30    a register is set within the loop by zero-extending a narrower value
31    and changes these to zero the entire register once before the loop
32    and merely copy the low part within the loop.
33
34    Most of the complexity is in heuristics to decide when it is worth
35    while to do these things.  */
36
37 #include "config.h"
38 #include "system.h"
39 #include "rtl.h"
40 #include "tm_p.h"
41 #include "obstack.h"
42 #include "function.h"
43 #include "expr.h"
44 #include "insn-config.h"
45 #include "insn-flags.h"
46 #include "regs.h"
47 #include "hard-reg-set.h"
48 #include "recog.h"
49 #include "flags.h"
50 #include "real.h"
51 #include "loop.h"
52 #include "except.h"
53 #include "toplev.h"
54
55 /* Information about the loop being processed used to compute
56    the number of loop iterations for loop unrolling and doloop
57    optimization.  */
58 static struct loop_info this_loop_info;
59
60 /* Vector mapping INSN_UIDs to luids.
61    The luids are like uids but increase monotonically always.
62    We use them to see whether a jump comes from outside a given loop.  */
63
64 int *uid_luid;
65
66 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
67    number the insn is contained in.  */
68
69 int *uid_loop_num;
70
71 /* 1 + largest uid of any insn.  */
72
73 int max_uid_for_loop;
74
75 /* 1 + luid of last insn.  */
76
77 static int max_luid;
78
79 /* Number of loops detected in current function.  Used as index to the
80    next few tables.  */
81
82 static int max_loop_num;
83
84 /* Indexed by loop number, contains the first and last insn of each loop.  */
85
86 static rtx *loop_number_loop_starts, *loop_number_loop_ends;
87
88 /* Likewise for the continue insn */
89 static rtx *loop_number_loop_cont;
90
91 /* The first code_label that is reached in every loop iteration.
92    0 when not computed yet, initially const0_rtx if a jump couldn't be
93    followed.
94    Also set to 0 when there is no such label before the NOTE_INSN_LOOP_CONT
95    of this loop, or in verify_dominator, if a jump couldn't be followed.  */
96 static rtx *loop_number_cont_dominator;
97
98 /* For each loop, gives the containing loop number, -1 if none.  */
99
100 int *loop_outer_loop;
101
102 #ifdef HAVE_decrement_and_branch_on_count
103 /* Records whether resource in use by inner loop.  */
104
105 int *loop_used_count_register;
106 #endif  /* HAVE_decrement_and_branch_on_count */
107
108 /* Indexed by loop number, contains a nonzero value if the "loop" isn't
109    really a loop (an insn outside the loop branches into it).  */
110
111 static char *loop_invalid;
112
113 /* Indexed by loop number, links together all LABEL_REFs which refer to
114    code labels outside the loop.  Used by routines that need to know all
115    loop exits, such as final_biv_value and final_giv_value.
116
117    This does not include loop exits due to return instructions.  This is
118    because all bivs and givs are pseudos, and hence must be dead after a
119    return, so the presense of a return does not affect any of the
120    optimizations that use this info.  It is simpler to just not include return
121    instructions on this list.  */
122
123 rtx *loop_number_exit_labels;
124
125 /* Indexed by loop number, counts the number of LABEL_REFs on
126    loop_number_exit_labels for this loop and all loops nested inside it.  */
127
128 int *loop_number_exit_count;
129
130 /* Indexed by register number, contains the number of times the reg
131    is set during the loop being scanned.
132    During code motion, a negative value indicates a reg that has been
133    made a candidate; in particular -2 means that it is an candidate that
134    we know is equal to a constant and -1 means that it is an candidate
135    not known equal to a constant.
136    After code motion, regs moved have 0 (which is accurate now)
137    while the failed candidates have the original number of times set.
138
139    Therefore, at all times, == 0 indicates an invariant register;
140    < 0 a conditionally invariant one.  */
141
142 static varray_type set_in_loop;
143
144 /* Original value of set_in_loop; same except that this value
145    is not set negative for a reg whose sets have been made candidates
146    and not set to 0 for a reg that is moved.  */
147
148 static varray_type n_times_set;
149
150 /* Index by register number, 1 indicates that the register
151    cannot be moved or strength reduced.  */
152
153 static varray_type may_not_optimize;
154
155 /* Contains the insn in which a register was used if it was used
156    exactly once; contains const0_rtx if it was used more than once.  */
157
158 static varray_type reg_single_usage;
159
160 /* Nonzero means reg N has already been moved out of one loop.
161    This reduces the desire to move it out of another.  */
162
163 static char *moved_once;
164
165 /* List of MEMs that are stored in this loop.  */
166
167 static rtx loop_store_mems;
168
169 /* The insn where the first of these was found.  */
170 static rtx first_loop_store_insn;
171
172 typedef struct loop_mem_info {
173   rtx mem;      /* The MEM itself.  */
174   rtx reg;      /* Corresponding pseudo, if any.  */
175   int optimize; /* Nonzero if we can optimize access to this MEM.  */
176 } loop_mem_info;
177
178 /* Array of MEMs that are used (read or written) in this loop, but
179    cannot be aliased by anything in this loop, except perhaps
180    themselves.  In other words, if loop_mems[i] is altered during the
181    loop, it is altered by an expression that is rtx_equal_p to it.  */
182
183 static loop_mem_info *loop_mems;
184
185 /* The index of the next available slot in LOOP_MEMS.  */
186
187 static int loop_mems_idx;
188
189 /* The number of elements allocated in LOOP_MEMs.  */
190
191 static int loop_mems_allocated;
192
193 /* Nonzero if we don't know what MEMs were changed in the current
194    loop.  This happens if the loop contains a call (in which case
195    `loop_info->has_call' will also be set) or if we store into more
196    than NUM_STORES MEMs.  */
197
198 static int unknown_address_altered;
199
200 /* Count of movable (i.e. invariant) instructions discovered in the loop.  */
201 static int num_movables;
202
203 /* Count of memory write instructions discovered in the loop.  */
204 static int num_mem_sets;
205
206 /* Bound on pseudo register number before loop optimization.
207    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
208 int max_reg_before_loop;
209
210 /* This obstack is used in product_cheap_p to allocate its rtl.  It
211    may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
212    If we used the same obstack that it did, we would be deallocating
213    that array.  */
214
215 static struct obstack temp_obstack;
216
217 /* This is where the pointer to the obstack being used for RTL is stored.  */
218
219 extern struct obstack *rtl_obstack;
220
221 #define obstack_chunk_alloc xmalloc
222 #define obstack_chunk_free free
223 \f
224 /* During the analysis of a loop, a chain of `struct movable's
225    is made to record all the movable insns found.
226    Then the entire chain can be scanned to decide which to move.  */
227
228 struct movable
229 {
230   rtx insn;                     /* A movable insn */
231   rtx set_src;                  /* The expression this reg is set from.  */
232   rtx set_dest;                 /* The destination of this SET.  */
233   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
234                                    of any registers used within the LIBCALL.  */
235   int consec;                   /* Number of consecutive following insns 
236                                    that must be moved with this one.  */
237   int regno;                    /* The register it sets */
238   short lifetime;               /* lifetime of that register;
239                                    may be adjusted when matching movables
240                                    that load the same value are found.  */
241   short savings;                /* Number of insns we can move for this reg,
242                                    including other movables that force this
243                                    or match this one.  */
244   unsigned int cond : 1;        /* 1 if only conditionally movable */
245   unsigned int force : 1;       /* 1 means MUST move this insn */
246   unsigned int global : 1;      /* 1 means reg is live outside this loop */
247                 /* If PARTIAL is 1, GLOBAL means something different:
248                    that the reg is live outside the range from where it is set
249                    to the following label.  */
250   unsigned int done : 1;        /* 1 inhibits further processing of this */
251   
252   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
253                                    In particular, moving it does not make it
254                                    invariant.  */
255   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
256                                    load SRC, rather than copying INSN.  */
257   unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
258                                     first insn of a consecutive sets group.  */
259   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN.  */
260   enum machine_mode savemode;   /* Nonzero means it is a mode for a low part
261                                    that we should avoid changing when clearing
262                                    the rest of the reg.  */
263   struct movable *match;        /* First entry for same value */
264   struct movable *forces;       /* An insn that must be moved if this is */
265   struct movable *next;
266 };
267
268 static struct movable *the_movables;
269
270 FILE *loop_dump_stream;
271
272 /* For communicating return values from note_set_pseudo_multiple_uses.  */
273 static int note_set_pseudo_multiple_uses_retval;
274
275 /* Forward declarations.  */
276
277 static void verify_dominator PROTO((int));
278 static void find_and_verify_loops PROTO((rtx));
279 static void mark_loop_jump PROTO((rtx, int));
280 static void prescan_loop PROTO((rtx, rtx, struct loop_info *));
281 static int reg_in_basic_block_p PROTO((rtx, rtx));
282 static int consec_sets_invariant_p PROTO((rtx, int, rtx));
283 static int labels_in_range_p PROTO((rtx, int));
284 static void count_one_set PROTO((rtx, rtx, varray_type, rtx *));
285
286 static void count_loop_regs_set PROTO((rtx, rtx, varray_type, varray_type,
287                                        int *, int)); 
288 static void note_addr_stored PROTO((rtx, rtx));
289 static void note_set_pseudo_multiple_uses PROTO((rtx, rtx));
290 static int loop_reg_used_before_p PROTO((rtx, rtx, rtx, rtx, rtx));
291 static void scan_loop PROTO((rtx, rtx, rtx, int, int));
292 #if 0
293 static void replace_call_address PROTO((rtx, rtx, rtx));
294 #endif
295 static rtx skip_consec_insns PROTO((rtx, int));
296 static int libcall_benefit PROTO((rtx));
297 static void ignore_some_movables PROTO((struct movable *));
298 static void force_movables PROTO((struct movable *));
299 static void combine_movables PROTO((struct movable *, int));
300 static int regs_match_p PROTO((rtx, rtx, struct movable *));
301 static int rtx_equal_for_loop_p PROTO((rtx, rtx, struct movable *));
302 static void add_label_notes PROTO((rtx, rtx));
303 static void move_movables PROTO((struct movable *, int, int, rtx, rtx, int));
304 static int count_nonfixed_reads PROTO((rtx));
305 static void strength_reduce PROTO((rtx, rtx, rtx, int, rtx, rtx, 
306                                    struct loop_info *, rtx, int, int));
307 static void find_single_use_in_loop PROTO((rtx, rtx, varray_type));
308 static int valid_initial_value_p PROTO((rtx, rtx, int, rtx));
309 static void find_mem_givs PROTO((rtx, rtx, int, int, rtx, rtx));
310 static void record_biv PROTO((struct induction *, rtx, rtx, rtx, rtx, rtx *, int, int));
311 static void check_final_value PROTO((struct induction *, rtx, rtx, 
312                                      unsigned HOST_WIDE_INT));
313 static void record_giv PROTO((struct induction *, rtx, rtx, rtx, rtx, rtx, int, enum g_types, int, int, rtx *, rtx, rtx));
314 static void update_giv_derive PROTO((rtx));
315 static int basic_induction_var PROTO((rtx, enum machine_mode, rtx, rtx, rtx *, rtx *, rtx **));
316 static rtx simplify_giv_expr PROTO((rtx, int *));
317 static int general_induction_var PROTO((rtx, rtx *, rtx *, rtx *, int, int *));
318 static int consec_sets_giv PROTO((int, rtx, rtx, rtx, rtx *, rtx *, rtx *));
319 static int check_dbra_loop PROTO((rtx, int, rtx, struct loop_info *));
320 static rtx express_from_1 PROTO((rtx, rtx, rtx));
321 static rtx combine_givs_p PROTO((struct induction *, struct induction *));
322 static void combine_givs PROTO((struct iv_class *));
323 struct recombine_givs_stats;
324 static int find_life_end PROTO((rtx, struct recombine_givs_stats *, rtx, rtx));
325 static void recombine_givs PROTO((struct iv_class *, rtx, rtx, int));
326 static int product_cheap_p PROTO((rtx, rtx));
327 static int maybe_eliminate_biv PROTO((struct iv_class *, rtx, rtx, int, int, int));
328 static int maybe_eliminate_biv_1 PROTO((rtx, rtx, struct iv_class *, int, rtx));
329 static int last_use_this_basic_block PROTO((rtx, rtx));
330 static void record_initial PROTO((rtx, rtx));
331 static void update_reg_last_use PROTO((rtx, rtx));
332 static rtx next_insn_in_loop PROTO((rtx, rtx, rtx, rtx));
333 static void load_mems_and_recount_loop_regs_set PROTO((rtx, rtx, rtx,
334                                                        rtx, int *));
335 static void load_mems PROTO((rtx, rtx, rtx, rtx));
336 static int insert_loop_mem PROTO((rtx *, void *));
337 static int replace_loop_mem PROTO((rtx *, void *));
338 static int replace_label PROTO((rtx *, void *));
339
340 typedef struct rtx_and_int {
341   rtx r;
342   int i;
343 } rtx_and_int;
344
345 typedef struct rtx_pair {
346   rtx r1;
347   rtx r2;
348 } rtx_pair;
349
350 /* Nonzero iff INSN is between START and END, inclusive.  */
351 #define INSN_IN_RANGE_P(INSN, START, END)       \
352   (INSN_UID (INSN) < max_uid_for_loop           \
353    && INSN_LUID (INSN) >= INSN_LUID (START)     \
354    && INSN_LUID (INSN) <= INSN_LUID (END))
355
356 #ifdef HAVE_decrement_and_branch_on_count
357 /* Test whether BCT applicable and safe.  */
358 static void insert_bct PROTO((rtx, rtx, struct loop_info *));
359
360 /* Auxiliary function that inserts the BCT pattern into the loop.  */
361 static void instrument_loop_bct PROTO((rtx, rtx, rtx));
362 #endif /* HAVE_decrement_and_branch_on_count */
363
364 /* Indirect_jump_in_function is computed once per function.  */
365 int indirect_jump_in_function = 0;
366 static int indirect_jump_in_function_p PROTO((rtx));
367
368 static int compute_luids PROTO((rtx, rtx, int));
369
370 static int biv_elimination_giv_has_0_offset PROTO((struct induction *,
371                                                    struct induction *, rtx));
372 \f
373 /* Relative gain of eliminating various kinds of operations.  */
374 static int add_cost;
375 #if 0
376 static int shift_cost;
377 static int mult_cost;
378 #endif
379
380 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
381    copy the value of the strength reduced giv to its original register.  */
382 static int copy_cost;
383
384 /* Cost of using a register, to normalize the benefits of a giv.  */
385 static int reg_address_cost;
386
387
388 void
389 init_loop ()
390 {
391   char *free_point = (char *) oballoc (1);
392   rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
393
394   add_cost = rtx_cost (gen_rtx_PLUS (word_mode, reg, reg), SET);
395
396 #ifdef ADDRESS_COST
397   reg_address_cost = ADDRESS_COST (reg);
398 #else
399   reg_address_cost = rtx_cost (reg, MEM);
400 #endif
401
402   /* We multiply by 2 to reconcile the difference in scale between
403      these two ways of computing costs.  Otherwise the cost of a copy
404      will be far less than the cost of an add.  */
405
406   copy_cost = 2 * 2;
407
408   /* Free the objects we just allocated.  */
409   obfree (free_point);
410
411   /* Initialize the obstack used for rtl in product_cheap_p.  */
412   gcc_obstack_init (&temp_obstack);
413 }
414 \f
415 /* Compute the mapping from uids to luids.
416    LUIDs are numbers assigned to insns, like uids,
417    except that luids increase monotonically through the code.
418    Start at insn START and stop just before END.  Assign LUIDs
419    starting with PREV_LUID + 1.  Return the last assigned LUID + 1.  */
420 static int
421 compute_luids (start, end, prev_luid)
422      rtx start, end;
423      int prev_luid;
424 {
425   int i;
426   rtx insn;
427
428   for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
429     {
430       if (INSN_UID (insn) >= max_uid_for_loop)
431         continue;
432       /* Don't assign luids to line-number NOTEs, so that the distance in
433          luids between two insns is not affected by -g.  */
434       if (GET_CODE (insn) != NOTE
435           || NOTE_LINE_NUMBER (insn) <= 0)
436         uid_luid[INSN_UID (insn)] = ++i;
437       else
438         /* Give a line number note the same luid as preceding insn.  */
439         uid_luid[INSN_UID (insn)] = i;
440     }
441   return i + 1;
442 }
443 \f
444 /* Entry point of this file.  Perform loop optimization
445    on the current function.  F is the first insn of the function
446    and DUMPFILE is a stream for output of a trace of actions taken
447    (or 0 if none should be output).  */
448
449 void
450 loop_optimize (f, dumpfile, unroll_p, bct_p)
451      /* f is the first instruction of a chain of insns for one function */
452      rtx f;
453      FILE *dumpfile;
454      int unroll_p, bct_p;
455 {
456   register rtx insn;
457   register int i;
458
459   loop_dump_stream = dumpfile;
460
461   init_recog_no_volatile ();
462
463   max_reg_before_loop = max_reg_num ();
464
465   moved_once = (char *) alloca (max_reg_before_loop);
466   bzero (moved_once, max_reg_before_loop);
467
468   regs_may_share = 0;
469
470   /* Count the number of loops.  */
471
472   max_loop_num = 0;
473   for (insn = f; insn; insn = NEXT_INSN (insn))
474     {
475       if (GET_CODE (insn) == NOTE
476           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
477         max_loop_num++;
478     }
479
480   /* Don't waste time if no loops.  */
481   if (max_loop_num == 0)
482     return;
483
484   /* Get size to use for tables indexed by uids.
485      Leave some space for labels allocated by find_and_verify_loops.  */
486   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
487
488   uid_luid = (int *) alloca (max_uid_for_loop * sizeof (int));
489   uid_loop_num = (int *) alloca (max_uid_for_loop * sizeof (int));
490
491   bzero ((char *) uid_luid, max_uid_for_loop * sizeof (int));
492   bzero ((char *) uid_loop_num, max_uid_for_loop * sizeof (int));
493
494   /* Allocate tables for recording each loop.  We set each entry, so they need
495      not be zeroed.  */
496   loop_number_loop_starts = (rtx *) alloca (max_loop_num * sizeof (rtx));
497   loop_number_loop_ends = (rtx *) alloca (max_loop_num * sizeof (rtx));
498   loop_number_loop_cont = (rtx *) alloca (max_loop_num * sizeof (rtx));
499   loop_number_cont_dominator = (rtx *) alloca (max_loop_num * sizeof (rtx));
500   loop_outer_loop = (int *) alloca (max_loop_num * sizeof (int));
501   loop_invalid = (char *) alloca (max_loop_num * sizeof (char));
502   loop_number_exit_labels = (rtx *) alloca (max_loop_num * sizeof (rtx));
503   loop_number_exit_count = (int *) alloca (max_loop_num * sizeof (int));
504
505 #ifdef HAVE_decrement_and_branch_on_count
506   /* Allocate for BCT optimization */
507   loop_used_count_register = (int *) alloca (max_loop_num * sizeof (int));
508   bzero ((char *) loop_used_count_register, max_loop_num * sizeof (int));
509 #endif  /* HAVE_decrement_and_branch_on_count */
510
511   /* Find and process each loop.
512      First, find them, and record them in order of their beginnings.  */
513   find_and_verify_loops (f);
514
515   /* Now find all register lifetimes.  This must be done after
516      find_and_verify_loops, because it might reorder the insns in the
517      function.  */
518   reg_scan (f, max_reg_num (), 1);
519
520   /* This must occur after reg_scan so that registers created by gcse
521      will have entries in the register tables.
522
523      We could have added a call to reg_scan after gcse_main in toplev.c,
524      but moving this call to init_alias_analysis is more efficient.  */
525   init_alias_analysis ();
526
527   /* See if we went too far.  Note that get_max_uid already returns
528      one more that the maximum uid of all insn.  */
529   if (get_max_uid () > max_uid_for_loop)
530     abort ();
531   /* Now reset it to the actual size we need.  See above.  */
532   max_uid_for_loop = get_max_uid ();
533
534   /* find_and_verify_loops has already called compute_luids, but it might
535      have rearranged code afterwards, so we need to recompute the luids now.  */
536   max_luid = compute_luids (f, NULL_RTX, 0);
537
538   /* Don't leave gaps in uid_luid for insns that have been
539      deleted.  It is possible that the first or last insn
540      using some register has been deleted by cross-jumping.
541      Make sure that uid_luid for that former insn's uid
542      points to the general area where that insn used to be.  */
543   for (i = 0; i < max_uid_for_loop; i++)
544     {
545       uid_luid[0] = uid_luid[i];
546       if (uid_luid[0] != 0)
547         break;
548     }
549   for (i = 0; i < max_uid_for_loop; i++)
550     if (uid_luid[i] == 0)
551       uid_luid[i] = uid_luid[i - 1];
552
553   /* Create a mapping from loops to BLOCK tree nodes.  */
554   if (unroll_p && write_symbols != NO_DEBUG)
555     find_loop_tree_blocks ();
556
557   /* Determine if the function has indirect jump.  On some systems
558      this prevents low overhead loop instructions from being used.  */
559   indirect_jump_in_function = indirect_jump_in_function_p (f);
560
561   /* Now scan the loops, last ones first, since this means inner ones are done
562      before outer ones.  */
563   for (i = max_loop_num-1; i >= 0; i--)
564     if (! loop_invalid[i] && loop_number_loop_ends[i])
565       scan_loop (loop_number_loop_starts[i], loop_number_loop_ends[i],
566                  loop_number_loop_cont[i], unroll_p, bct_p);
567
568   /* If debugging and unrolling loops, we must replicate the tree nodes
569      corresponding to the blocks inside the loop, so that the original one
570      to one mapping will remain.  */
571   if (unroll_p && write_symbols != NO_DEBUG)
572     unroll_block_trees ();
573
574   end_alias_analysis ();
575 }
576 \f
577 /* Returns the next insn, in execution order, after INSN.  START and
578    END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
579    respectively.  LOOP_TOP, if non-NULL, is the top of the loop in the
580    insn-stream; it is used with loops that are entered near the
581    bottom.  */
582
583 static rtx
584 next_insn_in_loop (insn, start, end, loop_top)
585      rtx insn;
586      rtx start;
587      rtx end;
588      rtx loop_top;
589 {
590   insn = NEXT_INSN (insn);
591
592   if (insn == end)
593     {
594       if (loop_top)
595         /* Go to the top of the loop, and continue there.  */
596         insn = loop_top;
597       else
598         /* We're done.  */
599         insn = NULL_RTX;
600     }
601
602   if (insn == start)
603     /* We're done.  */
604     insn = NULL_RTX;
605
606   return insn;
607 }
608
609 /* Optimize one loop whose start is LOOP_START and end is END.
610    LOOP_START is the NOTE_INSN_LOOP_BEG and END is the matching
611    NOTE_INSN_LOOP_END.
612    LOOP_CONT is the NOTE_INSN_LOOP_CONT.  */
613
614 /* ??? Could also move memory writes out of loops if the destination address
615    is invariant, the source is invariant, the memory write is not volatile,
616    and if we can prove that no read inside the loop can read this address
617    before the write occurs.  If there is a read of this address after the
618    write, then we can also mark the memory read as invariant.  */
619
620 static void
621 scan_loop (loop_start, end, loop_cont, unroll_p, bct_p)
622      rtx loop_start, end, loop_cont;
623      int unroll_p, bct_p;
624 {
625   register int i;
626   rtx p;
627   /* 1 if we are scanning insns that could be executed zero times.  */
628   int maybe_never = 0;
629   /* 1 if we are scanning insns that might never be executed
630      due to a subroutine call which might exit before they are reached.  */
631   int call_passed = 0;
632   /* For a rotated loop that is entered near the bottom,
633      this is the label at the top.  Otherwise it is zero.  */
634   rtx loop_top = 0;
635   /* Jump insn that enters the loop, or 0 if control drops in.  */
636   rtx loop_entry_jump = 0;
637   /* Place in the loop where control enters.  */
638   rtx scan_start;
639   /* Number of insns in the loop.  */
640   int insn_count;
641   int in_libcall = 0;
642   int tem;
643   rtx temp;
644   /* The SET from an insn, if it is the only SET in the insn.  */
645   rtx set, set1;
646   /* Chain describing insns movable in current loop.  */
647   struct movable *movables = 0;
648   /* Last element in `movables' -- so we can add elements at the end.  */
649   struct movable *last_movable = 0;
650   /* Ratio of extra register life span we can justify
651      for saving an instruction.  More if loop doesn't call subroutines
652      since in that case saving an insn makes more difference
653      and more registers are available.  */
654   int threshold;
655   /* Nonzero if we are scanning instructions in a sub-loop.  */
656   int loop_depth = 0;
657   int nregs;
658   struct loop_info *loop_info = &this_loop_info;
659
660   /* Determine whether this loop starts with a jump down to a test at
661      the end.  This will occur for a small number of loops with a test
662      that is too complex to duplicate in front of the loop.
663
664      We search for the first insn or label in the loop, skipping NOTEs.
665      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
666      (because we might have a loop executed only once that contains a
667      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
668      (in case we have a degenerate loop).
669
670      Note that if we mistakenly think that a loop is entered at the top
671      when, in fact, it is entered at the exit test, the only effect will be
672      slightly poorer optimization.  Making the opposite error can generate
673      incorrect code.  Since very few loops now start with a jump to the 
674      exit test, the code here to detect that case is very conservative.  */
675
676   for (p = NEXT_INSN (loop_start);
677        p != end
678          && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
679          && (GET_CODE (p) != NOTE
680              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
681                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
682        p = NEXT_INSN (p))
683     ;
684
685   scan_start = p;
686
687   /* Set up variables describing this loop.  */
688   prescan_loop (loop_start, end, loop_info);
689   threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
690
691   /* If loop has a jump before the first label,
692      the true entry is the target of that jump.
693      Start scan from there.
694      But record in LOOP_TOP the place where the end-test jumps
695      back to so we can scan that after the end of the loop.  */
696   if (GET_CODE (p) == JUMP_INSN)
697     {
698       loop_entry_jump = p;
699
700       /* Loop entry must be unconditional jump (and not a RETURN)  */
701       if (simplejump_p (p)
702           && JUMP_LABEL (p) != 0
703           /* Check to see whether the jump actually
704              jumps out of the loop (meaning it's no loop).
705              This case can happen for things like
706              do {..} while (0).  If this label was generated previously
707              by loop, we can't tell anything about it and have to reject
708              the loop.  */
709           && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, end))
710         {
711           loop_top = next_label (scan_start);
712           scan_start = JUMP_LABEL (p);
713         }
714     }
715
716   /* If SCAN_START was an insn created by loop, we don't know its luid
717      as required by loop_reg_used_before_p.  So skip such loops.  (This
718      test may never be true, but it's best to play it safe.) 
719
720      Also, skip loops where we do not start scanning at a label.  This
721      test also rejects loops starting with a JUMP_INSN that failed the
722      test above.  */
723
724   if (INSN_UID (scan_start) >= max_uid_for_loop
725       || GET_CODE (scan_start) != CODE_LABEL)
726     {
727       if (loop_dump_stream)
728         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
729                  INSN_UID (loop_start), INSN_UID (end));
730       return;
731     }
732
733   /* Count number of times each reg is set during this loop.
734      Set VARRAY_CHAR (may_not_optimize, I) if it is not safe to move out
735      the setting of register I.  Set VARRAY_RTX (reg_single_usage, I).  */
736   
737   /* Allocate extra space for REGS that might be created by
738      load_mems.  We allocate a little extra slop as well, in the hopes
739      that even after the moving of movables creates some new registers
740      we won't have to reallocate these arrays.  However, we do grow
741      the arrays, if necessary, in load_mems_recount_loop_regs_set.  */
742   nregs = max_reg_num () + loop_mems_idx + 16;
743   VARRAY_INT_INIT (set_in_loop, nregs, "set_in_loop");
744   VARRAY_INT_INIT (n_times_set, nregs, "n_times_set");
745   VARRAY_CHAR_INIT (may_not_optimize, nregs, "may_not_optimize");
746   VARRAY_RTX_INIT (reg_single_usage, nregs, "reg_single_usage");
747
748   count_loop_regs_set (loop_top ? loop_top : loop_start, end,
749                        may_not_optimize, reg_single_usage, &insn_count, nregs);
750
751   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
752     {
753       VARRAY_CHAR (may_not_optimize, i) = 1;
754       VARRAY_INT (set_in_loop, i) = 1;
755     }
756
757 #ifdef AVOID_CCMODE_COPIES
758   /* Don't try to move insns which set CC registers if we should not
759      create CCmode register copies.  */
760   for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
761     if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
762       VARRAY_CHAR (may_not_optimize, i) = 1;
763 #endif
764
765   bcopy ((char *) &set_in_loop->data, 
766          (char *) &n_times_set->data, nregs * sizeof (int));
767
768   if (loop_dump_stream)
769     {
770       fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
771                INSN_UID (loop_start), INSN_UID (end), insn_count);
772       if (loop_info->cont)
773         fprintf (loop_dump_stream, "Continue at insn %d.\n",
774                  INSN_UID (loop_info->cont));
775     }
776
777   /* Scan through the loop finding insns that are safe to move.
778      Set set_in_loop negative for the reg being set, so that
779      this reg will be considered invariant for subsequent insns.
780      We consider whether subsequent insns use the reg
781      in deciding whether it is worth actually moving.
782
783      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
784      and therefore it is possible that the insns we are scanning
785      would never be executed.  At such times, we must make sure
786      that it is safe to execute the insn once instead of zero times.
787      When MAYBE_NEVER is 0, all insns will be executed at least once
788      so that is not a problem.  */
789
790   for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top); 
791        p != NULL_RTX;
792        p = next_insn_in_loop (p, scan_start, end, loop_top))
793     {
794       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
795           && find_reg_note (p, REG_LIBCALL, NULL_RTX))
796         in_libcall = 1;
797       else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
798                && find_reg_note (p, REG_RETVAL, NULL_RTX))
799         in_libcall = 0;
800
801       if (GET_CODE (p) == INSN
802           && (set = single_set (p))
803           && GET_CODE (SET_DEST (set)) == REG
804           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
805         {
806           int tem1 = 0;
807           int tem2 = 0;
808           int move_insn = 0;
809           rtx src = SET_SRC (set);
810           rtx dependencies = 0;
811
812           /* Figure out what to use as a source of this insn.  If a REG_EQUIV
813              note is given or if a REG_EQUAL note with a constant operand is
814              specified, use it as the source and mark that we should move
815              this insn by calling emit_move_insn rather that duplicating the
816              insn.
817
818              Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
819              is present.  */
820           temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
821           if (temp)
822             src = XEXP (temp, 0), move_insn = 1;
823           else 
824             {
825               temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
826               if (temp && CONSTANT_P (XEXP (temp, 0)))
827                 src = XEXP (temp, 0), move_insn = 1;
828               if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
829                 {
830                   src = XEXP (temp, 0);
831                   /* A libcall block can use regs that don't appear in
832                      the equivalent expression.  To move the libcall,
833                      we must move those regs too.  */
834                   dependencies = libcall_other_reg (p, src);
835                 }
836             }
837
838           /* Don't try to optimize a register that was made
839              by loop-optimization for an inner loop.
840              We don't know its life-span, so we can't compute the benefit.  */
841           if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
842             ;
843           else if (/* The register is used in basic blocks other
844                       than the one where it is set (meaning that
845                       something after this point in the loop might
846                       depend on its value before the set).  */
847                    ! reg_in_basic_block_p (p, SET_DEST (set))
848                    /* And the set is not guaranteed to be executed one
849                       the loop starts, or the value before the set is
850                       needed before the set occurs... 
851
852                       ??? Note we have quadratic behaviour here, mitigated
853                       by the fact that the previous test will often fail for
854                       large loops.  Rather than re-scanning the entire loop
855                       each time for register usage, we should build tables
856                       of the register usage and use them here instead.  */
857                    && (maybe_never
858                        || loop_reg_used_before_p (set, p, loop_start,
859                                                   scan_start, end)))
860             /* It is unsafe to move the set.  
861
862                This code used to consider it OK to move a set of a variable
863                which was not created by the user and not used in an exit test.
864                That behavior is incorrect and was removed.  */
865             ;
866           else if ((tem = invariant_p (src))
867                    && (dependencies == 0
868                        || (tem2 = invariant_p (dependencies)) != 0)
869                    && (VARRAY_INT (set_in_loop, 
870                                    REGNO (SET_DEST (set))) == 1
871                        || (tem1
872                            = consec_sets_invariant_p 
873                            (SET_DEST (set),
874                             VARRAY_INT (set_in_loop, REGNO (SET_DEST (set))),
875                             p)))
876                    /* If the insn can cause a trap (such as divide by zero),
877                       can't move it unless it's guaranteed to be executed
878                       once loop is entered.  Even a function call might
879                       prevent the trap insn from being reached
880                       (since it might exit!)  */
881                    && ! ((maybe_never || call_passed)
882                          && may_trap_p (src)))
883             {
884               register struct movable *m;
885               register int regno = REGNO (SET_DEST (set));
886
887               /* A potential lossage is where we have a case where two insns
888                  can be combined as long as they are both in the loop, but
889                  we move one of them outside the loop.  For large loops,
890                  this can lose.  The most common case of this is the address
891                  of a function being called.  
892
893                  Therefore, if this register is marked as being used exactly
894                  once if we are in a loop with calls (a "large loop"), see if
895                  we can replace the usage of this register with the source
896                  of this SET.  If we can, delete this insn. 
897
898                  Don't do this if P has a REG_RETVAL note or if we have
899                  SMALL_REGISTER_CLASSES and SET_SRC is a hard register.  */
900
901               if (loop_info->has_call
902                   && VARRAY_RTX (reg_single_usage, regno) != 0
903                   && VARRAY_RTX (reg_single_usage, regno) != const0_rtx
904                   && REGNO_FIRST_UID (regno) == INSN_UID (p)
905                   && (REGNO_LAST_UID (regno)
906                       == INSN_UID (VARRAY_RTX (reg_single_usage, regno)))
907                   && VARRAY_INT (set_in_loop, regno) == 1
908                   && ! side_effects_p (SET_SRC (set))
909                   && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
910                   && (! SMALL_REGISTER_CLASSES
911                       || (! (GET_CODE (SET_SRC (set)) == REG
912                              && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)))
913                   /* This test is not redundant; SET_SRC (set) might be
914                      a call-clobbered register and the life of REGNO
915                      might span a call.  */
916                   && ! modified_between_p (SET_SRC (set), p,
917                                            VARRAY_RTX
918                                            (reg_single_usage, regno)) 
919                   && no_labels_between_p (p, VARRAY_RTX (reg_single_usage, regno))
920                   && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
921                                            VARRAY_RTX
922                                            (reg_single_usage, regno))) 
923                 {
924                   /* Replace any usage in a REG_EQUAL note.  Must copy the
925                      new source, so that we don't get rtx sharing between the
926                      SET_SOURCE and REG_NOTES of insn p.  */
927                   REG_NOTES (VARRAY_RTX (reg_single_usage, regno))
928                     = replace_rtx (REG_NOTES (VARRAY_RTX
929                                               (reg_single_usage, regno)), 
930                                    SET_DEST (set), copy_rtx (SET_SRC (set)));
931                                    
932                   PUT_CODE (p, NOTE);
933                   NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
934                   NOTE_SOURCE_FILE (p) = 0;
935                   VARRAY_INT (set_in_loop, regno) = 0;
936                   continue;
937                 }
938
939               m = (struct movable *) alloca (sizeof (struct movable));
940               m->next = 0;
941               m->insn = p;
942               m->set_src = src;
943               m->dependencies = dependencies;
944               m->set_dest = SET_DEST (set);
945               m->force = 0;
946               m->consec = VARRAY_INT (set_in_loop, 
947                                       REGNO (SET_DEST (set))) - 1;
948               m->done = 0;
949               m->forces = 0;
950               m->partial = 0;
951               m->move_insn = move_insn;
952               m->move_insn_first = 0;
953               m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
954               m->savemode = VOIDmode;
955               m->regno = regno;
956               /* Set M->cond if either invariant_p or consec_sets_invariant_p
957                  returned 2 (only conditionally invariant).  */
958               m->cond = ((tem | tem1 | tem2) > 1);
959               m->global = (uid_luid[REGNO_LAST_UID (regno)] > INSN_LUID (end)
960                            || uid_luid[REGNO_FIRST_UID (regno)] < INSN_LUID (loop_start));
961               m->match = 0;
962               m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
963                              - uid_luid[REGNO_FIRST_UID (regno)]);
964               m->savings = VARRAY_INT (n_times_set, regno);
965               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
966                 m->savings += libcall_benefit (p);
967               VARRAY_INT (set_in_loop, regno) = move_insn ? -2 : -1;
968               /* Add M to the end of the chain MOVABLES.  */
969               if (movables == 0)
970                 movables = m;
971               else
972                 last_movable->next = m;
973               last_movable = m;
974
975               if (m->consec > 0)
976                 {
977                   /* It is possible for the first instruction to have a
978                      REG_EQUAL note but a non-invariant SET_SRC, so we must
979                      remember the status of the first instruction in case
980                      the last instruction doesn't have a REG_EQUAL note.  */
981                   m->move_insn_first = m->move_insn;
982
983                   /* Skip this insn, not checking REG_LIBCALL notes.  */
984                   p = next_nonnote_insn (p);
985                   /* Skip the consecutive insns, if there are any.  */
986                   p = skip_consec_insns (p, m->consec);
987                   /* Back up to the last insn of the consecutive group.  */
988                   p = prev_nonnote_insn (p);
989
990                   /* We must now reset m->move_insn, m->is_equiv, and possibly
991                      m->set_src to correspond to the effects of all the
992                      insns.  */
993                   temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
994                   if (temp)
995                     m->set_src = XEXP (temp, 0), m->move_insn = 1;
996                   else
997                     {
998                       temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
999                       if (temp && CONSTANT_P (XEXP (temp, 0)))
1000                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
1001                       else
1002                         m->move_insn = 0;
1003
1004                     }
1005                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1006                 }
1007             }
1008           /* If this register is always set within a STRICT_LOW_PART
1009              or set to zero, then its high bytes are constant.
1010              So clear them outside the loop and within the loop
1011              just load the low bytes.
1012              We must check that the machine has an instruction to do so.
1013              Also, if the value loaded into the register
1014              depends on the same register, this cannot be done.  */
1015           else if (SET_SRC (set) == const0_rtx
1016                    && GET_CODE (NEXT_INSN (p)) == INSN
1017                    && (set1 = single_set (NEXT_INSN (p)))
1018                    && GET_CODE (set1) == SET
1019                    && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1020                    && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1021                    && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1022                        == SET_DEST (set))
1023                    && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1024             {
1025               register int regno = REGNO (SET_DEST (set));
1026               if (VARRAY_INT (set_in_loop, regno) == 2)
1027                 {
1028                   register struct movable *m;
1029                   m = (struct movable *) alloca (sizeof (struct movable));
1030                   m->next = 0;
1031                   m->insn = p;
1032                   m->set_dest = SET_DEST (set);
1033                   m->dependencies = 0;
1034                   m->force = 0;
1035                   m->consec = 0;
1036                   m->done = 0;
1037                   m->forces = 0;
1038                   m->move_insn = 0;
1039                   m->move_insn_first = 0;
1040                   m->partial = 1;
1041                   /* If the insn may not be executed on some cycles,
1042                      we can't clear the whole reg; clear just high part.
1043                      Not even if the reg is used only within this loop.
1044                      Consider this:
1045                      while (1)
1046                        while (s != t) {
1047                          if (foo ()) x = *s;
1048                          use (x);
1049                        }
1050                      Clearing x before the inner loop could clobber a value
1051                      being saved from the last time around the outer loop.
1052                      However, if the reg is not used outside this loop
1053                      and all uses of the register are in the same
1054                      basic block as the store, there is no problem.
1055
1056                      If this insn was made by loop, we don't know its
1057                      INSN_LUID and hence must make a conservative
1058                      assumption.  */
1059                   m->global = (INSN_UID (p) >= max_uid_for_loop
1060                                || (uid_luid[REGNO_LAST_UID (regno)]
1061                                    > INSN_LUID (end))
1062                                || (uid_luid[REGNO_FIRST_UID (regno)]
1063                                    < INSN_LUID (p))
1064                                || (labels_in_range_p
1065                                    (p, uid_luid[REGNO_FIRST_UID (regno)])));
1066                   if (maybe_never && m->global)
1067                     m->savemode = GET_MODE (SET_SRC (set1));
1068                   else
1069                     m->savemode = VOIDmode;
1070                   m->regno = regno;
1071                   m->cond = 0;
1072                   m->match = 0;
1073                   m->lifetime = (uid_luid[REGNO_LAST_UID (regno)]
1074                                  - uid_luid[REGNO_FIRST_UID (regno)]);
1075                   m->savings = 1;
1076                   VARRAY_INT (set_in_loop, regno) = -1;
1077                   /* Add M to the end of the chain MOVABLES.  */
1078                   if (movables == 0)
1079                     movables = m;
1080                   else
1081                     last_movable->next = m;
1082                   last_movable = m;
1083                 }
1084             }
1085         }
1086       /* Past a call insn, we get to insns which might not be executed
1087          because the call might exit.  This matters for insns that trap.
1088          Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
1089          so they don't count.  */
1090       else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
1091         call_passed = 1;
1092       /* Past a label or a jump, we get to insns for which we
1093          can't count on whether or how many times they will be
1094          executed during each iteration.  Therefore, we can
1095          only move out sets of trivial variables
1096          (those not used after the loop).  */
1097       /* Similar code appears twice in strength_reduce.  */
1098       else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1099                /* If we enter the loop in the middle, and scan around to the
1100                   beginning, don't set maybe_never for that.  This must be an
1101                   unconditional jump, otherwise the code at the top of the
1102                   loop might never be executed.  Unconditional jumps are
1103                   followed a by barrier then loop end.  */
1104                && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
1105                      && NEXT_INSN (NEXT_INSN (p)) == end
1106                      && simplejump_p (p)))
1107         maybe_never = 1;
1108       else if (GET_CODE (p) == NOTE)
1109         {
1110           /* At the virtual top of a converted loop, insns are again known to
1111              be executed: logically, the loop begins here even though the exit
1112              code has been duplicated.  */
1113           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1114             maybe_never = call_passed = 0;
1115           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1116             loop_depth++;
1117           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1118             loop_depth--;
1119         }
1120     }
1121
1122   /* If one movable subsumes another, ignore that other.  */
1123
1124   ignore_some_movables (movables);
1125
1126   /* For each movable insn, see if the reg that it loads
1127      leads when it dies right into another conditionally movable insn.
1128      If so, record that the second insn "forces" the first one,
1129      since the second can be moved only if the first is.  */
1130
1131   force_movables (movables);
1132
1133   /* See if there are multiple movable insns that load the same value.
1134      If there are, make all but the first point at the first one
1135      through the `match' field, and add the priorities of them
1136      all together as the priority of the first.  */
1137
1138   combine_movables (movables, nregs);
1139         
1140   /* Now consider each movable insn to decide whether it is worth moving.
1141      Store 0 in set_in_loop for each reg that is moved.
1142
1143      Generally this increases code size, so do not move moveables when
1144      optimizing for code size.  */
1145
1146   if (! optimize_size)
1147     move_movables (movables, threshold,
1148                    insn_count, loop_start, end, nregs);
1149
1150   /* Now candidates that still are negative are those not moved.
1151      Change set_in_loop to indicate that those are not actually invariant.  */
1152   for (i = 0; i < nregs; i++)
1153     if (VARRAY_INT (set_in_loop, i) < 0)
1154       VARRAY_INT (set_in_loop, i) = VARRAY_INT (n_times_set, i);
1155
1156   /* Now that we've moved some things out of the loop, we might be able to
1157      hoist even more memory references.  */
1158   load_mems_and_recount_loop_regs_set (scan_start, end, loop_top,
1159                                        loop_start, &insn_count);
1160
1161   if (flag_strength_reduce)
1162     {
1163       the_movables = movables;
1164       strength_reduce (scan_start, end, loop_top,
1165                        insn_count, loop_start, end,
1166                        loop_info, loop_cont, unroll_p, bct_p);
1167     }
1168
1169   VARRAY_FREE (reg_single_usage);
1170   VARRAY_FREE (set_in_loop);
1171   VARRAY_FREE (n_times_set);
1172   VARRAY_FREE (may_not_optimize);
1173 }
1174 \f
1175 /* Add elements to *OUTPUT to record all the pseudo-regs
1176    mentioned in IN_THIS but not mentioned in NOT_IN_THIS.  */
1177
1178 void
1179 record_excess_regs (in_this, not_in_this, output)
1180      rtx in_this, not_in_this;
1181      rtx *output;
1182 {
1183   enum rtx_code code;
1184   const char *fmt;
1185   int i;
1186
1187   code = GET_CODE (in_this);
1188
1189   switch (code)
1190     {
1191     case PC:
1192     case CC0:
1193     case CONST_INT:
1194     case CONST_DOUBLE:
1195     case CONST:
1196     case SYMBOL_REF:
1197     case LABEL_REF:
1198       return;
1199
1200     case REG:
1201       if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1202           && ! reg_mentioned_p (in_this, not_in_this))
1203         *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1204       return;
1205       
1206     default:
1207       break;
1208     }
1209
1210   fmt = GET_RTX_FORMAT (code);
1211   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1212     {
1213       int j;
1214
1215       switch (fmt[i])
1216         {
1217         case 'E':
1218           for (j = 0; j < XVECLEN (in_this, i); j++)
1219             record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1220           break;
1221
1222         case 'e':
1223           record_excess_regs (XEXP (in_this, i), not_in_this, output);
1224           break;
1225         }
1226     }
1227 }
1228 \f
1229 /* Check what regs are referred to in the libcall block ending with INSN,
1230    aside from those mentioned in the equivalent value.
1231    If there are none, return 0.
1232    If there are one or more, return an EXPR_LIST containing all of them.  */
1233
1234 rtx
1235 libcall_other_reg (insn, equiv)
1236      rtx insn, equiv;
1237 {
1238   rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1239   rtx p = XEXP (note, 0);
1240   rtx output = 0;
1241
1242   /* First, find all the regs used in the libcall block
1243      that are not mentioned as inputs to the result.  */
1244
1245   while (p != insn)
1246     {
1247       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1248           || GET_CODE (p) == CALL_INSN)
1249         record_excess_regs (PATTERN (p), equiv, &output);
1250       p = NEXT_INSN (p);
1251     }
1252
1253   return output;
1254 }
1255 \f
1256 /* Return 1 if all uses of REG
1257    are between INSN and the end of the basic block.  */
1258
1259 static int 
1260 reg_in_basic_block_p (insn, reg)
1261      rtx insn, reg;
1262 {
1263   int regno = REGNO (reg);
1264   rtx p;
1265
1266   if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1267     return 0;
1268
1269   /* Search this basic block for the already recorded last use of the reg.  */
1270   for (p = insn; p; p = NEXT_INSN (p))
1271     {
1272       switch (GET_CODE (p))
1273         {
1274         case NOTE:
1275           break;
1276
1277         case INSN:
1278         case CALL_INSN:
1279           /* Ordinary insn: if this is the last use, we win.  */
1280           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1281             return 1;
1282           break;
1283
1284         case JUMP_INSN:
1285           /* Jump insn: if this is the last use, we win.  */
1286           if (REGNO_LAST_UID (regno) == INSN_UID (p))
1287             return 1;
1288           /* Otherwise, it's the end of the basic block, so we lose.  */
1289           return 0;
1290
1291         case CODE_LABEL:
1292         case BARRIER:
1293           /* It's the end of the basic block, so we lose.  */
1294           return 0;
1295           
1296         default:
1297           break;
1298         }
1299     }
1300
1301   /* The "last use" doesn't follow the "first use"??  */
1302   abort ();
1303 }
1304 \f
1305 /* Compute the benefit of eliminating the insns in the block whose
1306    last insn is LAST.  This may be a group of insns used to compute a
1307    value directly or can contain a library call.  */
1308
1309 static int
1310 libcall_benefit (last)
1311      rtx last;
1312 {
1313   rtx insn;
1314   int benefit = 0;
1315
1316   for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1317        insn != last; insn = NEXT_INSN (insn))
1318     {
1319       if (GET_CODE (insn) == CALL_INSN)
1320         benefit += 10;          /* Assume at least this many insns in a library
1321                                    routine.  */
1322       else if (GET_CODE (insn) == INSN
1323                && GET_CODE (PATTERN (insn)) != USE
1324                && GET_CODE (PATTERN (insn)) != CLOBBER)
1325         benefit++;
1326     }
1327
1328   return benefit;
1329 }
1330 \f
1331 /* Skip COUNT insns from INSN, counting library calls as 1 insn.  */
1332
1333 static rtx
1334 skip_consec_insns (insn, count)
1335      rtx insn;
1336      int count;
1337 {
1338   for (; count > 0; count--)
1339     {
1340       rtx temp;
1341
1342       /* If first insn of libcall sequence, skip to end.  */
1343       /* Do this at start of loop, since INSN is guaranteed to 
1344          be an insn here.  */
1345       if (GET_CODE (insn) != NOTE
1346           && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1347         insn = XEXP (temp, 0);
1348
1349       do insn = NEXT_INSN (insn);
1350       while (GET_CODE (insn) == NOTE);
1351     }
1352
1353   return insn;
1354 }
1355
1356 /* Ignore any movable whose insn falls within a libcall
1357    which is part of another movable.
1358    We make use of the fact that the movable for the libcall value
1359    was made later and so appears later on the chain.  */
1360
1361 static void
1362 ignore_some_movables (movables)
1363      struct movable *movables;
1364 {
1365   register struct movable *m, *m1;
1366
1367   for (m = movables; m; m = m->next)
1368     {
1369       /* Is this a movable for the value of a libcall?  */
1370       rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1371       if (note)
1372         {
1373           rtx insn;
1374           /* Check for earlier movables inside that range,
1375              and mark them invalid.  We cannot use LUIDs here because
1376              insns created by loop.c for prior loops don't have LUIDs.
1377              Rather than reject all such insns from movables, we just
1378              explicitly check each insn in the libcall (since invariant
1379              libcalls aren't that common).  */
1380           for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1381             for (m1 = movables; m1 != m; m1 = m1->next)
1382               if (m1->insn == insn)
1383                 m1->done = 1;
1384         }
1385     }
1386 }         
1387
1388 /* For each movable insn, see if the reg that it loads
1389    leads when it dies right into another conditionally movable insn.
1390    If so, record that the second insn "forces" the first one,
1391    since the second can be moved only if the first is.  */
1392
1393 static void
1394 force_movables (movables)
1395      struct movable *movables;
1396 {
1397   register struct movable *m, *m1;
1398   for (m1 = movables; m1; m1 = m1->next)
1399     /* Omit this if moving just the (SET (REG) 0) of a zero-extend.  */
1400     if (!m1->partial && !m1->done)
1401       {
1402         int regno = m1->regno;
1403         for (m = m1->next; m; m = m->next)
1404           /* ??? Could this be a bug?  What if CSE caused the
1405              register of M1 to be used after this insn?
1406              Since CSE does not update regno_last_uid,
1407              this insn M->insn might not be where it dies.
1408              But very likely this doesn't matter; what matters is
1409              that M's reg is computed from M1's reg.  */
1410           if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1411               && !m->done)
1412             break;
1413         if (m != 0 && m->set_src == m1->set_dest
1414             /* If m->consec, m->set_src isn't valid.  */
1415             && m->consec == 0)
1416           m = 0;
1417
1418         /* Increase the priority of the moving the first insn
1419            since it permits the second to be moved as well.  */
1420         if (m != 0)
1421           {
1422             m->forces = m1;
1423             m1->lifetime += m->lifetime;
1424             m1->savings += m->savings;
1425           }
1426       }
1427 }
1428 \f
1429 /* Find invariant expressions that are equal and can be combined into
1430    one register.  */
1431
1432 static void
1433 combine_movables (movables, nregs)
1434      struct movable *movables;
1435      int nregs;
1436 {
1437   register struct movable *m;
1438   char *matched_regs = (char *) alloca (nregs);
1439   enum machine_mode mode;
1440
1441   /* Regs that are set more than once are not allowed to match
1442      or be matched.  I'm no longer sure why not.  */
1443   /* Perhaps testing m->consec_sets would be more appropriate here?  */
1444
1445   for (m = movables; m; m = m->next)
1446     if (m->match == 0 && VARRAY_INT (n_times_set, m->regno) == 1 && !m->partial)
1447       {
1448         register struct movable *m1;
1449         int regno = m->regno;
1450
1451         bzero (matched_regs, nregs);
1452         matched_regs[regno] = 1;
1453
1454         /* We want later insns to match the first one.  Don't make the first
1455            one match any later ones.  So start this loop at m->next.  */
1456         for (m1 = m->next; m1; m1 = m1->next)
1457           if (m != m1 && m1->match == 0 && VARRAY_INT (n_times_set, m1->regno) == 1
1458               /* A reg used outside the loop mustn't be eliminated.  */
1459               && !m1->global
1460               /* A reg used for zero-extending mustn't be eliminated.  */
1461               && !m1->partial
1462               && (matched_regs[m1->regno]
1463                   ||
1464                   (
1465                    /* Can combine regs with different modes loaded from the
1466                       same constant only if the modes are the same or
1467                       if both are integer modes with M wider or the same
1468                       width as M1.  The check for integer is redundant, but
1469                       safe, since the only case of differing destination
1470                       modes with equal sources is when both sources are
1471                       VOIDmode, i.e., CONST_INT.  */
1472                    (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1473                     || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1474                         && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1475                         && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1476                             >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1477                    /* See if the source of M1 says it matches M.  */
1478                    && ((GET_CODE (m1->set_src) == REG
1479                         && matched_regs[REGNO (m1->set_src)])
1480                        || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1481                                                 movables))))
1482               && ((m->dependencies == m1->dependencies)
1483                   || rtx_equal_p (m->dependencies, m1->dependencies)))
1484             {
1485               m->lifetime += m1->lifetime;
1486               m->savings += m1->savings;
1487               m1->done = 1;
1488               m1->match = m;
1489               matched_regs[m1->regno] = 1;
1490             }
1491       }
1492
1493   /* Now combine the regs used for zero-extension.
1494      This can be done for those not marked `global'
1495      provided their lives don't overlap.  */
1496
1497   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1498        mode = GET_MODE_WIDER_MODE (mode))
1499     {
1500       register struct movable *m0 = 0;
1501
1502       /* Combine all the registers for extension from mode MODE.
1503          Don't combine any that are used outside this loop.  */
1504       for (m = movables; m; m = m->next)
1505         if (m->partial && ! m->global
1506             && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1507           {
1508             register struct movable *m1;
1509             int first = uid_luid[REGNO_FIRST_UID (m->regno)];
1510             int last = uid_luid[REGNO_LAST_UID (m->regno)];
1511
1512             if (m0 == 0)
1513               {
1514                 /* First one: don't check for overlap, just record it.  */
1515                 m0 = m;
1516                   continue;
1517               }
1518
1519             /* Make sure they extend to the same mode.
1520                (Almost always true.)  */
1521             if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1522                 continue;
1523
1524             /* We already have one: check for overlap with those
1525                already combined together.  */
1526             for (m1 = movables; m1 != m; m1 = m1->next)
1527               if (m1 == m0 || (m1->partial && m1->match == m0))
1528                 if (! (uid_luid[REGNO_FIRST_UID (m1->regno)] > last
1529                        || uid_luid[REGNO_LAST_UID (m1->regno)] < first))
1530                   goto overlap;
1531
1532             /* No overlap: we can combine this with the others.  */
1533             m0->lifetime += m->lifetime;
1534             m0->savings += m->savings;
1535             m->done = 1;
1536             m->match = m0;
1537
1538           overlap: ;
1539           }
1540     }
1541 }
1542 \f
1543 /* Return 1 if regs X and Y will become the same if moved.  */
1544
1545 static int
1546 regs_match_p (x, y, movables)
1547      rtx x, y;
1548      struct movable *movables;
1549 {
1550   int xn = REGNO (x);
1551   int yn = REGNO (y);
1552   struct movable *mx, *my;
1553
1554   for (mx = movables; mx; mx = mx->next)
1555     if (mx->regno == xn)
1556       break;
1557
1558   for (my = movables; my; my = my->next)
1559     if (my->regno == yn)
1560       break;
1561
1562   return (mx && my
1563           && ((mx->match == my->match && mx->match != 0)
1564               || mx->match == my
1565               || mx == my->match));
1566 }
1567
1568 /* Return 1 if X and Y are identical-looking rtx's.
1569    This is the Lisp function EQUAL for rtx arguments.
1570
1571    If two registers are matching movables or a movable register and an
1572    equivalent constant, consider them equal.  */
1573
1574 static int
1575 rtx_equal_for_loop_p (x, y, movables)
1576      rtx x, y;
1577      struct movable *movables;
1578 {
1579   register int i;
1580   register int j;
1581   register struct movable *m;
1582   register enum rtx_code code;
1583   register const char *fmt;
1584
1585   if (x == y)
1586     return 1;
1587   if (x == 0 || y == 0)
1588     return 0;
1589
1590   code = GET_CODE (x);
1591
1592   /* If we have a register and a constant, they may sometimes be
1593      equal.  */
1594   if (GET_CODE (x) == REG && VARRAY_INT (set_in_loop, REGNO (x)) == -2
1595       && CONSTANT_P (y))
1596     {
1597       for (m = movables; m; m = m->next)
1598         if (m->move_insn && m->regno == REGNO (x)
1599             && rtx_equal_p (m->set_src, y))
1600           return 1;
1601     }
1602   else if (GET_CODE (y) == REG && VARRAY_INT (set_in_loop, REGNO (y)) == -2
1603            && CONSTANT_P (x))
1604     {
1605       for (m = movables; m; m = m->next)
1606         if (m->move_insn && m->regno == REGNO (y)
1607             && rtx_equal_p (m->set_src, x))
1608           return 1;
1609     }
1610
1611   /* Otherwise, rtx's of different codes cannot be equal.  */
1612   if (code != GET_CODE (y))
1613     return 0;
1614
1615   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1616      (REG:SI x) and (REG:HI x) are NOT equivalent.  */
1617
1618   if (GET_MODE (x) != GET_MODE (y))
1619     return 0;
1620
1621   /* These three types of rtx's can be compared nonrecursively.  */
1622   if (code == REG)
1623     return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1624
1625   if (code == LABEL_REF)
1626     return XEXP (x, 0) == XEXP (y, 0);
1627   if (code == SYMBOL_REF)
1628     return XSTR (x, 0) == XSTR (y, 0);
1629
1630   /* Compare the elements.  If any pair of corresponding elements
1631      fail to match, return 0 for the whole things.  */
1632
1633   fmt = GET_RTX_FORMAT (code);
1634   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1635     {
1636       switch (fmt[i])
1637         {
1638         case 'w':
1639           if (XWINT (x, i) != XWINT (y, i))
1640             return 0;
1641           break;
1642
1643         case 'i':
1644           if (XINT (x, i) != XINT (y, i))
1645             return 0;
1646           break;
1647
1648         case 'E':
1649           /* Two vectors must have the same length.  */
1650           if (XVECLEN (x, i) != XVECLEN (y, i))
1651             return 0;
1652
1653           /* And the corresponding elements must match.  */
1654           for (j = 0; j < XVECLEN (x, i); j++)
1655             if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j), movables) == 0)
1656               return 0;
1657           break;
1658
1659         case 'e':
1660           if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables) == 0)
1661             return 0;
1662           break;
1663
1664         case 's':
1665           if (strcmp (XSTR (x, i), XSTR (y, i)))
1666             return 0;
1667           break;
1668
1669         case 'u':
1670           /* These are just backpointers, so they don't matter.  */
1671           break;
1672
1673         case '0':
1674           break;
1675
1676           /* It is believed that rtx's at this level will never
1677              contain anything but integers and other rtx's,
1678              except for within LABEL_REFs and SYMBOL_REFs.  */
1679         default:
1680           abort ();
1681         }
1682     }
1683   return 1;
1684 }
1685 \f
1686 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1687   insns in INSNS which use the reference.  */
1688
1689 static void
1690 add_label_notes (x, insns)
1691      rtx x;
1692      rtx insns;
1693 {
1694   enum rtx_code code = GET_CODE (x);
1695   int i, j;
1696   const char *fmt;
1697   rtx insn;
1698
1699   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1700     {
1701       /* This code used to ignore labels that referred to dispatch tables to
1702          avoid flow generating (slighly) worse code.
1703
1704          We no longer ignore such label references (see LABEL_REF handling in
1705          mark_jump_label for additional information).  */
1706       for (insn = insns; insn; insn = NEXT_INSN (insn))
1707         if (reg_mentioned_p (XEXP (x, 0), insn))
1708           REG_NOTES (insn) = gen_rtx_EXPR_LIST (REG_LABEL, XEXP (x, 0),
1709                                                 REG_NOTES (insn));
1710     }
1711
1712   fmt = GET_RTX_FORMAT (code);
1713   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1714     {
1715       if (fmt[i] == 'e')
1716         add_label_notes (XEXP (x, i), insns);
1717       else if (fmt[i] == 'E')
1718         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1719           add_label_notes (XVECEXP (x, i, j), insns);
1720     }
1721 }
1722 \f
1723 /* Scan MOVABLES, and move the insns that deserve to be moved.
1724    If two matching movables are combined, replace one reg with the
1725    other throughout.  */
1726
1727 static void
1728 move_movables (movables, threshold, insn_count, loop_start, end, nregs)
1729      struct movable *movables;
1730      int threshold;
1731      int insn_count;
1732      rtx loop_start;
1733      rtx end;
1734      int nregs;
1735 {
1736   rtx new_start = 0;
1737   register struct movable *m;
1738   register rtx p;
1739   /* Map of pseudo-register replacements to handle combining
1740      when we move several insns that load the same value
1741      into different pseudo-registers.  */
1742   rtx *reg_map = (rtx *) alloca (nregs * sizeof (rtx));
1743   char *already_moved = (char *) alloca (nregs);
1744
1745   bzero (already_moved, nregs);
1746   bzero ((char *) reg_map, nregs * sizeof (rtx));
1747
1748   num_movables = 0;
1749
1750   for (m = movables; m; m = m->next)
1751     {
1752       /* Describe this movable insn.  */
1753
1754       if (loop_dump_stream)
1755         {
1756           fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1757                    INSN_UID (m->insn), m->regno, m->lifetime);
1758           if (m->consec > 0)
1759             fprintf (loop_dump_stream, "consec %d, ", m->consec);
1760           if (m->cond)
1761             fprintf (loop_dump_stream, "cond ");
1762           if (m->force)
1763             fprintf (loop_dump_stream, "force ");
1764           if (m->global)
1765             fprintf (loop_dump_stream, "global ");
1766           if (m->done)
1767             fprintf (loop_dump_stream, "done ");
1768           if (m->move_insn)
1769             fprintf (loop_dump_stream, "move-insn ");
1770           if (m->match)
1771             fprintf (loop_dump_stream, "matches %d ",
1772                      INSN_UID (m->match->insn));
1773           if (m->forces)
1774             fprintf (loop_dump_stream, "forces %d ",
1775                      INSN_UID (m->forces->insn));
1776         }
1777
1778       /* Count movables.  Value used in heuristics in strength_reduce.  */
1779       num_movables++;
1780
1781       /* Ignore the insn if it's already done (it matched something else).
1782          Otherwise, see if it is now safe to move.  */
1783
1784       if (!m->done
1785           && (! m->cond
1786               || (1 == invariant_p (m->set_src)
1787                   && (m->dependencies == 0
1788                       || 1 == invariant_p (m->dependencies))
1789                   && (m->consec == 0
1790                       || 1 == consec_sets_invariant_p (m->set_dest,
1791                                                        m->consec + 1,
1792                                                        m->insn))))
1793           && (! m->forces || m->forces->done))
1794         {
1795           register int regno;
1796           register rtx p;
1797           int savings = m->savings;
1798
1799           /* We have an insn that is safe to move.
1800              Compute its desirability.  */
1801
1802           p = m->insn;
1803           regno = m->regno;
1804
1805           if (loop_dump_stream)
1806             fprintf (loop_dump_stream, "savings %d ", savings);
1807
1808           if (moved_once[regno] && loop_dump_stream)
1809             fprintf (loop_dump_stream, "halved since already moved ");
1810
1811           /* An insn MUST be moved if we already moved something else
1812              which is safe only if this one is moved too: that is,
1813              if already_moved[REGNO] is nonzero.  */
1814
1815           /* An insn is desirable to move if the new lifetime of the
1816              register is no more than THRESHOLD times the old lifetime.
1817              If it's not desirable, it means the loop is so big
1818              that moving won't speed things up much,
1819              and it is liable to make register usage worse.  */
1820
1821           /* It is also desirable to move if it can be moved at no
1822              extra cost because something else was already moved.  */
1823
1824           if (already_moved[regno]
1825               || flag_move_all_movables
1826               || (threshold * savings * m->lifetime) >=
1827                  (moved_once[regno] ? insn_count * 2 : insn_count)
1828               || (m->forces && m->forces->done
1829                   && VARRAY_INT (n_times_set, m->forces->regno) == 1))
1830             {
1831               int count;
1832               register struct movable *m1;
1833               rtx first = NULL_RTX;
1834
1835               /* Now move the insns that set the reg.  */
1836
1837               if (m->partial && m->match)
1838                 {
1839                   rtx newpat, i1;
1840                   rtx r1, r2;
1841                   /* Find the end of this chain of matching regs.
1842                      Thus, we load each reg in the chain from that one reg.
1843                      And that reg is loaded with 0 directly,
1844                      since it has ->match == 0.  */
1845                   for (m1 = m; m1->match; m1 = m1->match);
1846                   newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1847                                           SET_DEST (PATTERN (m1->insn)));
1848                   i1 = emit_insn_before (newpat, loop_start);
1849
1850                   /* Mark the moved, invariant reg as being allowed to
1851                      share a hard reg with the other matching invariant.  */
1852                   REG_NOTES (i1) = REG_NOTES (m->insn);
1853                   r1 = SET_DEST (PATTERN (m->insn));
1854                   r2 = SET_DEST (PATTERN (m1->insn));
1855                   regs_may_share
1856                     = gen_rtx_EXPR_LIST (VOIDmode, r1,
1857                                          gen_rtx_EXPR_LIST (VOIDmode, r2,
1858                                                             regs_may_share));
1859                   delete_insn (m->insn);
1860
1861                   if (new_start == 0)
1862                     new_start = i1;
1863
1864                   if (loop_dump_stream)
1865                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1866                 }
1867               /* If we are to re-generate the item being moved with a
1868                  new move insn, first delete what we have and then emit
1869                  the move insn before the loop.  */
1870               else if (m->move_insn)
1871                 {
1872                   rtx i1, temp;
1873
1874                   for (count = m->consec; count >= 0; count--)
1875                     {
1876                       /* If this is the first insn of a library call sequence,
1877                          skip to the end.  */
1878                       if (GET_CODE (p) != NOTE
1879                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1880                         p = XEXP (temp, 0);
1881
1882                       /* If this is the last insn of a libcall sequence, then
1883                          delete every insn in the sequence except the last.
1884                          The last insn is handled in the normal manner.  */
1885                       if (GET_CODE (p) != NOTE
1886                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1887                         {
1888                           temp = XEXP (temp, 0);
1889                           while (temp != p)
1890                             temp = delete_insn (temp);
1891                         }
1892
1893                       temp = p;
1894                       p = delete_insn (p);
1895
1896                       /* simplify_giv_expr expects that it can walk the insns
1897                          at m->insn forwards and see this old sequence we are
1898                          tossing here.  delete_insn does preserve the next
1899                          pointers, but when we skip over a NOTE we must fix
1900                          it up.  Otherwise that code walks into the non-deleted
1901                          insn stream.  */
1902                       while (p && GET_CODE (p) == NOTE)
1903                         p = NEXT_INSN (temp) = NEXT_INSN (p);
1904                     }
1905
1906                   start_sequence ();
1907                   emit_move_insn (m->set_dest, m->set_src);
1908                   temp = get_insns ();
1909                   end_sequence ();
1910
1911                   add_label_notes (m->set_src, temp);
1912
1913                   i1 = emit_insns_before (temp, loop_start);
1914                   if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1915                     REG_NOTES (i1)
1916                       = gen_rtx_EXPR_LIST (m->is_equiv ? REG_EQUIV : REG_EQUAL,
1917                                            m->set_src, REG_NOTES (i1));
1918
1919                   if (loop_dump_stream)
1920                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1921
1922                   /* The more regs we move, the less we like moving them.  */
1923                   threshold -= 3;
1924                 }
1925               else
1926                 {
1927                   for (count = m->consec; count >= 0; count--)
1928                     {
1929                       rtx i1, temp;
1930
1931                       /* If first insn of libcall sequence, skip to end.  */
1932                       /* Do this at start of loop, since p is guaranteed to 
1933                          be an insn here.  */
1934                       if (GET_CODE (p) != NOTE
1935                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1936                         p = XEXP (temp, 0);
1937
1938                       /* If last insn of libcall sequence, move all
1939                          insns except the last before the loop.  The last
1940                          insn is handled in the normal manner.  */
1941                       if (GET_CODE (p) != NOTE
1942                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1943                         {
1944                           rtx fn_address = 0;
1945                           rtx fn_reg = 0;
1946                           rtx fn_address_insn = 0;
1947
1948                           first = 0;
1949                           for (temp = XEXP (temp, 0); temp != p;
1950                                temp = NEXT_INSN (temp))
1951                             {
1952                               rtx body;
1953                               rtx n;
1954                               rtx next;
1955
1956                               if (GET_CODE (temp) == NOTE)
1957                                 continue;
1958
1959                               body = PATTERN (temp);
1960
1961                               /* Find the next insn after TEMP,
1962                                  not counting USE or NOTE insns.  */
1963                               for (next = NEXT_INSN (temp); next != p;
1964                                    next = NEXT_INSN (next))
1965                                 if (! (GET_CODE (next) == INSN
1966                                        && GET_CODE (PATTERN (next)) == USE)
1967                                     && GET_CODE (next) != NOTE)
1968                                   break;
1969                               
1970                               /* If that is the call, this may be the insn
1971                                  that loads the function address.
1972
1973                                  Extract the function address from the insn
1974                                  that loads it into a register.
1975                                  If this insn was cse'd, we get incorrect code.
1976
1977                                  So emit a new move insn that copies the
1978                                  function address into the register that the
1979                                  call insn will use.  flow.c will delete any
1980                                  redundant stores that we have created.  */
1981                               if (GET_CODE (next) == CALL_INSN
1982                                   && GET_CODE (body) == SET
1983                                   && GET_CODE (SET_DEST (body)) == REG
1984                                   && (n = find_reg_note (temp, REG_EQUAL,
1985                                                          NULL_RTX)))
1986                                 {
1987                                   fn_reg = SET_SRC (body);
1988                                   if (GET_CODE (fn_reg) != REG)
1989                                     fn_reg = SET_DEST (body);
1990                                   fn_address = XEXP (n, 0);
1991                                   fn_address_insn = temp;
1992                                 }
1993                               /* We have the call insn.
1994                                  If it uses the register we suspect it might,
1995                                  load it with the correct address directly.  */
1996                               if (GET_CODE (temp) == CALL_INSN
1997                                   && fn_address != 0
1998                                   && reg_referenced_p (fn_reg, body))
1999                                 emit_insn_after (gen_move_insn (fn_reg,
2000                                                                 fn_address),
2001                                                  fn_address_insn);
2002
2003                               if (GET_CODE (temp) == CALL_INSN)
2004                                 {
2005                                   i1 = emit_call_insn_before (body, loop_start);
2006                                   /* Because the USAGE information potentially
2007                                      contains objects other than hard registers
2008                                      we need to copy it.  */
2009                                   if (CALL_INSN_FUNCTION_USAGE (temp))
2010                                     CALL_INSN_FUNCTION_USAGE (i1)
2011                                       = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2012                                 }
2013                               else
2014                                 i1 = emit_insn_before (body, loop_start);
2015                               if (first == 0)
2016                                 first = i1;
2017                               if (temp == fn_address_insn)
2018                                 fn_address_insn = i1;
2019                               REG_NOTES (i1) = REG_NOTES (temp);
2020                               delete_insn (temp);
2021                             }
2022                           if (new_start == 0)
2023                             new_start = first;
2024                         }
2025                       if (m->savemode != VOIDmode)
2026                         {
2027                           /* P sets REG to zero; but we should clear only
2028                              the bits that are not covered by the mode
2029                              m->savemode.  */
2030                           rtx reg = m->set_dest;
2031                           rtx sequence;
2032                           rtx tem;
2033                       
2034                           start_sequence ();
2035                           tem = expand_binop
2036                             (GET_MODE (reg), and_optab, reg,
2037                              GEN_INT ((((HOST_WIDE_INT) 1
2038                                         << GET_MODE_BITSIZE (m->savemode)))
2039                                       - 1),
2040                              reg, 1, OPTAB_LIB_WIDEN);
2041                           if (tem == 0)
2042                             abort ();
2043                           if (tem != reg)
2044                             emit_move_insn (reg, tem);
2045                           sequence = gen_sequence ();
2046                           end_sequence ();
2047                           i1 = emit_insn_before (sequence, loop_start);
2048                         }
2049                       else if (GET_CODE (p) == CALL_INSN)
2050                         {
2051                           i1 = emit_call_insn_before (PATTERN (p), loop_start);
2052                           /* Because the USAGE information potentially
2053                              contains objects other than hard registers
2054                              we need to copy it.  */
2055                           if (CALL_INSN_FUNCTION_USAGE (p))
2056                             CALL_INSN_FUNCTION_USAGE (i1)
2057                               = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2058                         }
2059                       else if (count == m->consec && m->move_insn_first)
2060                         {
2061                           /* The SET_SRC might not be invariant, so we must
2062                              use the REG_EQUAL note.  */
2063                           start_sequence ();
2064                           emit_move_insn (m->set_dest, m->set_src);
2065                           temp = get_insns ();
2066                           end_sequence ();
2067
2068                           add_label_notes (m->set_src, temp);
2069
2070                           i1 = emit_insns_before (temp, loop_start);
2071                           if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2072                             REG_NOTES (i1)
2073                               = gen_rtx_EXPR_LIST ((m->is_equiv ? REG_EQUIV
2074                                                     : REG_EQUAL),
2075                                                    m->set_src, REG_NOTES (i1));
2076                         }
2077                       else
2078                         i1 = emit_insn_before (PATTERN (p), loop_start);
2079
2080                       if (REG_NOTES (i1) == 0)
2081                         {
2082                           REG_NOTES (i1) = REG_NOTES (p);
2083
2084                           /* If there is a REG_EQUAL note present whose value
2085                              is not loop invariant, then delete it, since it
2086                              may cause problems with later optimization passes.
2087                              It is possible for cse to create such notes
2088                              like this as a result of record_jump_cond.  */
2089                       
2090                           if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2091                               && ! invariant_p (XEXP (temp, 0)))
2092                             remove_note (i1, temp);
2093                         }
2094
2095                       if (new_start == 0)
2096                         new_start = i1;
2097
2098                       if (loop_dump_stream)
2099                         fprintf (loop_dump_stream, " moved to %d",
2100                                  INSN_UID (i1));
2101
2102                       /* If library call, now fix the REG_NOTES that contain
2103                          insn pointers, namely REG_LIBCALL on FIRST
2104                          and REG_RETVAL on I1.  */
2105                       if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2106                         {
2107                           XEXP (temp, 0) = first;
2108                           temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2109                           XEXP (temp, 0) = i1;
2110                         }
2111
2112                       temp = p;
2113                       delete_insn (p);
2114                       p = NEXT_INSN (p);
2115
2116                       /* simplify_giv_expr expects that it can walk the insns
2117                          at m->insn forwards and see this old sequence we are
2118                          tossing here.  delete_insn does preserve the next
2119                          pointers, but when we skip over a NOTE we must fix
2120                          it up.  Otherwise that code walks into the non-deleted
2121                          insn stream.  */
2122                       while (p && GET_CODE (p) == NOTE)
2123                         p = NEXT_INSN (temp) = NEXT_INSN (p);
2124                     }
2125
2126                   /* The more regs we move, the less we like moving them.  */
2127                   threshold -= 3;
2128                 }
2129
2130               /* Any other movable that loads the same register
2131                  MUST be moved.  */
2132               already_moved[regno] = 1;
2133
2134               /* This reg has been moved out of one loop.  */
2135               moved_once[regno] = 1;
2136
2137               /* The reg set here is now invariant.  */
2138               if (! m->partial)
2139                 VARRAY_INT (set_in_loop, regno) = 0;
2140
2141               m->done = 1;
2142
2143               /* Change the length-of-life info for the register
2144                  to say it lives at least the full length of this loop.
2145                  This will help guide optimizations in outer loops.  */
2146
2147               if (uid_luid[REGNO_FIRST_UID (regno)] > INSN_LUID (loop_start))
2148                 /* This is the old insn before all the moved insns.
2149                    We can't use the moved insn because it is out of range
2150                    in uid_luid.  Only the old insns have luids.  */
2151                 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2152               if (uid_luid[REGNO_LAST_UID (regno)] < INSN_LUID (end))
2153                 REGNO_LAST_UID (regno) = INSN_UID (end);
2154
2155               /* Combine with this moved insn any other matching movables.  */
2156
2157               if (! m->partial)
2158                 for (m1 = movables; m1; m1 = m1->next)
2159                   if (m1->match == m)
2160                     {
2161                       rtx temp;
2162
2163                       /* Schedule the reg loaded by M1
2164                          for replacement so that shares the reg of M.
2165                          If the modes differ (only possible in restricted
2166                          circumstances, make a SUBREG.
2167
2168                          Note this assumes that the target dependent files
2169                          treat REG and SUBREG equally, including within
2170                          GO_IF_LEGITIMATE_ADDRESS and in all the
2171                          predicates since we never verify that replacing the
2172                          original register with a SUBREG results in a
2173                          recognizable insn.  */
2174                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2175                         reg_map[m1->regno] = m->set_dest;
2176                       else
2177                         reg_map[m1->regno]
2178                           = gen_lowpart_common (GET_MODE (m1->set_dest),
2179                                                 m->set_dest);
2180                     
2181                       /* Get rid of the matching insn
2182                          and prevent further processing of it.  */
2183                       m1->done = 1;
2184
2185                       /* if library call, delete all insn except last, which
2186                          is deleted below */
2187                       if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2188                                                  NULL_RTX)))
2189                         {
2190                           for (temp = XEXP (temp, 0); temp != m1->insn;
2191                                temp = NEXT_INSN (temp))
2192                             delete_insn (temp);
2193                         }
2194                       delete_insn (m1->insn);
2195
2196                       /* Any other movable that loads the same register
2197                          MUST be moved.  */
2198                       already_moved[m1->regno] = 1;
2199
2200                       /* The reg merged here is now invariant,
2201                          if the reg it matches is invariant.  */
2202                       if (! m->partial)
2203                         VARRAY_INT (set_in_loop, m1->regno) = 0;
2204                     }
2205             }
2206           else if (loop_dump_stream)
2207             fprintf (loop_dump_stream, "not desirable");
2208         }
2209       else if (loop_dump_stream && !m->match)
2210         fprintf (loop_dump_stream, "not safe");
2211
2212       if (loop_dump_stream)
2213         fprintf (loop_dump_stream, "\n");
2214     }
2215
2216   if (new_start == 0)
2217     new_start = loop_start;
2218
2219   /* Go through all the instructions in the loop, making
2220      all the register substitutions scheduled in REG_MAP.  */
2221   for (p = new_start; p != end; p = NEXT_INSN (p))
2222     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2223         || GET_CODE (p) == CALL_INSN)
2224       {
2225         replace_regs (PATTERN (p), reg_map, nregs, 0);
2226         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2227         INSN_CODE (p) = -1;
2228       }
2229 }
2230 \f
2231 #if 0
2232 /* Scan X and replace the address of any MEM in it with ADDR.
2233    REG is the address that MEM should have before the replacement.  */
2234
2235 static void
2236 replace_call_address (x, reg, addr)
2237      rtx x, reg, addr;
2238 {
2239   register enum rtx_code code;
2240   register int i;
2241   register const char *fmt;
2242
2243   if (x == 0)
2244     return;
2245   code = GET_CODE (x);
2246   switch (code)
2247     {
2248     case PC:
2249     case CC0:
2250     case CONST_INT:
2251     case CONST_DOUBLE:
2252     case CONST:
2253     case SYMBOL_REF:
2254     case LABEL_REF:
2255     case REG:
2256       return;
2257
2258     case SET:
2259       /* Short cut for very common case.  */
2260       replace_call_address (XEXP (x, 1), reg, addr);
2261       return;
2262
2263     case CALL:
2264       /* Short cut for very common case.  */
2265       replace_call_address (XEXP (x, 0), reg, addr);
2266       return;
2267
2268     case MEM:
2269       /* If this MEM uses a reg other than the one we expected,
2270          something is wrong.  */
2271       if (XEXP (x, 0) != reg)
2272         abort ();
2273       XEXP (x, 0) = addr;
2274       return;
2275       
2276     default:
2277       break;
2278     }
2279
2280   fmt = GET_RTX_FORMAT (code);
2281   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2282     {
2283       if (fmt[i] == 'e')
2284         replace_call_address (XEXP (x, i), reg, addr);
2285       if (fmt[i] == 'E')
2286         {
2287           register int j;
2288           for (j = 0; j < XVECLEN (x, i); j++)
2289             replace_call_address (XVECEXP (x, i, j), reg, addr);
2290         }
2291     }
2292 }
2293 #endif
2294 \f
2295 /* Return the number of memory refs to addresses that vary
2296    in the rtx X.  */
2297
2298 static int
2299 count_nonfixed_reads (x)
2300      rtx x;
2301 {
2302   register enum rtx_code code;
2303   register int i;
2304   register const char *fmt;
2305   int value;
2306
2307   if (x == 0)
2308     return 0;
2309
2310   code = GET_CODE (x);
2311   switch (code)
2312     {
2313     case PC:
2314     case CC0:
2315     case CONST_INT:
2316     case CONST_DOUBLE:
2317     case CONST:
2318     case SYMBOL_REF:
2319     case LABEL_REF:
2320     case REG:
2321       return 0;
2322
2323     case MEM:
2324       return ((invariant_p (XEXP (x, 0)) != 1)
2325               + count_nonfixed_reads (XEXP (x, 0)));
2326       
2327     default:
2328       break;
2329     }
2330
2331   value = 0;
2332   fmt = GET_RTX_FORMAT (code);
2333   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2334     {
2335       if (fmt[i] == 'e')
2336         value += count_nonfixed_reads (XEXP (x, i));
2337       if (fmt[i] == 'E')
2338         {
2339           register int j;
2340           for (j = 0; j < XVECLEN (x, i); j++)
2341             value += count_nonfixed_reads (XVECEXP (x, i, j));
2342         }
2343     }
2344   return value;
2345 }
2346
2347 \f
2348 #if 0
2349 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2350    Replace it with an instruction to load just the low bytes
2351    if the machine supports such an instruction,
2352    and insert above LOOP_START an instruction to clear the register.  */
2353
2354 static void
2355 constant_high_bytes (p, loop_start)
2356      rtx p, loop_start;
2357 {
2358   register rtx new;
2359   register int insn_code_number;
2360
2361   /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2362      to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...).  */
2363
2364   new
2365     = gen_rtx_SET
2366       (VOIDmode,
2367        gen_rtx_STRICT_LOW_PART
2368        (VOIDmode,
2369         gen_rtx_SUBREG (GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2370                         SET_DEST (PATTERN (p)), 0)),
2371        XEXP (SET_SRC (PATTERN (p)), 0));
2372
2373   insn_code_number = recog (new, p);
2374
2375   if (insn_code_number)
2376     {
2377       register int i;
2378
2379       /* Clear destination register before the loop.  */
2380       emit_insn_before (gen_rtx_SET (VOIDmode,
2381                                      SET_DEST (PATTERN (p)), const0_rtx),
2382                         loop_start);
2383
2384       /* Inside the loop, just load the low part.  */
2385       PATTERN (p) = new;
2386     }
2387 }
2388 #endif
2389 \f
2390 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2391    `has_call', `has_volatile', and `has_tablejump' within LOOP_INFO.
2392    Set the global variables `unknown_address_altered' and
2393    `num_mem_sets'.  Also, fill in the array `loop_mems' and the list
2394    `loop_store_mems'.  */
2395
2396 static void
2397 prescan_loop (start, end, loop_info)
2398      rtx start, end;
2399      struct loop_info *loop_info;
2400 {
2401   register int level = 1;
2402   rtx insn;
2403   /* The label after END.  Jumping here is just like falling off the
2404      end of the loop.  We use next_nonnote_insn instead of next_label
2405      as a hedge against the (pathological) case where some actual insn
2406      might end up between the two.  */
2407   rtx exit_target = next_nonnote_insn (end);
2408
2409   loop_info->num = uid_loop_num [INSN_UID (start)];
2410   loop_info->has_indirect_jump = indirect_jump_in_function;
2411   loop_info->has_call = 0;
2412   loop_info->has_volatile = 0;
2413   loop_info->has_tablejump = 0;
2414   loop_info->loops_enclosed = 1;
2415   loop_info->has_multiple_exit_targets = 0;
2416   loop_info->cont = 0;
2417   loop_info->vtop = 0;
2418
2419   unknown_address_altered = 0;
2420   loop_store_mems = NULL_RTX;
2421   first_loop_store_insn = NULL_RTX;
2422   loop_mems_idx = 0;
2423   num_mem_sets = 0;
2424
2425   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2426        insn = NEXT_INSN (insn))
2427     {
2428       if (GET_CODE (insn) == NOTE)
2429         {
2430           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2431             {
2432               ++level;
2433               /* Count number of loops contained in this one.  */
2434               loop_info->loops_enclosed++;
2435             }
2436           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2437             {
2438               --level;
2439               if (level == 0)
2440                 {
2441                   end = insn;
2442                   break;
2443                 }
2444             }
2445           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2446             {
2447               if (level == 1)
2448                 loop_info->cont = insn;
2449             }
2450           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_VTOP)
2451             {
2452               /* If there is a NOTE_INSN_LOOP_VTOP, then this is a for
2453                  or while style loop, with a loop exit test at the
2454                  start.  Thus, we can assume that the loop condition
2455                  was true when the loop was entered.  */
2456               if (level == 1)
2457                 loop_info->vtop = insn;
2458             }
2459         }
2460       else if (GET_CODE (insn) == CALL_INSN)
2461         {
2462           if (! CONST_CALL_P (insn))
2463             unknown_address_altered = 1;
2464           loop_info->has_call = 1;
2465         }
2466       else if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2467         {
2468           rtx label1 = NULL_RTX;
2469           rtx label2 = NULL_RTX;
2470
2471           if (volatile_refs_p (PATTERN (insn)))
2472             loop_info->has_volatile = 1;
2473
2474           if (GET_CODE (insn) == JUMP_INSN
2475               && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2476                   || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2477             loop_info->has_tablejump = 1;
2478           
2479           note_stores (PATTERN (insn), note_addr_stored);
2480           if (! first_loop_store_insn && loop_store_mems)
2481             first_loop_store_insn = insn;
2482
2483           if (! loop_info->has_multiple_exit_targets
2484               && GET_CODE (insn) == JUMP_INSN
2485               && GET_CODE (PATTERN (insn)) == SET
2486               && SET_DEST (PATTERN (insn)) == pc_rtx)
2487             {
2488               if (GET_CODE (SET_SRC (PATTERN (insn))) == IF_THEN_ELSE)
2489                 {
2490                   label1 = XEXP (SET_SRC (PATTERN (insn)), 1);
2491                   label2 = XEXP (SET_SRC (PATTERN (insn)), 2);
2492                 }
2493               else
2494                 {
2495                   label1 = SET_SRC (PATTERN (insn));
2496                 }
2497
2498               do {
2499                 if (label1 && label1 != pc_rtx)
2500                   {
2501                     if (GET_CODE (label1) != LABEL_REF)
2502                       {
2503                         /* Something tricky.  */
2504                         loop_info->has_multiple_exit_targets = 1;
2505                         break;
2506                       }
2507                     else if (XEXP (label1, 0) != exit_target
2508                              && LABEL_OUTSIDE_LOOP_P (label1))
2509                       {
2510                         /* A jump outside the current loop.  */
2511                         loop_info->has_multiple_exit_targets = 1;
2512                         break;
2513                       }
2514                   }
2515
2516                 label1 = label2;
2517                 label2 = NULL_RTX;
2518               } while (label1);
2519             }
2520         }
2521       else if (GET_CODE (insn) == RETURN)
2522         loop_info->has_multiple_exit_targets = 1;
2523     }
2524
2525   /* Now, rescan the loop, setting up the LOOP_MEMS array.  */
2526   if (/* We can't tell what MEMs are aliased by what.  */
2527       !unknown_address_altered 
2528       /* An exception thrown by a called function might land us
2529          anywhere.  */
2530       && !loop_info->has_call
2531       /* We don't want loads for MEMs moved to a location before the
2532          one at which their stack memory becomes allocated.  (Note
2533          that this is not a problem for malloc, etc., since those
2534          require actual function calls.  */
2535       && !current_function_calls_alloca
2536       /* There are ways to leave the loop other than falling off the
2537          end.  */
2538       && !loop_info->has_multiple_exit_targets)
2539     for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2540          insn = NEXT_INSN (insn))
2541       for_each_rtx (&insn, insert_loop_mem, 0);
2542 }
2543 \f
2544 /* LOOP_NUMBER_CONT_DOMINATOR is now the last label between the loop start
2545    and the continue note that is a the destination of a (cond)jump after
2546    the continue note.  If there is any (cond)jump between the loop start
2547    and what we have so far as LOOP_NUMBER_CONT_DOMINATOR that has a
2548    target between LOOP_DOMINATOR and the continue note, move
2549    LOOP_NUMBER_CONT_DOMINATOR forward to that label; if a jump's
2550    destination cannot be determined, clear LOOP_NUMBER_CONT_DOMINATOR.  */
2551
2552 static void
2553 verify_dominator (loop_number)
2554      int loop_number;
2555 {
2556   rtx insn;
2557
2558   if (! loop_number_cont_dominator[loop_number])
2559     /* This can happen for an empty loop, e.g. in
2560        gcc.c-torture/compile/920410-2.c  */
2561     return;
2562   if (loop_number_cont_dominator[loop_number] == const0_rtx)
2563     {
2564       loop_number_cont_dominator[loop_number] = 0;
2565       return;
2566     }
2567   for (insn = loop_number_loop_starts[loop_number];
2568        insn != loop_number_cont_dominator[loop_number];
2569        insn = NEXT_INSN (insn))
2570     {
2571       if (GET_CODE (insn) == JUMP_INSN
2572           && GET_CODE (PATTERN (insn)) != RETURN)
2573         {
2574           rtx label = JUMP_LABEL (insn);
2575           int label_luid;
2576
2577           /* If it is not a jump we can easily understand or for
2578              which we do not have jump target information in the JUMP_LABEL
2579              field (consider ADDR_VEC and ADDR_DIFF_VEC insns), then clear
2580              LOOP_NUMBER_CONT_DOMINATOR.  */
2581           if ((! condjump_p (insn)
2582                && ! condjump_in_parallel_p (insn))
2583               || label == NULL_RTX)
2584             {
2585               loop_number_cont_dominator[loop_number] = NULL_RTX;
2586               return;
2587             }
2588
2589           label_luid = INSN_LUID (label);
2590           if (label_luid < INSN_LUID (loop_number_loop_cont[loop_number])
2591               && (label_luid
2592                   > INSN_LUID (loop_number_cont_dominator[loop_number])))
2593             loop_number_cont_dominator[loop_number] = label;
2594         }
2595     }
2596 }
2597
2598 /* Scan the function looking for loops.  Record the start and end of each loop.
2599    Also mark as invalid loops any loops that contain a setjmp or are branched
2600    to from outside the loop.  */
2601
2602 static void
2603 find_and_verify_loops (f)
2604      rtx f;
2605 {
2606   rtx insn, label;
2607   int current_loop = -1;
2608   int next_loop = -1;
2609   int loop;
2610
2611   compute_luids (f, NULL_RTX, 0);
2612
2613   /* If there are jumps to undefined labels,
2614      treat them as jumps out of any/all loops.
2615      This also avoids writing past end of tables when there are no loops.  */
2616   uid_loop_num[0] = -1;
2617
2618   /* Find boundaries of loops, mark which loops are contained within
2619      loops, and invalidate loops that have setjmp.  */
2620
2621   for (insn = f; insn; insn = NEXT_INSN (insn))
2622     {
2623       if (GET_CODE (insn) == NOTE)
2624         switch (NOTE_LINE_NUMBER (insn))
2625           {
2626           case NOTE_INSN_LOOP_BEG:
2627             loop_number_loop_starts[++next_loop] =  insn;
2628             loop_number_loop_ends[next_loop] = 0;
2629             loop_number_loop_cont[next_loop] = 0;
2630             loop_number_cont_dominator[next_loop] = 0;
2631             loop_outer_loop[next_loop] = current_loop;
2632             loop_invalid[next_loop] = 0;
2633             loop_number_exit_labels[next_loop] = 0;
2634             loop_number_exit_count[next_loop] = 0;
2635             current_loop = next_loop;
2636             break;
2637
2638           case NOTE_INSN_SETJMP:
2639             /* In this case, we must invalidate our current loop and any
2640                enclosing loop.  */
2641             for (loop = current_loop; loop != -1; loop = loop_outer_loop[loop])
2642               {
2643                 loop_invalid[loop] = 1;
2644                 if (loop_dump_stream)
2645                   fprintf (loop_dump_stream,
2646                            "\nLoop at %d ignored due to setjmp.\n",
2647                            INSN_UID (loop_number_loop_starts[loop]));
2648               }
2649             break;
2650
2651           case NOTE_INSN_LOOP_CONT:
2652             loop_number_loop_cont[current_loop] = insn;
2653             break;
2654           case NOTE_INSN_LOOP_END:
2655             if (current_loop == -1)
2656               abort ();
2657
2658             loop_number_loop_ends[current_loop] = insn;
2659             verify_dominator (current_loop);
2660             current_loop = loop_outer_loop[current_loop];
2661             break;
2662
2663           default:
2664             break;
2665           }
2666       /* If for any loop, this is a jump insn between the NOTE_INSN_LOOP_CONT
2667          and NOTE_INSN_LOOP_END notes, update loop_number_loop_dominator.  */
2668       else if (GET_CODE (insn) == JUMP_INSN
2669                && GET_CODE (PATTERN (insn)) != RETURN
2670                && current_loop >= 0)
2671         {
2672           int this_loop_num;
2673           rtx label = JUMP_LABEL (insn);
2674
2675           if (! condjump_p (insn) && ! condjump_in_parallel_p (insn))
2676             label = NULL_RTX;
2677
2678           this_loop_num = current_loop;
2679           do
2680             {
2681               /* First see if we care about this loop.  */
2682               if (loop_number_loop_cont[this_loop_num]
2683                   && loop_number_cont_dominator[this_loop_num] != const0_rtx)
2684                 {
2685                   /* If the jump destination is not known, invalidate
2686                      loop_number_const_dominator.  */
2687                   if (! label)
2688                     loop_number_cont_dominator[this_loop_num] = const0_rtx;
2689                   else
2690                     /* Check if the destination is between loop start and
2691                        cont.  */
2692                     if ((INSN_LUID (label)
2693                          < INSN_LUID (loop_number_loop_cont[this_loop_num]))
2694                         && (INSN_LUID (label)
2695                             > INSN_LUID (loop_number_loop_starts[this_loop_num]))
2696                         /* And if there is no later destination already
2697                            recorded.  */
2698                         && (! loop_number_cont_dominator[this_loop_num]
2699                             || (INSN_LUID (label)
2700                                 > INSN_LUID (loop_number_cont_dominator
2701                                              [this_loop_num]))))
2702                       loop_number_cont_dominator[this_loop_num] = label;
2703                 }
2704               this_loop_num = loop_outer_loop[this_loop_num];
2705             }
2706           while (this_loop_num >= 0);
2707         }
2708
2709       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2710          enclosing loop, but this doesn't matter.  */
2711       uid_loop_num[INSN_UID (insn)] = current_loop;
2712     }
2713
2714   /* Any loop containing a label used in an initializer must be invalidated,
2715      because it can be jumped into from anywhere.  */
2716
2717   for (label = forced_labels; label; label = XEXP (label, 1))
2718     {
2719       int loop_num;
2720
2721       for (loop_num = uid_loop_num[INSN_UID (XEXP (label, 0))];
2722            loop_num != -1;
2723            loop_num = loop_outer_loop[loop_num])
2724         loop_invalid[loop_num] = 1;
2725     }
2726
2727   /* Any loop containing a label used for an exception handler must be
2728      invalidated, because it can be jumped into from anywhere.  */
2729
2730   for (label = exception_handler_labels; label; label = XEXP (label, 1))
2731     {
2732       int loop_num;
2733
2734       for (loop_num = uid_loop_num[INSN_UID (XEXP (label, 0))];
2735            loop_num != -1;
2736            loop_num = loop_outer_loop[loop_num])
2737         loop_invalid[loop_num] = 1;
2738     }
2739
2740   /* Now scan all insn's in the function.  If any JUMP_INSN branches into a
2741      loop that it is not contained within, that loop is marked invalid.
2742      If any INSN or CALL_INSN uses a label's address, then the loop containing
2743      that label is marked invalid, because it could be jumped into from
2744      anywhere.
2745
2746      Also look for blocks of code ending in an unconditional branch that
2747      exits the loop.  If such a block is surrounded by a conditional 
2748      branch around the block, move the block elsewhere (see below) and
2749      invert the jump to point to the code block.  This may eliminate a
2750      label in our loop and will simplify processing by both us and a
2751      possible second cse pass.  */
2752
2753   for (insn = f; insn; insn = NEXT_INSN (insn))
2754     if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2755       {
2756         int this_loop_num = uid_loop_num[INSN_UID (insn)];
2757
2758         if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2759           {
2760             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2761             if (note)
2762               {
2763                 int loop_num;
2764
2765                 for (loop_num = uid_loop_num[INSN_UID (XEXP (note, 0))];
2766                      loop_num != -1;
2767                      loop_num = loop_outer_loop[loop_num])
2768                   loop_invalid[loop_num] = 1;
2769               }
2770           }
2771
2772         if (GET_CODE (insn) != JUMP_INSN)
2773           continue;
2774
2775         mark_loop_jump (PATTERN (insn), this_loop_num);
2776
2777         /* See if this is an unconditional branch outside the loop.  */
2778         if (this_loop_num != -1
2779             && (GET_CODE (PATTERN (insn)) == RETURN
2780                 || (simplejump_p (insn)
2781                     && (uid_loop_num[INSN_UID (JUMP_LABEL (insn))]
2782                         != this_loop_num)))
2783             && get_max_uid () < max_uid_for_loop)
2784           {
2785             rtx p;
2786             rtx our_next = next_real_insn (insn);
2787             rtx last_insn_to_move = NEXT_INSN (insn);
2788             int dest_loop;
2789             int outer_loop = -1;
2790
2791             /* Go backwards until we reach the start of the loop, a label,
2792                or a JUMP_INSN.  */
2793             for (p = PREV_INSN (insn);
2794                  GET_CODE (p) != CODE_LABEL
2795                  && ! (GET_CODE (p) == NOTE
2796                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2797                  && GET_CODE (p) != JUMP_INSN;
2798                  p = PREV_INSN (p))
2799               ;
2800
2801             /* Check for the case where we have a jump to an inner nested
2802                loop, and do not perform the optimization in that case.  */
2803
2804             if (JUMP_LABEL (insn))
2805               {
2806                 dest_loop = uid_loop_num[INSN_UID (JUMP_LABEL (insn))];
2807                 if (dest_loop != -1)
2808                   {
2809                     for (outer_loop = dest_loop; outer_loop != -1;
2810                          outer_loop = loop_outer_loop[outer_loop])
2811                       if (outer_loop == this_loop_num)
2812                         break;
2813                   }
2814               }
2815
2816             /* Make sure that the target of P is within the current loop.  */
2817
2818             if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2819                 && uid_loop_num[INSN_UID (JUMP_LABEL (p))] != this_loop_num)
2820               outer_loop = this_loop_num;
2821
2822             /* If we stopped on a JUMP_INSN to the next insn after INSN,
2823                we have a block of code to try to move.
2824
2825                We look backward and then forward from the target of INSN
2826                to find a BARRIER at the same loop depth as the target.
2827                If we find such a BARRIER, we make a new label for the start
2828                of the block, invert the jump in P and point it to that label,
2829                and move the block of code to the spot we found.  */
2830
2831             if (outer_loop == -1
2832                 && GET_CODE (p) == JUMP_INSN
2833                 && JUMP_LABEL (p) != 0
2834                 /* Just ignore jumps to labels that were never emitted.
2835                    These always indicate compilation errors.  */
2836                 && INSN_UID (JUMP_LABEL (p)) != 0
2837                 && condjump_p (p)
2838                 && ! simplejump_p (p)
2839                 && next_real_insn (JUMP_LABEL (p)) == our_next
2840                 /* If it's not safe to move the sequence, then we
2841                    mustn't try.  */
2842                 && insns_safe_to_move_p (p, NEXT_INSN (insn), 
2843                                          &last_insn_to_move))
2844               {
2845                 rtx target
2846                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2847                 int target_loop_num = uid_loop_num[INSN_UID (target)];
2848                 rtx loc, loc2;
2849
2850                 for (loc = target; loc; loc = PREV_INSN (loc))
2851                   if (GET_CODE (loc) == BARRIER
2852                       /* Don't move things inside a tablejump.  */
2853                       && ((loc2 = next_nonnote_insn (loc)) == 0
2854                           || GET_CODE (loc2) != CODE_LABEL
2855                           || (loc2 = next_nonnote_insn (loc2)) == 0
2856                           || GET_CODE (loc2) != JUMP_INSN
2857                           || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2858                               && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2859                       && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2860                     break;
2861
2862                 if (loc == 0)
2863                   for (loc = target; loc; loc = NEXT_INSN (loc))
2864                     if (GET_CODE (loc) == BARRIER
2865                         /* Don't move things inside a tablejump.  */
2866                         && ((loc2 = next_nonnote_insn (loc)) == 0
2867                             || GET_CODE (loc2) != CODE_LABEL
2868                             || (loc2 = next_nonnote_insn (loc2)) == 0
2869                             || GET_CODE (loc2) != JUMP_INSN
2870                             || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2871                                 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2872                         && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2873                       break;
2874
2875                 if (loc)
2876                   {
2877                     rtx cond_label = JUMP_LABEL (p);
2878                     rtx new_label = get_label_after (p);
2879
2880                     /* Ensure our label doesn't go away.  */
2881                     LABEL_NUSES (cond_label)++;
2882
2883                     /* Verify that uid_loop_num is large enough and that
2884                        we can invert P.  */
2885                    if (invert_jump (p, new_label))
2886                      {
2887                        rtx q, r;
2888
2889                        /* If no suitable BARRIER was found, create a suitable
2890                           one before TARGET.  Since TARGET is a fall through
2891                           path, we'll need to insert an jump around our block
2892                           and a add a BARRIER before TARGET.
2893
2894                           This creates an extra unconditional jump outside
2895                           the loop.  However, the benefits of removing rarely
2896                           executed instructions from inside the loop usually
2897                           outweighs the cost of the extra unconditional jump
2898                           outside the loop.  */
2899                        if (loc == 0)
2900                          {
2901                            rtx temp;
2902
2903                            temp = gen_jump (JUMP_LABEL (insn));
2904                            temp = emit_jump_insn_before (temp, target);
2905                            JUMP_LABEL (temp) = JUMP_LABEL (insn);
2906                            LABEL_NUSES (JUMP_LABEL (insn))++;
2907                            loc = emit_barrier_before (target);
2908                          }
2909
2910                        /* Include the BARRIER after INSN and copy the
2911                           block after LOC.  */
2912                        new_label = squeeze_notes (new_label, 
2913                                                   last_insn_to_move);
2914                        reorder_insns (new_label, last_insn_to_move, loc);
2915
2916                        /* All those insns are now in TARGET_LOOP_NUM.  */
2917                        for (q = new_label; 
2918                             q != NEXT_INSN (last_insn_to_move);
2919                             q = NEXT_INSN (q))
2920                          uid_loop_num[INSN_UID (q)] = target_loop_num;
2921
2922                        /* The label jumped to by INSN is no longer a loop exit.
2923                           Unless INSN does not have a label (e.g., it is a
2924                           RETURN insn), search loop_number_exit_labels to find
2925                           its label_ref, and remove it.  Also turn off
2926                           LABEL_OUTSIDE_LOOP_P bit.  */
2927                        if (JUMP_LABEL (insn))
2928                          {
2929                            int loop_num;
2930
2931                            for (q = 0,
2932                                 r = loop_number_exit_labels[this_loop_num];
2933                                 r; q = r, r = LABEL_NEXTREF (r))
2934                              if (XEXP (r, 0) == JUMP_LABEL (insn))
2935                                {
2936                                  LABEL_OUTSIDE_LOOP_P (r) = 0;
2937                                  if (q)
2938                                    LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2939                                  else
2940                                    loop_number_exit_labels[this_loop_num]
2941                                      = LABEL_NEXTREF (r);
2942                                  break;
2943                                }
2944
2945                            for (loop_num = this_loop_num;
2946                                 loop_num != -1 && loop_num != target_loop_num;
2947                                 loop_num = loop_outer_loop[loop_num])
2948                              loop_number_exit_count[loop_num]--;
2949
2950                            /* If we didn't find it, then something is wrong.  */
2951                            if (! r)
2952                              abort ();
2953                          }
2954
2955                        /* P is now a jump outside the loop, so it must be put
2956                           in loop_number_exit_labels, and marked as such.
2957                           The easiest way to do this is to just call
2958                           mark_loop_jump again for P.  */
2959                        mark_loop_jump (PATTERN (p), this_loop_num);
2960
2961                        /* If INSN now jumps to the insn after it,
2962                           delete INSN.  */
2963                        if (JUMP_LABEL (insn) != 0
2964                            && (next_real_insn (JUMP_LABEL (insn))
2965                                == next_real_insn (insn)))
2966                          delete_insn (insn);
2967                      }
2968
2969                     /* Continue the loop after where the conditional
2970                        branch used to jump, since the only branch insn
2971                        in the block (if it still remains) is an inter-loop
2972                        branch and hence needs no processing.  */
2973                     insn = NEXT_INSN (cond_label);
2974
2975                     if (--LABEL_NUSES (cond_label) == 0)
2976                       delete_insn (cond_label);
2977
2978                     /* This loop will be continued with NEXT_INSN (insn).  */
2979                     insn = PREV_INSN (insn);
2980                   }
2981               }
2982           }
2983       }
2984 }
2985
2986 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2987    loops it is contained in, mark the target loop invalid.
2988
2989    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
2990
2991 static void
2992 mark_loop_jump (x, loop_num)
2993      rtx x;
2994      int loop_num;
2995 {
2996   int dest_loop;
2997   int outer_loop;
2998   int i;
2999
3000   switch (GET_CODE (x))
3001     {
3002     case PC:
3003     case USE:
3004     case CLOBBER:
3005     case REG:
3006     case MEM:
3007     case CONST_INT:
3008     case CONST_DOUBLE:
3009     case RETURN:
3010       return;
3011
3012     case CONST:
3013       /* There could be a label reference in here.  */
3014       mark_loop_jump (XEXP (x, 0), loop_num);
3015       return;
3016
3017     case PLUS:
3018     case MINUS:
3019     case MULT:
3020       mark_loop_jump (XEXP (x, 0), loop_num);
3021       mark_loop_jump (XEXP (x, 1), loop_num);
3022       return;
3023
3024     case LO_SUM:
3025       /* This may refer to a LABEL_REF or SYMBOL_REF.  */
3026       mark_loop_jump (XEXP (x, 1), loop_num);
3027       return;
3028
3029     case SIGN_EXTEND:
3030     case ZERO_EXTEND:
3031       mark_loop_jump (XEXP (x, 0), loop_num);
3032       return;
3033
3034     case LABEL_REF:
3035       dest_loop = uid_loop_num[INSN_UID (XEXP (x, 0))];
3036
3037       /* Link together all labels that branch outside the loop.  This
3038          is used by final_[bg]iv_value and the loop unrolling code.  Also
3039          mark this LABEL_REF so we know that this branch should predict
3040          false.  */
3041
3042       /* A check to make sure the label is not in an inner nested loop,
3043          since this does not count as a loop exit.  */
3044       if (dest_loop != -1)
3045         {
3046           for (outer_loop = dest_loop; outer_loop != -1;
3047                outer_loop = loop_outer_loop[outer_loop])
3048             if (outer_loop == loop_num)
3049               break;
3050         }
3051       else
3052         outer_loop = -1;
3053
3054       if (loop_num != -1 && outer_loop == -1)
3055         {
3056           LABEL_OUTSIDE_LOOP_P (x) = 1;
3057           LABEL_NEXTREF (x) = loop_number_exit_labels[loop_num];
3058           loop_number_exit_labels[loop_num] = x;
3059
3060           for (outer_loop = loop_num;
3061                outer_loop != -1 && outer_loop != dest_loop;
3062                outer_loop = loop_outer_loop[outer_loop])
3063             loop_number_exit_count[outer_loop]++;
3064         }
3065
3066       /* If this is inside a loop, but not in the current loop or one enclosed
3067          by it, it invalidates at least one loop.  */
3068
3069       if (dest_loop == -1)
3070         return;
3071
3072       /* We must invalidate every nested loop containing the target of this
3073          label, except those that also contain the jump insn.  */
3074
3075       for (; dest_loop != -1; dest_loop = loop_outer_loop[dest_loop])
3076         {
3077           /* Stop when we reach a loop that also contains the jump insn.  */
3078           for (outer_loop = loop_num; outer_loop != -1;
3079                outer_loop = loop_outer_loop[outer_loop])
3080             if (dest_loop == outer_loop)
3081               return;
3082
3083           /* If we get here, we know we need to invalidate a loop.  */
3084           if (loop_dump_stream && ! loop_invalid[dest_loop])
3085             fprintf (loop_dump_stream,
3086                      "\nLoop at %d ignored due to multiple entry points.\n",
3087                      INSN_UID (loop_number_loop_starts[dest_loop]));
3088           
3089           loop_invalid[dest_loop] = 1;
3090         }
3091       return;
3092
3093     case SET:
3094       /* If this is not setting pc, ignore.  */
3095       if (SET_DEST (x) == pc_rtx)
3096         mark_loop_jump (SET_SRC (x), loop_num);
3097       return;
3098
3099     case IF_THEN_ELSE:
3100       mark_loop_jump (XEXP (x, 1), loop_num);
3101       mark_loop_jump (XEXP (x, 2), loop_num);
3102       return;
3103
3104     case PARALLEL:
3105     case ADDR_VEC:
3106       for (i = 0; i < XVECLEN (x, 0); i++)
3107         mark_loop_jump (XVECEXP (x, 0, i), loop_num);
3108       return;
3109
3110     case ADDR_DIFF_VEC:
3111       for (i = 0; i < XVECLEN (x, 1); i++)
3112         mark_loop_jump (XVECEXP (x, 1, i), loop_num);
3113       return;
3114
3115     default:
3116       /* Strictly speaking this is not a jump into the loop, only a possible
3117          jump out of the loop.  However, we have no way to link the destination
3118          of this jump onto the list of exit labels.  To be safe we mark this
3119          loop and any containing loops as invalid.  */
3120       if (loop_num != -1)
3121         {
3122           for (outer_loop = loop_num; outer_loop != -1;
3123                outer_loop = loop_outer_loop[outer_loop])
3124             {
3125               if (loop_dump_stream && ! loop_invalid[outer_loop])
3126                 fprintf (loop_dump_stream,
3127                          "\nLoop at %d ignored due to unknown exit jump.\n",
3128                          INSN_UID (loop_number_loop_starts[outer_loop]));
3129               loop_invalid[outer_loop] = 1;
3130             }
3131         }
3132       return;
3133     }
3134 }
3135 \f
3136 /* Return nonzero if there is a label in the range from
3137    insn INSN to and including the insn whose luid is END
3138    INSN must have an assigned luid (i.e., it must not have
3139    been previously created by loop.c).  */
3140
3141 static int
3142 labels_in_range_p (insn, end)
3143      rtx insn;
3144      int end;
3145 {
3146   while (insn && INSN_LUID (insn) <= end)
3147     {
3148       if (GET_CODE (insn) == CODE_LABEL)
3149         return 1;
3150       insn = NEXT_INSN (insn);
3151     }
3152
3153   return 0;
3154 }
3155
3156 /* Record that a memory reference X is being set.  */
3157
3158 static void
3159 note_addr_stored (x, y)
3160      rtx x;
3161      rtx y ATTRIBUTE_UNUSED;
3162 {
3163   if (x == 0 || GET_CODE (x) != MEM)
3164     return;
3165
3166   /* Count number of memory writes.
3167      This affects heuristics in strength_reduce.  */
3168   num_mem_sets++;
3169
3170   /* BLKmode MEM means all memory is clobbered.  */
3171   if (GET_MODE (x) == BLKmode)
3172     unknown_address_altered = 1;
3173
3174   if (unknown_address_altered)
3175     return;
3176
3177   loop_store_mems = gen_rtx_EXPR_LIST (VOIDmode, x, loop_store_mems);
3178 }
3179
3180 /* X is a value modified by an INSN that references a biv inside a loop
3181    exit test (ie, X is somehow related to the value of the biv).  If X
3182    is a pseudo that is used more than once, then the biv is (effectively)
3183    used more than once.  */
3184
3185 static void
3186 note_set_pseudo_multiple_uses (x, y)
3187      rtx x;
3188      rtx y ATTRIBUTE_UNUSED;
3189 {
3190   if (x == 0)
3191     return;
3192
3193   while (GET_CODE (x) == STRICT_LOW_PART
3194          || GET_CODE (x) == SIGN_EXTRACT
3195          || GET_CODE (x) == ZERO_EXTRACT
3196          || GET_CODE (x) == SUBREG)
3197     x = XEXP (x, 0);
3198
3199   if (GET_CODE (x) != REG || REGNO (x) < FIRST_PSEUDO_REGISTER)
3200     return;
3201
3202   /* If we do not have usage information, or if we know the register
3203      is used more than once, note that fact for check_dbra_loop.  */
3204   if (REGNO (x) >= max_reg_before_loop
3205       || ! VARRAY_RTX (reg_single_usage, REGNO (x))
3206       || VARRAY_RTX (reg_single_usage, REGNO (x)) == const0_rtx)
3207     note_set_pseudo_multiple_uses_retval = 1;
3208 }
3209 \f
3210 /* Return nonzero if the rtx X is invariant over the current loop.
3211
3212    The value is 2 if we refer to something only conditionally invariant.
3213
3214    If `unknown_address_altered' is nonzero, no memory ref is invariant.
3215    Otherwise, a memory ref is invariant if it does not conflict with
3216    anything stored in `loop_store_mems'.  */
3217
3218 int
3219 invariant_p (x)
3220      register rtx x;
3221 {
3222   register int i;
3223   register enum rtx_code code;
3224   register const char *fmt;
3225   int conditional = 0;
3226   rtx mem_list_entry;
3227
3228   if (x == 0)
3229     return 1;
3230   code = GET_CODE (x);
3231   switch (code)
3232     {
3233     case CONST_INT:
3234     case CONST_DOUBLE:
3235     case SYMBOL_REF:
3236     case CONST:
3237       return 1;
3238
3239     case LABEL_REF:
3240       /* A LABEL_REF is normally invariant, however, if we are unrolling
3241          loops, and this label is inside the loop, then it isn't invariant.
3242          This is because each unrolled copy of the loop body will have
3243          a copy of this label.  If this was invariant, then an insn loading
3244          the address of this label into a register might get moved outside
3245          the loop, and then each loop body would end up using the same label.
3246
3247          We don't know the loop bounds here though, so just fail for all
3248          labels.  */
3249       if (flag_unroll_loops)
3250         return 0;
3251       else
3252         return 1;
3253
3254     case PC:
3255     case CC0:
3256     case UNSPEC_VOLATILE:
3257       return 0;
3258
3259     case REG:
3260       /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3261          since the reg might be set by initialization within the loop.  */
3262
3263       if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3264            || x == arg_pointer_rtx)
3265           && ! current_function_has_nonlocal_goto)
3266         return 1;
3267
3268       if (this_loop_info.has_call
3269           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3270         return 0;
3271
3272       if (VARRAY_INT (set_in_loop, REGNO (x)) < 0)
3273         return 2;
3274
3275       return VARRAY_INT (set_in_loop, REGNO (x)) == 0;
3276
3277     case MEM:
3278       /* Volatile memory references must be rejected.  Do this before
3279          checking for read-only items, so that volatile read-only items
3280          will be rejected also.  */
3281       if (MEM_VOLATILE_P (x))
3282         return 0;
3283
3284       /* Read-only items (such as constants in a constant pool) are
3285          invariant if their address is.  */
3286       if (RTX_UNCHANGING_P (x))
3287         break;
3288
3289       /* If we had a subroutine call, any location in memory could have been
3290          clobbered.  */
3291       if (unknown_address_altered)
3292         return 0;
3293
3294       /* See if there is any dependence between a store and this load.  */
3295       mem_list_entry = loop_store_mems;
3296       while (mem_list_entry)
3297         {
3298           if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3299                                x, rtx_varies_p))
3300             return 0;
3301           mem_list_entry = XEXP (mem_list_entry, 1);
3302         }
3303
3304       /* It's not invalidated by a store in memory
3305          but we must still verify the address is invariant.  */
3306       break;
3307
3308     case ASM_OPERANDS:
3309       /* Don't mess with insns declared volatile.  */
3310       if (MEM_VOLATILE_P (x))
3311         return 0;
3312       break;
3313       
3314     default:
3315       break;
3316     }
3317
3318   fmt = GET_RTX_FORMAT (code);
3319   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3320     {
3321       if (fmt[i] == 'e')
3322         {
3323           int tem = invariant_p (XEXP (x, i));
3324           if (tem == 0)
3325             return 0;
3326           if (tem == 2)
3327             conditional = 1;
3328         }
3329       else if (fmt[i] == 'E')
3330         {
3331           register int j;
3332           for (j = 0; j < XVECLEN (x, i); j++)
3333             {
3334               int tem = invariant_p (XVECEXP (x, i, j));
3335               if (tem == 0)
3336                 return 0;
3337               if (tem == 2)
3338                 conditional = 1;
3339             }
3340
3341         }
3342     }
3343
3344   return 1 + conditional;
3345 }
3346
3347 \f
3348 /* Return nonzero if all the insns in the loop that set REG
3349    are INSN and the immediately following insns,
3350    and if each of those insns sets REG in an invariant way
3351    (not counting uses of REG in them).
3352
3353    The value is 2 if some of these insns are only conditionally invariant.
3354
3355    We assume that INSN itself is the first set of REG
3356    and that its source is invariant.  */
3357
3358 static int
3359 consec_sets_invariant_p (reg, n_sets, insn)
3360      int n_sets;
3361      rtx reg, insn;
3362 {
3363   register rtx p = insn;
3364   register int regno = REGNO (reg);
3365   rtx temp;
3366   /* Number of sets we have to insist on finding after INSN.  */
3367   int count = n_sets - 1;
3368   int old = VARRAY_INT (set_in_loop, regno);
3369   int value = 0;
3370   int this;
3371
3372   /* If N_SETS hit the limit, we can't rely on its value.  */
3373   if (n_sets == 127)
3374     return 0;
3375
3376   VARRAY_INT (set_in_loop, regno) = 0;
3377
3378   while (count > 0)
3379     {
3380       register enum rtx_code code;
3381       rtx set;
3382
3383       p = NEXT_INSN (p);
3384       code = GET_CODE (p);
3385
3386       /* If library call, skip to end of it.  */
3387       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3388         p = XEXP (temp, 0);
3389
3390       this = 0;
3391       if (code == INSN
3392           && (set = single_set (p))
3393           && GET_CODE (SET_DEST (set)) == REG
3394           && REGNO (SET_DEST (set)) == regno)
3395         {
3396           this = invariant_p (SET_SRC (set));
3397           if (this != 0)
3398             value |= this;
3399           else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3400             {
3401               /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3402                  If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3403                  notes are OK.  */
3404               this = (CONSTANT_P (XEXP (temp, 0))
3405                       || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3406                           && invariant_p (XEXP (temp, 0))));
3407               if (this != 0)
3408                 value |= this;
3409             }
3410         }
3411       if (this != 0)
3412         count--;
3413       else if (code != NOTE)
3414         {
3415           VARRAY_INT (set_in_loop, regno) = old;
3416           return 0;
3417         }
3418     }
3419
3420   VARRAY_INT (set_in_loop, regno) = old;
3421   /* If invariant_p ever returned 2, we return 2.  */
3422   return 1 + (value & 2);
3423 }
3424
3425 #if 0
3426 /* I don't think this condition is sufficient to allow INSN
3427    to be moved, so we no longer test it.  */
3428
3429 /* Return 1 if all insns in the basic block of INSN and following INSN
3430    that set REG are invariant according to TABLE.  */
3431
3432 static int
3433 all_sets_invariant_p (reg, insn, table)
3434      rtx reg, insn;
3435      short *table;
3436 {
3437   register rtx p = insn;
3438   register int regno = REGNO (reg);
3439
3440   while (1)
3441     {
3442       register enum rtx_code code;
3443       p = NEXT_INSN (p);
3444       code = GET_CODE (p);
3445       if (code == CODE_LABEL || code == JUMP_INSN)
3446         return 1;
3447       if (code == INSN && GET_CODE (PATTERN (p)) == SET
3448           && GET_CODE (SET_DEST (PATTERN (p))) == REG
3449           && REGNO (SET_DEST (PATTERN (p))) == regno)
3450         {
3451           if (!invariant_p (SET_SRC (PATTERN (p)), table))
3452             return 0;
3453         }
3454     }
3455 }
3456 #endif /* 0 */
3457 \f
3458 /* Look at all uses (not sets) of registers in X.  For each, if it is
3459    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3460    a different insn, set USAGE[REGNO] to const0_rtx.  */
3461
3462 static void
3463 find_single_use_in_loop (insn, x, usage)
3464      rtx insn;
3465      rtx x;
3466      varray_type usage;
3467 {
3468   enum rtx_code code = GET_CODE (x);
3469   const char *fmt = GET_RTX_FORMAT (code);
3470   int i, j;
3471
3472   if (code == REG)
3473     VARRAY_RTX (usage, REGNO (x))
3474       = (VARRAY_RTX (usage, REGNO (x)) != 0 
3475          && VARRAY_RTX (usage, REGNO (x)) != insn)
3476         ? const0_rtx : insn;
3477
3478   else if (code == SET)
3479     {
3480       /* Don't count SET_DEST if it is a REG; otherwise count things
3481          in SET_DEST because if a register is partially modified, it won't
3482          show up as a potential movable so we don't care how USAGE is set 
3483          for it.  */
3484       if (GET_CODE (SET_DEST (x)) != REG)
3485         find_single_use_in_loop (insn, SET_DEST (x), usage);
3486       find_single_use_in_loop (insn, SET_SRC (x), usage);
3487     }
3488   else
3489     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3490       {
3491         if (fmt[i] == 'e' && XEXP (x, i) != 0)
3492           find_single_use_in_loop (insn, XEXP (x, i), usage);
3493         else if (fmt[i] == 'E')
3494           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3495             find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
3496       }
3497 }
3498 \f
3499 /* Count and record any set in X which is contained in INSN.  Update
3500    MAY_NOT_MOVE and LAST_SET for any register set in X.  */
3501
3502 static void
3503 count_one_set (insn, x, may_not_move, last_set)
3504      rtx insn, x;
3505      varray_type may_not_move;
3506      rtx *last_set;
3507 {
3508   if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3509     /* Don't move a reg that has an explicit clobber.
3510        It's not worth the pain to try to do it correctly.  */
3511     VARRAY_CHAR (may_not_move, REGNO (XEXP (x, 0))) = 1;
3512
3513   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3514     {
3515       rtx dest = SET_DEST (x);
3516       while (GET_CODE (dest) == SUBREG
3517              || GET_CODE (dest) == ZERO_EXTRACT
3518              || GET_CODE (dest) == SIGN_EXTRACT
3519              || GET_CODE (dest) == STRICT_LOW_PART)
3520         dest = XEXP (dest, 0);
3521       if (GET_CODE (dest) == REG)
3522         {
3523           register int regno = REGNO (dest);
3524           /* If this is the first setting of this reg
3525              in current basic block, and it was set before,
3526              it must be set in two basic blocks, so it cannot
3527              be moved out of the loop.  */
3528           if (VARRAY_INT (set_in_loop, regno) > 0 
3529               && last_set[regno] == 0)
3530             VARRAY_CHAR (may_not_move, regno) = 1;
3531           /* If this is not first setting in current basic block,
3532              see if reg was used in between previous one and this.
3533              If so, neither one can be moved.  */
3534           if (last_set[regno] != 0
3535               && reg_used_between_p (dest, last_set[regno], insn))
3536             VARRAY_CHAR (may_not_move, regno) = 1;
3537           if (VARRAY_INT (set_in_loop, regno) < 127)
3538             ++VARRAY_INT (set_in_loop, regno);
3539           last_set[regno] = insn;
3540         }
3541     }
3542 }
3543
3544 /* Increment SET_IN_LOOP at the index of each register
3545    that is modified by an insn between FROM and TO.
3546    If the value of an element of SET_IN_LOOP becomes 127 or more,
3547    stop incrementing it, to avoid overflow.
3548
3549    Store in SINGLE_USAGE[I] the single insn in which register I is
3550    used, if it is only used once.  Otherwise, it is set to 0 (for no
3551    uses) or const0_rtx for more than one use.  This parameter may be zero,
3552    in which case this processing is not done.
3553
3554    Store in *COUNT_PTR the number of actual instruction
3555    in the loop.  We use this to decide what is worth moving out.  */
3556
3557 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
3558    In that case, it is the insn that last set reg n.  */
3559
3560 static void
3561 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
3562      register rtx from, to;
3563      varray_type may_not_move;
3564      varray_type single_usage;
3565      int *count_ptr;
3566      int nregs;
3567 {
3568   register rtx *last_set = (rtx *) alloca (nregs * sizeof (rtx));
3569   register rtx insn;
3570   register int count = 0;
3571
3572   bzero ((char *) last_set, nregs * sizeof (rtx));
3573   for (insn = from; insn != to; insn = NEXT_INSN (insn))
3574     {
3575       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
3576         {
3577           ++count;
3578
3579           /* Record registers that have exactly one use.  */
3580           find_single_use_in_loop (insn, PATTERN (insn), single_usage);
3581
3582           /* Include uses in REG_EQUAL notes.  */
3583           if (REG_NOTES (insn))
3584             find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
3585
3586           if (GET_CODE (PATTERN (insn)) == SET
3587               || GET_CODE (PATTERN (insn)) == CLOBBER)
3588             count_one_set (insn, PATTERN (insn), may_not_move, last_set);
3589           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
3590             {
3591               register int i;
3592               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
3593                 count_one_set (insn, XVECEXP (PATTERN (insn), 0, i),
3594                                may_not_move, last_set);
3595             }
3596         }
3597
3598       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
3599         bzero ((char *) last_set, nregs * sizeof (rtx));
3600     }
3601   *count_ptr = count;
3602 }
3603 \f
3604 /* Given a loop that is bounded by LOOP_START and LOOP_END
3605    and that is entered at SCAN_START,
3606    return 1 if the register set in SET contained in insn INSN is used by
3607    any insn that precedes INSN in cyclic order starting
3608    from the loop entry point.
3609
3610    We don't want to use INSN_LUID here because if we restrict INSN to those
3611    that have a valid INSN_LUID, it means we cannot move an invariant out
3612    from an inner loop past two loops.  */
3613
3614 static int
3615 loop_reg_used_before_p (set, insn, loop_start, scan_start, loop_end)
3616      rtx set, insn, loop_start, scan_start, loop_end;
3617 {
3618   rtx reg = SET_DEST (set);
3619   rtx p;
3620
3621   /* Scan forward checking for register usage.  If we hit INSN, we
3622      are done.  Otherwise, if we hit LOOP_END, wrap around to LOOP_START.  */
3623   for (p = scan_start; p != insn; p = NEXT_INSN (p))
3624     {
3625       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
3626           && reg_overlap_mentioned_p (reg, PATTERN (p)))
3627         return 1;
3628
3629       if (p == loop_end)
3630         p = loop_start;
3631     }
3632
3633   return 0;
3634 }
3635 \f
3636 /* A "basic induction variable" or biv is a pseudo reg that is set
3637    (within this loop) only by incrementing or decrementing it.  */
3638 /* A "general induction variable" or giv is a pseudo reg whose
3639    value is a linear function of a biv.  */
3640
3641 /* Bivs are recognized by `basic_induction_var';
3642    Givs by `general_induction_var'.  */
3643
3644 /* Indexed by register number, indicates whether or not register is an
3645    induction variable, and if so what type.  */
3646
3647 varray_type reg_iv_type;
3648
3649 /* Indexed by register number, contains pointer to `struct induction'
3650    if register is an induction variable.  This holds general info for
3651    all induction variables.  */
3652
3653 varray_type reg_iv_info;
3654
3655 /* Indexed by register number, contains pointer to `struct iv_class'
3656    if register is a basic induction variable.  This holds info describing
3657    the class (a related group) of induction variables that the biv belongs
3658    to.  */
3659
3660 struct iv_class **reg_biv_class;
3661
3662 /* The head of a list which links together (via the next field)
3663    every iv class for the current loop.  */
3664
3665 struct iv_class *loop_iv_list;
3666
3667 /* Givs made from biv increments are always splittable for loop unrolling.
3668    Since there is no regscan info for them, we have to keep track of them
3669    separately.  */
3670 int first_increment_giv, last_increment_giv;
3671
3672 /* Communication with routines called via `note_stores'.  */
3673
3674 static rtx note_insn;
3675
3676 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs.  */
3677
3678 static rtx addr_placeholder;
3679
3680 /* ??? Unfinished optimizations, and possible future optimizations,
3681    for the strength reduction code.  */
3682
3683 /* ??? The interaction of biv elimination, and recognition of 'constant'
3684    bivs, may cause problems.  */
3685
3686 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3687    performance problems.
3688
3689    Perhaps don't eliminate things that can be combined with an addressing
3690    mode.  Find all givs that have the same biv, mult_val, and add_val;
3691    then for each giv, check to see if its only use dies in a following
3692    memory address.  If so, generate a new memory address and check to see
3693    if it is valid.   If it is valid, then store the modified memory address,
3694    otherwise, mark the giv as not done so that it will get its own iv.  */
3695
3696 /* ??? Could try to optimize branches when it is known that a biv is always
3697    positive.  */
3698
3699 /* ??? When replace a biv in a compare insn, we should replace with closest
3700    giv so that an optimized branch can still be recognized by the combiner,
3701    e.g. the VAX acb insn.  */
3702
3703 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3704    was rerun in loop_optimize whenever a register was added or moved.
3705    Also, some of the optimizations could be a little less conservative.  */
3706 \f
3707 /* Perform strength reduction and induction variable elimination.  
3708
3709    Pseudo registers created during this function will be beyond the last
3710    valid index in several tables including n_times_set and regno_last_uid.
3711    This does not cause a problem here, because the added registers cannot be
3712    givs outside of their loop, and hence will never be reconsidered.
3713    But scan_loop must check regnos to make sure they are in bounds. 
3714    
3715    SCAN_START is the first instruction in the loop, as the loop would
3716    actually be executed.  END is the NOTE_INSN_LOOP_END.  LOOP_TOP is
3717    the first instruction in the loop, as it is layed out in the
3718    instruction stream.  LOOP_START is the NOTE_INSN_LOOP_BEG.
3719    LOOP_CONT is the NOTE_INSN_LOOP_CONT.  */
3720
3721 static void
3722 strength_reduce (scan_start, end, loop_top, insn_count,
3723                  loop_start, loop_end, loop_info, loop_cont, unroll_p, bct_p)
3724      rtx scan_start;
3725      rtx end;
3726      rtx loop_top;
3727      int insn_count;
3728      rtx loop_start;
3729      rtx loop_end;
3730      struct loop_info *loop_info;
3731      rtx loop_cont;
3732      int unroll_p, bct_p ATTRIBUTE_UNUSED;
3733 {
3734   rtx p;
3735   rtx set;
3736   rtx inc_val;
3737   rtx mult_val;
3738   rtx dest_reg;
3739   rtx *location;
3740   /* This is 1 if current insn is not executed at least once for every loop
3741      iteration.  */
3742   int not_every_iteration = 0;
3743   /* This is 1 if current insn may be executed more than once for every
3744      loop iteration.  */
3745   int maybe_multiple = 0;
3746   /* This is 1 if we have past a branch back to the top of the loop
3747      (aka a loop latch).  */
3748   int past_loop_latch = 0;
3749   /* Temporary list pointers for traversing loop_iv_list.  */
3750   struct iv_class *bl, **backbl;
3751   /* Ratio of extra register life span we can justify
3752      for saving an instruction.  More if loop doesn't call subroutines
3753      since in that case saving an insn makes more difference
3754      and more registers are available.  */
3755   /* ??? could set this to last value of threshold in move_movables */
3756   int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3757   /* Map of pseudo-register replacements.  */
3758   rtx *reg_map;
3759   int reg_map_size;
3760   int call_seen;
3761   rtx test;
3762   rtx end_insert_before;
3763   int loop_depth = 0;
3764   int n_extra_increment;
3765   int unrolled_insn_copies = 0;
3766
3767   /* If scan_start points to the loop exit test, we have to be wary of
3768      subversive use of gotos inside expression statements.  */
3769   if (prev_nonnote_insn (scan_start) != prev_nonnote_insn (loop_start))
3770     maybe_multiple = back_branch_in_range_p (scan_start, loop_start, loop_end);
3771
3772   VARRAY_INT_INIT (reg_iv_type, max_reg_before_loop, "reg_iv_type");
3773   VARRAY_GENERIC_PTR_INIT (reg_iv_info, max_reg_before_loop, "reg_iv_info");
3774   reg_biv_class = (struct iv_class **)
3775     alloca (max_reg_before_loop * sizeof (struct iv_class *));
3776   bzero ((char *) reg_biv_class, (max_reg_before_loop
3777                                   * sizeof (struct iv_class *)));
3778
3779   loop_iv_list = 0;
3780   addr_placeholder = gen_reg_rtx (Pmode);
3781
3782   /* Save insn immediately after the loop_end.  Insns inserted after loop_end
3783      must be put before this insn, so that they will appear in the right
3784      order (i.e. loop order). 
3785
3786      If loop_end is the end of the current function, then emit a 
3787      NOTE_INSN_DELETED after loop_end and set end_insert_before to the
3788      dummy note insn.  */
3789   if (NEXT_INSN (loop_end) != 0)
3790     end_insert_before = NEXT_INSN (loop_end);
3791   else
3792     end_insert_before = emit_note_after (NOTE_INSN_DELETED, loop_end);
3793
3794   /* Scan through loop to find all possible bivs.  */
3795
3796   for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top);
3797        p != NULL_RTX;
3798        p = next_insn_in_loop (p, scan_start, end, loop_top))
3799     {
3800       if (GET_CODE (p) == INSN
3801           && (set = single_set (p))
3802           && GET_CODE (SET_DEST (set)) == REG)
3803         {
3804           dest_reg = SET_DEST (set);
3805           if (REGNO (dest_reg) < max_reg_before_loop
3806               && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
3807               && REG_IV_TYPE (REGNO (dest_reg)) != NOT_BASIC_INDUCT)
3808             {
3809               if (basic_induction_var (SET_SRC (set), GET_MODE (SET_SRC (set)),
3810                                        dest_reg, p, &inc_val, &mult_val,
3811                                        &location))
3812                 {
3813                   /* It is a possible basic induction variable.
3814                      Create and initialize an induction structure for it.  */
3815
3816                   struct induction *v
3817                     = (struct induction *) alloca (sizeof (struct induction));
3818
3819                   record_biv (v, p, dest_reg, inc_val, mult_val, location,
3820                               not_every_iteration, maybe_multiple);
3821                   REG_IV_TYPE (REGNO (dest_reg)) = BASIC_INDUCT;
3822                 }
3823               else if (REGNO (dest_reg) < max_reg_before_loop)
3824                 REG_IV_TYPE (REGNO (dest_reg)) = NOT_BASIC_INDUCT;
3825             }
3826         }
3827
3828       /* Past CODE_LABEL, we get to insns that may be executed multiple
3829          times.  The only way we can be sure that they can't is if every
3830          jump insn between here and the end of the loop either
3831          returns, exits the loop, is a jump to a location that is still
3832          behind the label, or is a jump to the loop start.  */
3833
3834       if (GET_CODE (p) == CODE_LABEL)
3835         {
3836           rtx insn = p;
3837
3838           maybe_multiple = 0;
3839
3840           while (1)
3841             {
3842               insn = NEXT_INSN (insn);
3843               if (insn == scan_start)
3844                 break;
3845               if (insn == end)
3846                 {
3847                   if (loop_top != 0)
3848                     insn = loop_top;
3849                   else
3850                     break;
3851                   if (insn == scan_start)
3852                     break;
3853                 }
3854
3855               if (GET_CODE (insn) == JUMP_INSN
3856                   && GET_CODE (PATTERN (insn)) != RETURN
3857                   && (! condjump_p (insn)
3858                       || (JUMP_LABEL (insn) != 0
3859                           && JUMP_LABEL (insn) != scan_start
3860                           && ! loop_insn_first_p (p, JUMP_LABEL (insn)))))
3861                 {
3862                   maybe_multiple = 1;
3863                   break;
3864                 }
3865             }
3866         }
3867
3868       /* Past a jump, we get to insns for which we can't count
3869          on whether they will be executed during each iteration.  */
3870       /* This code appears twice in strength_reduce.  There is also similar
3871          code in scan_loop.  */
3872       if (GET_CODE (p) == JUMP_INSN
3873           /* If we enter the loop in the middle, and scan around to the
3874              beginning, don't set not_every_iteration for that.
3875              This can be any kind of jump, since we want to know if insns
3876              will be executed if the loop is executed.  */
3877           && ! (JUMP_LABEL (p) == loop_top
3878                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3879                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3880         {
3881           rtx label = 0;
3882
3883           /* If this is a jump outside the loop, then it also doesn't
3884              matter.  Check to see if the target of this branch is on the
3885              loop_number_exits_labels list.  */
3886              
3887           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
3888                label;
3889                label = LABEL_NEXTREF (label))
3890             if (XEXP (label, 0) == JUMP_LABEL (p))
3891               break;
3892
3893           if (! label)
3894             not_every_iteration = 1;
3895         }
3896
3897       else if (GET_CODE (p) == NOTE)
3898         {
3899           /* At the virtual top of a converted loop, insns are again known to
3900              be executed each iteration: logically, the loop begins here
3901              even though the exit code has been duplicated.
3902
3903              Insns are also again known to be executed each iteration at
3904              the LOOP_CONT note.  */
3905           if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
3906                || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
3907               && loop_depth == 0)
3908             not_every_iteration = 0;
3909           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3910             loop_depth++;
3911           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3912             loop_depth--;
3913         }
3914
3915       /* Note if we pass a loop latch.  If we do, then we can not clear
3916          NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
3917          a loop since a jump before the last CODE_LABEL may have started
3918          a new loop iteration.
3919
3920          Note that LOOP_TOP is only set for rotated loops and we need
3921          this check for all loops, so compare against the CODE_LABEL
3922          which immediately follows LOOP_START.  */
3923       if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == NEXT_INSN (loop_start))
3924         past_loop_latch = 1;
3925
3926       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3927          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3928          or not an insn is known to be executed each iteration of the
3929          loop, whether or not any iterations are known to occur.
3930
3931          Therefore, if we have just passed a label and have no more labels
3932          between here and the test insn of the loop, and we have not passed
3933          a jump to the top of the loop, then we know these insns will be
3934          executed each iteration.  */
3935
3936       if (not_every_iteration 
3937           && ! past_loop_latch
3938           && GET_CODE (p) == CODE_LABEL
3939           && no_labels_between_p (p, loop_end)
3940           && loop_insn_first_p (p, loop_cont))
3941         not_every_iteration = 0;
3942     }
3943
3944   /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3945      Make a sanity check against n_times_set.  */
3946   for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3947     {
3948       if (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3949           /* Above happens if register modified by subreg, etc.  */
3950           /* Make sure it is not recognized as a basic induction var: */
3951           || VARRAY_INT (n_times_set, bl->regno) != bl->biv_count
3952           /* If never incremented, it is invariant that we decided not to
3953              move.  So leave it alone.  */
3954           || ! bl->incremented)
3955         {
3956           if (loop_dump_stream)
3957             fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3958                      bl->regno,
3959                      (REG_IV_TYPE (bl->regno) != BASIC_INDUCT
3960                       ? "not induction variable"
3961                       : (! bl->incremented ? "never incremented"
3962                          : "count error")));
3963           
3964           REG_IV_TYPE (bl->regno) = NOT_BASIC_INDUCT;
3965           *backbl = bl->next;
3966         }
3967       else
3968         {
3969           backbl = &bl->next;
3970
3971           if (loop_dump_stream)
3972             fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3973         }
3974     }
3975
3976   /* Exit if there are no bivs.  */
3977   if (! loop_iv_list)
3978     {
3979       /* Can still unroll the loop anyways, but indicate that there is no
3980          strength reduction info available.  */
3981       if (unroll_p)
3982         unroll_loop (loop_end, insn_count, loop_start, end_insert_before,
3983                      loop_info, 0);
3984
3985       goto egress;
3986     }
3987
3988   /* Find initial value for each biv by searching backwards from loop_start,
3989      halting at first label.  Also record any test condition.  */
3990
3991   call_seen = 0;
3992   for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3993     {
3994       note_insn = p;
3995
3996       if (GET_CODE (p) == CALL_INSN)
3997         call_seen = 1;
3998
3999       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4000           || GET_CODE (p) == CALL_INSN)
4001         note_stores (PATTERN (p), record_initial);
4002
4003       /* Record any test of a biv that branches around the loop if no store
4004          between it and the start of loop.  We only care about tests with
4005          constants and registers and only certain of those.  */
4006       if (GET_CODE (p) == JUMP_INSN
4007           && JUMP_LABEL (p) != 0
4008           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
4009           && (test = get_condition_for_loop (p)) != 0
4010           && GET_CODE (XEXP (test, 0)) == REG
4011           && REGNO (XEXP (test, 0)) < max_reg_before_loop
4012           && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
4013           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
4014           && bl->init_insn == 0)
4015         {
4016           /* If an NE test, we have an initial value!  */
4017           if (GET_CODE (test) == NE)
4018             {
4019               bl->init_insn = p;
4020               bl->init_set = gen_rtx_SET (VOIDmode,
4021                                           XEXP (test, 0), XEXP (test, 1));
4022             }
4023           else
4024             bl->initial_test = test;
4025         }
4026     }
4027
4028   /* Look at the each biv and see if we can say anything better about its
4029      initial value from any initializing insns set up above.  (This is done
4030      in two passes to avoid missing SETs in a PARALLEL.)  */
4031   for (backbl = &loop_iv_list; (bl = *backbl); backbl = &bl->next)
4032     {
4033       rtx src;
4034       rtx note;
4035
4036       if (! bl->init_insn)
4037         continue;
4038
4039       /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4040          is a constant, use the value of that.  */
4041       if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4042            && CONSTANT_P (XEXP (note, 0)))
4043           || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4044               && CONSTANT_P (XEXP (note, 0))))
4045         src = XEXP (note, 0);
4046       else
4047         src = SET_SRC (bl->init_set);
4048
4049       if (loop_dump_stream)
4050         fprintf (loop_dump_stream,
4051                  "Biv %d initialized at insn %d: initial value ",
4052                  bl->regno, INSN_UID (bl->init_insn));
4053
4054       if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4055            || GET_MODE (src) == VOIDmode)
4056           && valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
4057         {
4058           bl->initial_value = src;
4059
4060           if (loop_dump_stream)
4061             {
4062               if (GET_CODE (src) == CONST_INT)
4063                 {
4064                   fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (src));
4065                   fputc ('\n', loop_dump_stream);
4066                 }
4067               else
4068                 {
4069                   print_rtl (loop_dump_stream, src);
4070                   fprintf (loop_dump_stream, "\n");
4071                 }
4072             }
4073         }
4074       else
4075         {
4076           struct iv_class *bl2 = 0;
4077           rtx increment = NULL_RTX;
4078
4079           /* Biv initial value is not a simple move.  If it is the sum of
4080              another biv and a constant, check if both bivs are incremented
4081              in lockstep.  Then we are actually looking at a giv.
4082              For simplicity, we only handle the case where there is but a
4083              single increment, and the register is not used elsewhere.  */
4084           if (bl->biv_count == 1
4085               && bl->regno < max_reg_before_loop
4086               && uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4087               && GET_CODE (src) == PLUS
4088               && GET_CODE (XEXP (src, 0)) == REG
4089               && CONSTANT_P (XEXP (src, 1))
4090               && ((increment = biv_total_increment (bl, loop_start, loop_end))
4091                   != NULL_RTX))
4092             {
4093               int regno = REGNO (XEXP (src, 0));
4094
4095               for (bl2 = loop_iv_list; bl2; bl2 = bl2->next)
4096                 if (bl2->regno == regno)
4097                   break;
4098             }
4099         
4100           /* Now, can we transform this biv into a giv?  */
4101           if (bl2
4102               && bl2->biv_count == 1
4103               && rtx_equal_p (increment,
4104                               biv_total_increment (bl2, loop_start, loop_end))
4105               /* init_insn is only set to insns that are before loop_start
4106                  without any intervening labels.  */
4107               && ! reg_set_between_p (bl2->biv->src_reg,
4108                                       PREV_INSN (bl->init_insn), loop_start)
4109               /* The register from BL2 must be set before the register from
4110                  BL is set, or we must be able to move the latter set after
4111                  the former set.  Currently there can't be any labels
4112                  in-between when biv_total_increment returns nonzero both times
4113                  but we test it here in case some day some real cfg analysis
4114                  gets used to set always_computable.  */
4115               && (loop_insn_first_p (bl2->biv->insn, bl->biv->insn)
4116                   ? no_labels_between_p (bl2->biv->insn, bl->biv->insn)
4117                   : (! reg_used_between_p (bl->biv->src_reg, bl->biv->insn,
4118                                            bl2->biv->insn)
4119                      && no_jumps_between_p (bl->biv->insn, bl2->biv->insn)))
4120               && validate_change (bl->biv->insn,
4121                                   &SET_SRC (single_set (bl->biv->insn)),
4122                                   copy_rtx (src), 0))
4123             {
4124               int loop_num = uid_loop_num[INSN_UID (loop_start)];
4125               rtx dominator = loop_number_cont_dominator[loop_num];
4126               rtx giv = bl->biv->src_reg;
4127               rtx giv_insn = bl->biv->insn;
4128               rtx after_giv = NEXT_INSN (giv_insn);
4129
4130               if (loop_dump_stream)
4131                 fprintf (loop_dump_stream, "is giv of biv %d\n", bl2->regno);
4132               /* Let this giv be discovered by the generic code.  */
4133               REG_IV_TYPE (bl->regno) = UNKNOWN_INDUCT;
4134               reg_biv_class[bl->regno] = NULL_PTR;
4135               /* We can get better optimization if we can move the giv setting
4136                  before the first giv use.  */
4137               if (dominator
4138                   && ! loop_insn_first_p (dominator, scan_start)
4139                   && ! reg_set_between_p (bl2->biv->src_reg, loop_start,
4140                                           dominator)
4141                   && ! reg_used_between_p (giv, loop_start, dominator)
4142                   && ! reg_used_between_p (giv, giv_insn, loop_end))
4143                 {
4144                   rtx p;
4145                   rtx next;
4146
4147                   for (next = NEXT_INSN (dominator); ; next = NEXT_INSN (next))
4148                     {
4149                       if ((GET_RTX_CLASS (GET_CODE (next)) == 'i'
4150                            && (reg_mentioned_p (giv, PATTERN (next))
4151                                || reg_set_p (bl2->biv->src_reg, next)))
4152                           || GET_CODE (next) == JUMP_INSN)
4153                         break;
4154 #ifdef HAVE_cc0
4155                       if (GET_RTX_CLASS (GET_CODE (next)) != 'i'
4156                           || ! sets_cc0_p (PATTERN (next)))
4157 #endif
4158                         dominator = next;
4159                     }
4160                   if (loop_dump_stream)
4161                     fprintf (loop_dump_stream, "move after insn %d\n",
4162                              INSN_UID (dominator));
4163                   /* Avoid problems with luids by actually moving the insn
4164                      and adjusting all luids in the range.  */
4165                   reorder_insns (giv_insn, giv_insn, dominator);
4166                   for (p = dominator; INSN_UID (p) >= max_uid_for_loop; )
4167                     p = PREV_INSN (p);
4168                   compute_luids (giv_insn, after_giv, INSN_LUID (p));
4169                   /* If the only purpose of the init insn is to initialize
4170                      this giv, delete it.  */
4171                   if (single_set (bl->init_insn)
4172                       && ! reg_used_between_p (giv, bl->init_insn, loop_start))
4173                     delete_insn (bl->init_insn);
4174                 }
4175               else if (! loop_insn_first_p (bl2->biv->insn, bl->biv->insn))
4176                 {
4177                   rtx p = PREV_INSN (giv_insn);
4178                   while (INSN_UID (p) >= max_uid_for_loop)
4179                     p = PREV_INSN (p);
4180                   reorder_insns (giv_insn, giv_insn, bl2->biv->insn);
4181                   compute_luids (after_giv, NEXT_INSN (giv_insn),
4182                                  INSN_LUID (p));
4183                 }
4184               /* Remove this biv from the chain.  */
4185               if (bl->next)
4186                 {
4187                   /* We move the following giv from *bl->next into *bl.
4188                      We have to update reg_biv_class for that moved biv
4189                      to point to its new address.  */
4190                   *bl = *bl->next;
4191                   reg_biv_class[bl->regno] = bl;
4192                 }
4193               else
4194                 {
4195                   *backbl = 0;
4196                   break;
4197                 }
4198             }
4199
4200           /* If we can't make it a giv,
4201              let biv keep initial value of "itself".  */
4202           else if (loop_dump_stream)
4203             fprintf (loop_dump_stream, "is complex\n");
4204         }
4205     }
4206
4207   /* If a biv is unconditionally incremented several times in a row, convert
4208      all but the last increment into a giv.  */
4209
4210   /* Get an upper bound for the number of registers
4211      we might have after all bivs have been processed.  */
4212   first_increment_giv = max_reg_num ();
4213   for (n_extra_increment = 0, bl = loop_iv_list; bl; bl = bl->next)
4214     n_extra_increment += bl->biv_count - 1;
4215
4216   /* If the loop contains volatile memory references do not allow any
4217      replacements to take place, since this could loose the volatile markers.  */
4218   if (n_extra_increment  && ! loop_info->has_volatile)
4219     {
4220       int nregs = first_increment_giv + n_extra_increment;
4221
4222       /* Reallocate reg_iv_type and reg_iv_info.  */
4223       VARRAY_GROW (reg_iv_type, nregs);
4224       VARRAY_GROW (reg_iv_info, nregs);
4225
4226       for (bl = loop_iv_list; bl; bl = bl->next)
4227         {
4228           struct induction **vp, *v, *next;
4229           int biv_dead_after_loop = 0;
4230
4231           /* The biv increments lists are in reverse order.  Fix this first.  */
4232           for (v = bl->biv, bl->biv = 0; v; v = next)
4233             {
4234               next = v->next_iv;
4235               v->next_iv = bl->biv;
4236               bl->biv = v;
4237             }
4238
4239           /* We must guard against the case that an early exit between v->insn
4240              and next->insn leaves the biv live after the loop, since that
4241              would mean that we'd be missing an increment for the final
4242              value.  The following test to set biv_dead_after_loop is like
4243              the first part of the test to set bl->eliminable.
4244              We don't check here if we can calculate the final value, since
4245              this can't succeed if we already know that there is a jump
4246              between v->insn and next->insn, yet next->always_executed is
4247              set and next->maybe_multiple is cleared.  Such a combination
4248              implies that the jump destination is outside the loop.
4249              If we want to make this check more sophisticated, we should
4250              check each branch between v->insn and next->insn individually
4251              to see if the biv is dead at its destination.  */
4252
4253           if (uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4254               && bl->init_insn
4255               && INSN_UID (bl->init_insn) < max_uid_for_loop
4256               && (uid_luid[REGNO_FIRST_UID (bl->regno)]
4257                   >= INSN_LUID (bl->init_insn))
4258 #ifdef HAVE_decrement_and_branch_until_zero
4259               && ! bl->nonneg
4260 #endif
4261               && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4262             biv_dead_after_loop = 1;
4263
4264           for (vp = &bl->biv, next = *vp; v = next, next = v->next_iv;)
4265             {
4266               HOST_WIDE_INT offset;
4267               rtx set, add_val, old_reg, dest_reg, last_use_insn, note;
4268               int old_regno, new_regno;
4269
4270               if (! v->always_executed
4271                   || v->maybe_multiple
4272                   || GET_CODE (v->add_val) != CONST_INT
4273                   || ! next->always_executed
4274                   || next->maybe_multiple
4275                   || ! CONSTANT_P (next->add_val)
4276                   || v->mult_val != const1_rtx
4277                   || next->mult_val != const1_rtx
4278                   || ! (biv_dead_after_loop
4279                         || no_jumps_between_p (v->insn, next->insn)))
4280                 {
4281                   vp = &v->next_iv;
4282                   continue;
4283                 }
4284               offset = INTVAL (v->add_val);
4285               set = single_set (v->insn);
4286               add_val = plus_constant (next->add_val, offset);
4287               old_reg = v->dest_reg;
4288               dest_reg = gen_reg_rtx (v->mode);
4289     
4290               /* Unlike reg_iv_type / reg_iv_info, the other three arrays
4291                  have been allocated with some slop space, so we may not
4292                  actually need to reallocate them.  If we do, the following
4293                  if statement will be executed just once in this loop.  */
4294               if ((unsigned) max_reg_num () > n_times_set->num_elements)
4295                 {
4296                   /* Grow all the remaining arrays.  */
4297                   VARRAY_GROW (set_in_loop, nregs);
4298                   VARRAY_GROW (n_times_set, nregs);
4299                   VARRAY_GROW (may_not_optimize, nregs);
4300                   VARRAY_GROW (reg_single_usage, nregs);
4301                 }
4302     
4303               if (! validate_change (next->insn, next->location, add_val, 0))
4304                 {
4305                   vp = &v->next_iv;
4306                   continue;
4307                 }
4308
4309               /* Here we can try to eliminate the increment by combining
4310                  it into the uses.  */
4311
4312               /* Set last_use_insn so that we can check against it.  */
4313
4314               for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4315                    p != next->insn;
4316                    p = next_insn_in_loop (p, scan_start, end, loop_top))
4317                 {
4318                   if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
4319                     continue;
4320                   if (reg_mentioned_p (old_reg, PATTERN (p)))
4321                     {
4322                       last_use_insn = p;
4323                     }
4324                 }
4325
4326               /* If we can't get the LUIDs for the insns, we can't
4327                  calculate the lifetime.  This is likely from unrolling
4328                  of an inner loop, so there is little point in making this
4329                  a DEST_REG giv anyways.  */
4330               if (INSN_UID (v->insn) >= max_uid_for_loop
4331                   || INSN_UID (last_use_insn) >= max_uid_for_loop
4332                   || ! validate_change (v->insn, &SET_DEST (set), dest_reg, 0))
4333                 {
4334                   /* Change the increment at NEXT back to what it was.  */
4335                   if (! validate_change (next->insn, next->location,
4336                       next->add_val, 0))
4337                     abort ();
4338                   vp = &v->next_iv;
4339                   continue;
4340                 }
4341               next->add_val = add_val;
4342               v->dest_reg = dest_reg;
4343               v->giv_type = DEST_REG;
4344               v->location = &SET_SRC (set);
4345               v->cant_derive = 0;
4346               v->combined_with = 0;
4347               v->maybe_dead = 0;
4348               v->derive_adjustment = 0;
4349               v->same = 0;
4350               v->ignore = 0;
4351               v->new_reg = 0;
4352               v->final_value = 0;
4353               v->same_insn = 0;
4354               v->auto_inc_opt = 0;
4355               v->unrolled = 0;
4356               v->shared = 0;
4357               v->derived_from = 0;
4358               v->always_computable = 1;
4359               v->always_executed = 1;
4360               v->replaceable = 1;
4361               v->no_const_addval = 0;
4362     
4363               old_regno = REGNO (old_reg);
4364               new_regno = REGNO (dest_reg);
4365               VARRAY_INT (set_in_loop, old_regno)--;
4366               VARRAY_INT (set_in_loop, new_regno) = 1;
4367               VARRAY_INT (n_times_set, old_regno)--;
4368               VARRAY_INT (n_times_set, new_regno) = 1;
4369               VARRAY_CHAR (may_not_optimize, new_regno) = 0;
4370     
4371               REG_IV_TYPE (new_regno) = GENERAL_INDUCT;
4372               REG_IV_INFO (new_regno) = v;
4373
4374               /* If next_insn has a REG_EQUAL note that mentiones OLD_REG,
4375                  it must be replaced.  */
4376               note = find_reg_note (next->insn, REG_EQUAL, NULL_RTX);
4377               if (note && reg_mentioned_p (old_reg, XEXP (note, 0)))
4378                 XEXP (note, 0) = copy_rtx (SET_SRC (single_set (next->insn)));
4379
4380               /* Remove the increment from the list of biv increments,
4381                  and record it as a giv.  */
4382               *vp = next;
4383               bl->biv_count--;
4384               v->next_iv = bl->giv;
4385               bl->giv = v;
4386               bl->giv_count++;
4387               v->benefit = rtx_cost (SET_SRC (set), SET);
4388               bl->total_benefit += v->benefit;
4389     
4390               /* Now replace the biv with DEST_REG in all insns between
4391                  the replaced increment and the next increment, and
4392                  remember the last insn that needed a replacement.  */
4393               for (last_use_insn = v->insn, p = NEXT_INSN (v->insn);
4394                    p != next->insn;
4395                    p = next_insn_in_loop (p, scan_start, end, loop_top))
4396                 {
4397                   rtx note;
4398     
4399                   if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
4400                     continue;
4401                   if (reg_mentioned_p (old_reg, PATTERN (p)))
4402                     {
4403                       last_use_insn = p;
4404                       if (! validate_replace_rtx (old_reg, dest_reg, p))
4405                         abort ();
4406                     }
4407                   for (note = REG_NOTES (p); note; note = XEXP (note, 1))
4408                     {
4409                       if (GET_CODE (note) == EXPR_LIST)
4410                         XEXP (note, 0)
4411                           = replace_rtx (XEXP (note, 0), old_reg, dest_reg);
4412                     }
4413                 }
4414     
4415               v->last_use = last_use_insn;
4416               v->lifetime = INSN_LUID (v->insn) - INSN_LUID (last_use_insn);
4417               /* If the lifetime is zero, it means that this register is really
4418                  a dead store.  So mark this as a giv that can be ignored.
4419                  This will not prevent the biv from being eliminated.  */
4420               if (v->lifetime == 0)
4421                 v->ignore = 1;
4422
4423               if (loop_dump_stream)
4424                 fprintf (loop_dump_stream,
4425                          "Increment %d of biv %d converted to giv %d.\n\n",
4426                          INSN_UID (v->insn), old_regno, new_regno);
4427             }
4428         }
4429     }
4430   last_increment_giv = max_reg_num () - 1;
4431
4432   /* Search the loop for general induction variables.  */
4433
4434   /* A register is a giv if: it is only set once, it is a function of a
4435      biv and a constant (or invariant), and it is not a biv.  */
4436
4437   not_every_iteration = 0;
4438   loop_depth = 0;
4439   maybe_multiple = 0;
4440   p = scan_start;
4441   while (1)
4442     {
4443       p = NEXT_INSN (p);
4444       /* At end of a straight-in loop, we are done.
4445          At end of a loop entered at the bottom, scan the top.  */
4446       if (p == scan_start)
4447         break;
4448       if (p == end)
4449         {
4450           if (loop_top != 0)
4451             p = loop_top;
4452           else
4453             break;
4454           if (p == scan_start)
4455             break;
4456         }
4457
4458       /* Look for a general induction variable in a register.  */
4459       if (GET_CODE (p) == INSN
4460           && (set = single_set (p))
4461           && GET_CODE (SET_DEST (set)) == REG
4462           && ! VARRAY_CHAR (may_not_optimize, REGNO (SET_DEST (set))))
4463         {
4464           rtx src_reg;
4465           rtx add_val;
4466           rtx mult_val;
4467           int benefit;
4468           rtx regnote = 0;
4469           rtx last_consec_insn;
4470
4471           dest_reg = SET_DEST (set);
4472           if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
4473             continue;
4474
4475           if (/* SET_SRC is a giv.  */
4476               (general_induction_var (SET_SRC (set), &src_reg, &add_val,
4477                                       &mult_val, 0, &benefit)
4478                /* Equivalent expression is a giv.  */
4479                || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
4480                    && general_induction_var (XEXP (regnote, 0), &src_reg,
4481                                              &add_val, &mult_val, 0,
4482                                              &benefit)))
4483               /* Don't try to handle any regs made by loop optimization.
4484                  We have nothing on them in regno_first_uid, etc.  */
4485               && REGNO (dest_reg) < max_reg_before_loop
4486               /* Don't recognize a BASIC_INDUCT_VAR here.  */
4487               && dest_reg != src_reg
4488               /* This must be the only place where the register is set.  */
4489               && (VARRAY_INT (n_times_set, REGNO (dest_reg)) == 1
4490                   /* or all sets must be consecutive and make a giv.  */
4491                   || (benefit = consec_sets_giv (benefit, p,
4492                                                  src_reg, dest_reg,
4493                                                  &add_val, &mult_val,
4494                                                  &last_consec_insn))))
4495             {
4496               struct induction *v
4497                 = (struct induction *) alloca (sizeof (struct induction));
4498
4499               /* If this is a library call, increase benefit.  */
4500               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
4501                 benefit += libcall_benefit (p);
4502
4503               /* Skip the consecutive insns, if there are any.  */
4504               if (VARRAY_INT (n_times_set, REGNO (dest_reg)) != 1)
4505                 p = last_consec_insn;
4506
4507               record_giv (v, p, src_reg, dest_reg, mult_val, add_val, benefit,
4508                           DEST_REG, not_every_iteration, maybe_multiple,
4509                           NULL_PTR, loop_start, loop_end);
4510
4511             }
4512         }
4513
4514 #ifndef DONT_REDUCE_ADDR
4515       /* Look for givs which are memory addresses.  */
4516       /* This resulted in worse code on a VAX 8600.  I wonder if it
4517          still does.  */
4518       if (GET_CODE (p) == INSN)
4519         find_mem_givs (PATTERN (p), p, not_every_iteration, maybe_multiple,
4520                        loop_start, loop_end);
4521 #endif
4522
4523       /* Update the status of whether giv can derive other givs.  This can
4524          change when we pass a label or an insn that updates a biv.  */
4525       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4526         || GET_CODE (p) == CODE_LABEL)
4527         update_giv_derive (p);
4528
4529       /* Past CODE_LABEL, we get to insns that may be executed multiple
4530          times.  The only way we can be sure that they can't is if every
4531          every jump insn between here and the end of the loop either
4532          returns, exits the loop, is a forward jump, or is a jump
4533          to the loop start.  */
4534
4535       if (GET_CODE (p) == CODE_LABEL)
4536         {
4537           rtx insn = p;
4538
4539           maybe_multiple = 0;
4540
4541           while (1)
4542             {
4543               insn = NEXT_INSN (insn);
4544               if (insn == scan_start)
4545                 break;
4546               if (insn == end)
4547                 {
4548                   if (loop_top != 0)
4549                     insn = loop_top;
4550                   else
4551                     break;
4552                   if (insn == scan_start)
4553                     break;
4554                 }
4555
4556               if (GET_CODE (insn) == JUMP_INSN
4557                   && GET_CODE (PATTERN (insn)) != RETURN
4558                   && (! condjump_p (insn)
4559                       || (JUMP_LABEL (insn) != 0
4560                           && JUMP_LABEL (insn) != scan_start
4561                           && (INSN_UID (JUMP_LABEL (insn)) >= max_uid_for_loop
4562                               || INSN_UID (insn) >= max_uid_for_loop
4563                               || (INSN_LUID (JUMP_LABEL (insn))
4564                                   < INSN_LUID (insn))))))
4565                 {
4566                   maybe_multiple = 1;
4567                   break;
4568                 }
4569             }
4570         }
4571
4572       /* Past a jump, we get to insns for which we can't count
4573          on whether they will be executed during each iteration.  */
4574       /* This code appears twice in strength_reduce.  There is also similar
4575          code in scan_loop.  */
4576       if (GET_CODE (p) == JUMP_INSN
4577           /* If we enter the loop in the middle, and scan around to the
4578              beginning, don't set not_every_iteration for that.
4579              This can be any kind of jump, since we want to know if insns
4580              will be executed if the loop is executed.  */
4581           && ! (JUMP_LABEL (p) == loop_top
4582                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
4583                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
4584         {
4585           rtx label = 0;
4586
4587           /* If this is a jump outside the loop, then it also doesn't
4588              matter.  Check to see if the target of this branch is on the
4589              loop_number_exits_labels list.  */
4590              
4591           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
4592                label;
4593                label = LABEL_NEXTREF (label))
4594             if (XEXP (label, 0) == JUMP_LABEL (p))
4595               break;
4596
4597           if (! label)
4598             not_every_iteration = 1;
4599         }
4600
4601       else if (GET_CODE (p) == NOTE)
4602         {
4603           /* At the virtual top of a converted loop, insns are again known to
4604              be executed each iteration: logically, the loop begins here
4605              even though the exit code has been duplicated.
4606
4607              Insns are also again known to be executed each iteration at
4608              the LOOP_CONT note.  */
4609           if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
4610                || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
4611               && loop_depth == 0)
4612             not_every_iteration = 0;
4613           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4614             loop_depth++;
4615           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4616             loop_depth--;
4617         }
4618
4619       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4620          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4621          or not an insn is known to be executed each iteration of the
4622          loop, whether or not any iterations are known to occur.
4623
4624          Therefore, if we have just passed a label and have no more labels
4625          between here and the test insn of the loop, we know these insns
4626          will be executed each iteration.  */
4627
4628       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
4629           && no_labels_between_p (p, loop_end)
4630           && loop_insn_first_p (p, loop_cont))
4631         not_every_iteration = 0;
4632     }
4633
4634   /* Try to calculate and save the number of loop iterations.  This is
4635      set to zero if the actual number can not be calculated.  This must
4636      be called after all giv's have been identified, since otherwise it may
4637      fail if the iteration variable is a giv.  */
4638
4639   loop_iterations (loop_start, loop_end, loop_info);
4640
4641   /* Now for each giv for which we still don't know whether or not it is
4642      replaceable, check to see if it is replaceable because its final value
4643      can be calculated.  This must be done after loop_iterations is called,
4644      so that final_giv_value will work correctly.  */
4645
4646   for (bl = loop_iv_list; bl; bl = bl->next)
4647     {
4648       struct induction *v;
4649
4650       for (v = bl->giv; v; v = v->next_iv)
4651         if (! v->replaceable && ! v->not_replaceable)
4652           check_final_value (v, loop_start, loop_end, loop_info->n_iterations);
4653     }
4654
4655   /* Try to prove that the loop counter variable (if any) is always
4656      nonnegative; if so, record that fact with a REG_NONNEG note
4657      so that "decrement and branch until zero" insn can be used.  */
4658   check_dbra_loop (loop_end, insn_count, loop_start, loop_info);
4659
4660   /* Create reg_map to hold substitutions for replaceable giv regs.
4661      Some givs might have been made from biv increments, so look at
4662      reg_iv_type for a suitable size.  */
4663   reg_map_size = reg_iv_type->num_elements;
4664   reg_map = (rtx *) alloca (reg_map_size * sizeof (rtx));
4665   bzero ((char *) reg_map, reg_map_size * sizeof (rtx));
4666
4667   /* Examine each iv class for feasibility of strength reduction/induction
4668      variable elimination.  */
4669
4670   for (bl = loop_iv_list; bl; bl = bl->next)
4671     {
4672       struct induction *v;
4673       int benefit;
4674       int all_reduced;
4675       rtx final_value = 0;
4676       unsigned int nregs;
4677
4678       /* Test whether it will be possible to eliminate this biv
4679          provided all givs are reduced.  This is possible if either
4680          the reg is not used outside the loop, or we can compute
4681          what its final value will be.
4682
4683          For architectures with a decrement_and_branch_until_zero insn,
4684          don't do this if we put a REG_NONNEG note on the endtest for
4685          this biv.  */
4686
4687       /* Compare against bl->init_insn rather than loop_start.
4688          We aren't concerned with any uses of the biv between
4689          init_insn and loop_start since these won't be affected
4690          by the value of the biv elsewhere in the function, so
4691          long as init_insn doesn't use the biv itself.
4692          March 14, 1989 -- self@bayes.arc.nasa.gov */
4693
4694       if ((uid_luid[REGNO_LAST_UID (bl->regno)] < INSN_LUID (loop_end)
4695            && bl->init_insn
4696            && INSN_UID (bl->init_insn) < max_uid_for_loop
4697            && uid_luid[REGNO_FIRST_UID (bl->regno)] >= INSN_LUID (bl->init_insn)
4698 #ifdef HAVE_decrement_and_branch_until_zero
4699            && ! bl->nonneg
4700 #endif
4701            && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4702           || ((final_value = final_biv_value (bl, loop_start, loop_end, 
4703                                               loop_info->n_iterations))
4704 #ifdef HAVE_decrement_and_branch_until_zero
4705               && ! bl->nonneg
4706 #endif
4707               ))
4708         bl->eliminable = maybe_eliminate_biv (bl, loop_start, end, 0,
4709                                               threshold, insn_count);
4710       else
4711         {
4712           if (loop_dump_stream)
4713             {
4714               fprintf (loop_dump_stream,
4715                        "Cannot eliminate biv %d.\n",
4716                        bl->regno);
4717               fprintf (loop_dump_stream,
4718                        "First use: insn %d, last use: insn %d.\n",
4719                        REGNO_FIRST_UID (bl->regno),
4720                        REGNO_LAST_UID (bl->regno));
4721             }
4722         }
4723
4724       /* Combine all giv's for this iv_class.  */
4725       combine_givs (bl);
4726
4727       /* This will be true at the end, if all givs which depend on this
4728          biv have been strength reduced.
4729          We can't (currently) eliminate the biv unless this is so.  */
4730       all_reduced = 1;
4731
4732       /* Check each giv in this class to see if we will benefit by reducing
4733          it.  Skip giv's combined with others.  */
4734       for (v = bl->giv; v; v = v->next_iv)
4735         {
4736           struct induction *tv;
4737
4738           if (v->ignore || v->same)
4739             continue;
4740
4741           benefit = v->benefit;
4742
4743           /* Reduce benefit if not replaceable, since we will insert
4744              a move-insn to replace the insn that calculates this giv.
4745              Don't do this unless the giv is a user variable, since it
4746              will often be marked non-replaceable because of the duplication
4747              of the exit code outside the loop.  In such a case, the copies
4748              we insert are dead and will be deleted.  So they don't have
4749              a cost.  Similar situations exist.  */
4750           /* ??? The new final_[bg]iv_value code does a much better job
4751              of finding replaceable giv's, and hence this code may no longer
4752              be necessary.  */
4753           if (! v->replaceable && ! bl->eliminable
4754               && REG_USERVAR_P (v->dest_reg))
4755             benefit -= copy_cost;
4756
4757           /* Decrease the benefit to count the add-insns that we will
4758              insert to increment the reduced reg for the giv.  */
4759           benefit -= add_cost * bl->biv_count;
4760
4761           /* Decide whether to strength-reduce this giv or to leave the code
4762              unchanged (recompute it from the biv each time it is used).
4763              This decision can be made independently for each giv.  */
4764
4765 #ifdef AUTO_INC_DEC
4766           /* Attempt to guess whether autoincrement will handle some of the
4767              new add insns; if so, increase BENEFIT (undo the subtraction of
4768              add_cost that was done above).  */
4769           if (v->giv_type == DEST_ADDR
4770               && GET_CODE (v->mult_val) == CONST_INT)
4771             {
4772               if (HAVE_POST_INCREMENT
4773                   && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4774                 benefit += add_cost * bl->biv_count;
4775               else if (HAVE_PRE_INCREMENT
4776                        && INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4777                 benefit += add_cost * bl->biv_count;
4778               else if (HAVE_POST_DECREMENT
4779                        && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4780                 benefit += add_cost * bl->biv_count;
4781               else if (HAVE_PRE_DECREMENT
4782                        && -INTVAL (v->mult_val) == GET_MODE_SIZE (v->mem_mode))
4783                 benefit += add_cost * bl->biv_count;
4784             }
4785 #endif
4786
4787           /* If an insn is not to be strength reduced, then set its ignore
4788              flag, and clear all_reduced.  */
4789
4790           /* A giv that depends on a reversed biv must be reduced if it is
4791              used after the loop exit, otherwise, it would have the wrong
4792              value after the loop exit.  To make it simple, just reduce all
4793              of such giv's whether or not we know they are used after the loop
4794              exit.  */
4795
4796           if ( ! flag_reduce_all_givs && v->lifetime * threshold * benefit < insn_count
4797               && ! bl->reversed )
4798             {
4799               if (loop_dump_stream)
4800                 fprintf (loop_dump_stream,
4801                          "giv of insn %d not worth while, %d vs %d.\n",
4802                          INSN_UID (v->insn),
4803                          v->lifetime * threshold * benefit, insn_count);
4804               v->ignore = 1;
4805               all_reduced = 0;
4806             }
4807           else
4808             {
4809               /* Check that we can increment the reduced giv without a
4810                  multiply insn.  If not, reject it.  */
4811
4812               for (tv = bl->biv; tv; tv = tv->next_iv)
4813                 if (tv->mult_val == const1_rtx
4814                     && ! product_cheap_p (tv->add_val, v->mult_val))
4815                   {
4816                     if (loop_dump_stream)
4817                       fprintf (loop_dump_stream,
4818                                "giv of insn %d: would need a multiply.\n",
4819                                INSN_UID (v->insn));
4820                     v->ignore = 1;
4821                     all_reduced = 0;
4822                     break;
4823                   }
4824             }
4825         }
4826
4827       /* Check for givs whose first use is their definition and whose
4828          last use is the definition of another giv.  If so, it is likely
4829          dead and should not be used to derive another giv nor to
4830          eliminate a biv.  */
4831       for (v = bl->giv; v; v = v->next_iv)
4832         {
4833           if (v->ignore
4834               || (v->same && v->same->ignore))
4835             continue;
4836
4837           if (v->last_use)
4838             {
4839               struct induction *v1;
4840
4841               for (v1 = bl->giv; v1; v1 = v1->next_iv)
4842                 if (v->last_use == v1->insn)
4843                   v->maybe_dead = 1;
4844             }
4845           else if (v->giv_type == DEST_REG
4846               && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4847             {
4848               struct induction *v1;
4849
4850               for (v1 = bl->giv; v1; v1 = v1->next_iv)
4851                 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4852                   v->maybe_dead = 1;
4853             }
4854         }
4855
4856       /* Now that we know which givs will be reduced, try to rearrange the
4857          combinations to reduce register pressure.
4858          recombine_givs calls find_life_end, which needs reg_iv_type and
4859          reg_iv_info to be valid for all pseudos.  We do the necessary
4860          reallocation here since it allows to check if there are still
4861          more bivs to process.  */
4862       nregs = max_reg_num ();
4863       if (nregs > reg_iv_type->num_elements)
4864         {
4865           /* If there are still more bivs to process, allocate some slack
4866              space so that we're not constantly reallocating these arrays.  */
4867           if (bl->next)
4868             nregs += nregs / 4;
4869           /* Reallocate reg_iv_type and reg_iv_info.  */
4870           VARRAY_GROW (reg_iv_type, nregs);
4871           VARRAY_GROW (reg_iv_info, nregs);
4872         }
4873       recombine_givs (bl, loop_start, loop_end, unroll_p);
4874
4875       /* Reduce each giv that we decided to reduce.  */
4876
4877       for (v = bl->giv; v; v = v->next_iv)
4878         {
4879           struct induction *tv;
4880           if (! v->ignore && v->same == 0)
4881             {
4882               int auto_inc_opt = 0;
4883
4884               /* If the code for derived givs immediately below has already
4885                  allocated a new_reg, we must keep it.  */
4886               if (! v->new_reg)
4887                 v->new_reg = gen_reg_rtx (v->mode);
4888
4889               if (v->derived_from)
4890                 {
4891                   struct induction *d = v->derived_from;
4892
4893                   /* In case d->dest_reg is not replaceable, we have
4894                      to replace it in v->insn now.  */
4895                   if (! d->new_reg)
4896                     d->new_reg = gen_reg_rtx (d->mode);
4897                   PATTERN (v->insn)
4898                     = replace_rtx (PATTERN (v->insn), d->dest_reg, d->new_reg);
4899                   PATTERN (v->insn)
4900                     = replace_rtx (PATTERN (v->insn), v->dest_reg, v->new_reg);
4901                   /* For each place where the biv is incremented, add an
4902                      insn to set the new, reduced reg for the giv.
4903                      We used to do this only for biv_count != 1, but
4904                      this fails when there is a giv after a single biv
4905                      increment, e.g. when the last giv was expressed as
4906                      pre-decrement.  */
4907                   for (tv = bl->biv; tv; tv = tv->next_iv)
4908                     {
4909                       /* We always emit reduced giv increments before the
4910                          biv increment when bl->biv_count != 1.  So by
4911                          emitting the add insns for derived givs after the
4912                          biv increment, they pick up the updated value of
4913                          the reduced giv.
4914                          If the reduced giv is processed with
4915                          auto_inc_opt == 1, then it is incremented earlier
4916                          than the biv, hence we'll still pick up the right
4917                          value.
4918                          If it's processed with auto_inc_opt == -1,
4919                          that implies that the biv increment is before the
4920                          first reduced giv's use.  The derived giv's lifetime
4921                          is after the reduced giv's lifetime, hence in this
4922                          case, the biv increment doesn't matter.  */
4923                       emit_insn_after (copy_rtx (PATTERN (v->insn)), tv->insn);
4924                     }
4925                   continue;
4926                 }
4927
4928 #ifdef AUTO_INC_DEC
4929               /* If the target has auto-increment addressing modes, and
4930                  this is an address giv, then try to put the increment
4931                  immediately after its use, so that flow can create an
4932                  auto-increment addressing mode.  */
4933               if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4934                   && bl->biv->always_executed && ! bl->biv->maybe_multiple
4935                   /* We don't handle reversed biv's because bl->biv->insn
4936                      does not have a valid INSN_LUID.  */
4937                   && ! bl->reversed
4938                   && v->always_executed && ! v->maybe_multiple
4939                   && INSN_UID (v->insn) < max_uid_for_loop)
4940                 {
4941                   /* If other giv's have been combined with this one, then
4942                      this will work only if all uses of the other giv's occur
4943                      before this giv's insn.  This is difficult to check.
4944
4945                      We simplify this by looking for the common case where
4946                      there is one DEST_REG giv, and this giv's insn is the
4947                      last use of the dest_reg of that DEST_REG giv.  If the
4948                      increment occurs after the address giv, then we can
4949                      perform the optimization.  (Otherwise, the increment
4950                      would have to go before other_giv, and we would not be
4951                      able to combine it with the address giv to get an
4952                      auto-inc address.)  */
4953                   if (v->combined_with)
4954                     {
4955                       struct induction *other_giv = 0;
4956
4957                       for (tv = bl->giv; tv; tv = tv->next_iv)
4958                         if (tv->same == v)
4959                           {
4960                             if (other_giv)
4961                               break;
4962                             else
4963                               other_giv = tv;
4964                           }
4965                       if (! tv && other_giv
4966                           && REGNO (other_giv->dest_reg) < max_reg_before_loop
4967                           && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4968                               == INSN_UID (v->insn))
4969                           && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4970                         auto_inc_opt = 1;
4971                     }
4972                   /* Check for case where increment is before the address
4973                      giv.  Do this test in "loop order".  */
4974                   else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4975                             && (INSN_LUID (v->insn) < INSN_LUID (scan_start)
4976                                 || (INSN_LUID (bl->biv->insn)
4977                                     > INSN_LUID (scan_start))))
4978                            || (INSN_LUID (v->insn) < INSN_LUID (scan_start)
4979                                && (INSN_LUID (scan_start)
4980                                    < INSN_LUID (bl->biv->insn))))
4981                     auto_inc_opt = -1;
4982                   else
4983                     auto_inc_opt = 1;
4984
4985 #ifdef HAVE_cc0
4986                   {
4987                     rtx prev;
4988
4989                     /* We can't put an insn immediately after one setting
4990                        cc0, or immediately before one using cc0.  */
4991                     if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4992                         || (auto_inc_opt == -1
4993                             && (prev = prev_nonnote_insn (v->insn)) != 0
4994                             && GET_RTX_CLASS (GET_CODE (prev)) == 'i'
4995                             && sets_cc0_p (PATTERN (prev))))
4996                       auto_inc_opt = 0;
4997                   }
4998 #endif
4999
5000                   if (auto_inc_opt)
5001                     v->auto_inc_opt = 1;
5002                 }
5003 #endif
5004
5005               /* For each place where the biv is incremented, add an insn
5006                  to increment the new, reduced reg for the giv.  */
5007               for (tv = bl->biv; tv; tv = tv->next_iv)
5008                 {
5009                   rtx insert_before;
5010
5011                   if (! auto_inc_opt)
5012                     insert_before = tv->insn;
5013                   else if (auto_inc_opt == 1)
5014                     insert_before = NEXT_INSN (v->insn);
5015                   else
5016                     insert_before = v->insn;
5017
5018                   if (tv->mult_val == const1_rtx)
5019                     emit_iv_add_mult (tv->add_val, v->mult_val,
5020                                       v->new_reg, v->new_reg, insert_before);
5021                   else /* tv->mult_val == const0_rtx */
5022                     /* A multiply is acceptable here
5023                        since this is presumed to be seldom executed.  */
5024                     emit_iv_add_mult (tv->add_val, v->mult_val,
5025                                       v->add_val, v->new_reg, insert_before);
5026                 }
5027
5028               /* Add code at loop start to initialize giv's reduced reg.  */
5029
5030               emit_iv_add_mult (bl->initial_value, v->mult_val,
5031                                 v->add_val, v->new_reg, loop_start);
5032             }
5033         }
5034
5035       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
5036          as not reduced.
5037          
5038          For each giv register that can be reduced now: if replaceable,
5039          substitute reduced reg wherever the old giv occurs;
5040          else add new move insn "giv_reg = reduced_reg".  */
5041
5042       for (v = bl->giv; v; v = v->next_iv)
5043         {
5044           if (v->same && v->same->ignore)
5045             v->ignore = 1;
5046
5047           if (v->ignore)
5048             continue;
5049
5050           /* Update expression if this was combined, in case other giv was
5051              replaced.  */
5052           if (v->same)
5053             v->new_reg = replace_rtx (v->new_reg,
5054                                       v->same->dest_reg, v->same->new_reg);
5055
5056           if (v->giv_type == DEST_ADDR)
5057             /* Store reduced reg as the address in the memref where we found
5058                this giv.  */
5059             validate_change (v->insn, v->location, v->new_reg, 0);
5060           else if (v->replaceable)
5061             {
5062               reg_map[REGNO (v->dest_reg)] = v->new_reg;
5063
5064 #if 0
5065               /* I can no longer duplicate the original problem.  Perhaps
5066                  this is unnecessary now?  */
5067
5068               /* Replaceable; it isn't strictly necessary to delete the old
5069                  insn and emit a new one, because v->dest_reg is now dead.
5070
5071                  However, especially when unrolling loops, the special
5072                  handling for (set REG0 REG1) in the second cse pass may
5073                  make v->dest_reg live again.  To avoid this problem, emit
5074                  an insn to set the original giv reg from the reduced giv.
5075                  We can not delete the original insn, since it may be part
5076                  of a LIBCALL, and the code in flow that eliminates dead
5077                  libcalls will fail if it is deleted.  */
5078               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
5079                                v->insn);
5080 #endif
5081             }
5082           else
5083             {
5084               /* Not replaceable; emit an insn to set the original giv reg from
5085                  the reduced giv, same as above.  */
5086               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
5087                                v->insn);
5088             }
5089
5090           /* When a loop is reversed, givs which depend on the reversed
5091              biv, and which are live outside the loop, must be set to their
5092              correct final value.  This insn is only needed if the giv is
5093              not replaceable.  The correct final value is the same as the
5094              value that the giv starts the reversed loop with.  */
5095           if (bl->reversed && ! v->replaceable)
5096             emit_iv_add_mult (bl->initial_value, v->mult_val,
5097                               v->add_val, v->dest_reg, end_insert_before);
5098           else if (v->final_value)
5099             {
5100               rtx insert_before;
5101
5102               /* If the loop has multiple exits, emit the insn before the
5103                  loop to ensure that it will always be executed no matter
5104                  how the loop exits.  Otherwise, emit the insn after the loop,
5105                  since this is slightly more efficient.  */
5106               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
5107                 insert_before = loop_start;
5108               else
5109                 insert_before = end_insert_before;
5110               emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
5111                                 insert_before);
5112
5113 #if 0
5114               /* If the insn to set the final value of the giv was emitted
5115                  before the loop, then we must delete the insn inside the loop
5116                  that sets it.  If this is a LIBCALL, then we must delete
5117                  every insn in the libcall.  Note, however, that
5118                  final_giv_value will only succeed when there are multiple
5119                  exits if the giv is dead at each exit, hence it does not
5120                  matter that the original insn remains because it is dead
5121                  anyways.  */
5122               /* Delete the insn inside the loop that sets the giv since
5123                  the giv is now set before (or after) the loop.  */
5124               delete_insn (v->insn);
5125 #endif
5126             }
5127
5128           if (loop_dump_stream)
5129             {
5130               fprintf (loop_dump_stream, "giv at %d reduced to ",
5131                        INSN_UID (v->insn));
5132               print_rtl (loop_dump_stream, v->new_reg);
5133               fprintf (loop_dump_stream, "\n");
5134             }
5135         }
5136
5137       /* All the givs based on the biv bl have been reduced if they
5138          merit it.  */
5139
5140       /* For each giv not marked as maybe dead that has been combined with a
5141          second giv, clear any "maybe dead" mark on that second giv.
5142          v->new_reg will either be or refer to the register of the giv it
5143          combined with.
5144
5145          Doing this clearing avoids problems in biv elimination where a
5146          giv's new_reg is a complex value that can't be put in the insn but
5147          the giv combined with (with a reg as new_reg) is marked maybe_dead.
5148          Since the register will be used in either case, we'd prefer it be
5149          used from the simpler giv.  */
5150
5151       for (v = bl->giv; v; v = v->next_iv)
5152         if (! v->maybe_dead && v->same)
5153           v->same->maybe_dead = 0;
5154
5155       /* Try to eliminate the biv, if it is a candidate.
5156          This won't work if ! all_reduced,
5157          since the givs we planned to use might not have been reduced.
5158
5159          We have to be careful that we didn't initially think we could eliminate
5160          this biv because of a giv that we now think may be dead and shouldn't
5161          be used as a biv replacement.  
5162
5163          Also, there is the possibility that we may have a giv that looks
5164          like it can be used to eliminate a biv, but the resulting insn
5165          isn't valid.  This can happen, for example, on the 88k, where a 
5166          JUMP_INSN can compare a register only with zero.  Attempts to
5167          replace it with a compare with a constant will fail.
5168
5169          Note that in cases where this call fails, we may have replaced some
5170          of the occurrences of the biv with a giv, but no harm was done in
5171          doing so in the rare cases where it can occur.  */
5172
5173       if (all_reduced == 1 && bl->eliminable
5174           && maybe_eliminate_biv (bl, loop_start, end, 1,
5175                                   threshold, insn_count))
5176
5177         {
5178           /* ?? If we created a new test to bypass the loop entirely,
5179              or otherwise drop straight in, based on this test, then
5180              we might want to rewrite it also.  This way some later
5181              pass has more hope of removing the initialization of this
5182              biv entirely.  */
5183
5184           /* If final_value != 0, then the biv may be used after loop end
5185              and we must emit an insn to set it just in case.
5186
5187              Reversed bivs already have an insn after the loop setting their
5188              value, so we don't need another one.  We can't calculate the
5189              proper final value for such a biv here anyways.  */
5190           if (final_value != 0 && ! bl->reversed)
5191             {
5192               rtx insert_before;
5193
5194               /* If the loop has multiple exits, emit the insn before the
5195                  loop to ensure that it will always be executed no matter
5196                  how the loop exits.  Otherwise, emit the insn after the
5197                  loop, since this is slightly more efficient.  */
5198               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
5199                 insert_before = loop_start;
5200               else
5201                 insert_before = end_insert_before;
5202
5203               emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
5204                                 end_insert_before);
5205             }
5206
5207 #if 0
5208           /* Delete all of the instructions inside the loop which set
5209              the biv, as they are all dead.  If is safe to delete them,
5210              because an insn setting a biv will never be part of a libcall.  */
5211           /* However, deleting them will invalidate the regno_last_uid info,
5212              so keeping them around is more convenient.  Final_biv_value
5213              will only succeed when there are multiple exits if the biv
5214              is dead at each exit, hence it does not matter that the original
5215              insn remains, because it is dead anyways.  */
5216           for (v = bl->biv; v; v = v->next_iv)
5217             delete_insn (v->insn);
5218 #endif
5219
5220           if (loop_dump_stream)
5221             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
5222                      bl->regno);
5223         }
5224     }
5225
5226   /* Go through all the instructions in the loop, making all the
5227      register substitutions scheduled in REG_MAP.  */
5228
5229   for (p = loop_start; p != end; p = NEXT_INSN (p))
5230     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5231         || GET_CODE (p) == CALL_INSN)
5232       {
5233         replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
5234         replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
5235         INSN_CODE (p) = -1;
5236       }
5237
5238   if (loop_info->n_iterations > 0)
5239     {
5240       /* When we completely unroll a loop we will likely not need the increment
5241          of the loop BIV and we will not need the conditional branch at the
5242          end of the loop.  */
5243       unrolled_insn_copies = insn_count - 2;
5244
5245 #ifdef HAVE_cc0
5246       /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5247          need the comparison before the conditional branch at the end of the
5248          loop.  */
5249       unrolled_insn_copies -= 1;
5250 #endif
5251
5252       /* We'll need one copy for each loop iteration.  */
5253       unrolled_insn_copies *= loop_info->n_iterations;
5254
5255       /* A little slop to account for the ability to remove initialization
5256          code, better CSE, and other secondary benefits of completely
5257          unrolling some loops.  */
5258       unrolled_insn_copies -= 1;
5259
5260       /* Clamp the value.  */
5261       if (unrolled_insn_copies < 0)
5262         unrolled_insn_copies = 0;
5263     }
5264   
5265   /* Unroll loops from within strength reduction so that we can use the
5266      induction variable information that strength_reduce has already
5267      collected.  Always unroll loops that would be as small or smaller
5268      unrolled than when rolled.  */
5269   if (unroll_p
5270       || (loop_info->n_iterations > 0
5271           && unrolled_insn_copies <= insn_count))
5272     unroll_loop (loop_end, insn_count, loop_start, end_insert_before,
5273                  loop_info, 1);
5274
5275 #ifdef HAVE_decrement_and_branch_on_count
5276   /* Instrument the loop with BCT insn.  */
5277   if (HAVE_decrement_and_branch_on_count && bct_p
5278       && flag_branch_on_count_reg)
5279     insert_bct (loop_start, loop_end, loop_info);
5280 #endif  /* HAVE_decrement_and_branch_on_count */
5281
5282   if (loop_dump_stream)
5283     fprintf (loop_dump_stream, "\n");
5284
5285 egress:
5286   VARRAY_FREE (reg_iv_type);
5287   VARRAY_FREE (reg_iv_info);
5288 }
5289 \f
5290 /* Return 1 if X is a valid source for an initial value (or as value being
5291    compared against in an initial test).
5292
5293    X must be either a register or constant and must not be clobbered between
5294    the current insn and the start of the loop.
5295
5296    INSN is the insn containing X.  */
5297
5298 static int
5299 valid_initial_value_p (x, insn, call_seen, loop_start)
5300      rtx x;
5301      rtx insn;
5302      int call_seen;
5303      rtx loop_start;
5304 {
5305   if (CONSTANT_P (x))
5306     return 1;
5307
5308   /* Only consider pseudos we know about initialized in insns whose luids
5309      we know.  */
5310   if (GET_CODE (x) != REG
5311       || REGNO (x) >= max_reg_before_loop)
5312     return 0;
5313
5314   /* Don't use call-clobbered registers across a call which clobbers it.  On
5315      some machines, don't use any hard registers at all.  */
5316   if (REGNO (x) < FIRST_PSEUDO_REGISTER
5317       && (SMALL_REGISTER_CLASSES
5318           || (call_used_regs[REGNO (x)] && call_seen)))
5319     return 0;
5320
5321   /* Don't use registers that have been clobbered before the start of the
5322      loop.  */
5323   if (reg_set_between_p (x, insn, loop_start))
5324     return 0;
5325
5326   return 1;
5327 }
5328 \f
5329 /* Scan X for memory refs and check each memory address
5330    as a possible giv.  INSN is the insn whose pattern X comes from.
5331    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5332    every loop iteration.  MAYBE_MULTIPLE is 1 if the insn might be executed
5333    more thanonce in each loop iteration.  */
5334
5335 static void
5336 find_mem_givs (x, insn, not_every_iteration, maybe_multiple, loop_start,
5337                loop_end)
5338      rtx x;
5339      rtx insn;
5340      int not_every_iteration, maybe_multiple;
5341      rtx loop_start, loop_end;
5342 {
5343   register int i, j;
5344   register enum rtx_code code;
5345   register const char *fmt;
5346
5347   if (x == 0)
5348     return;
5349
5350   code = GET_CODE (x);
5351   switch (code)
5352     {
5353     case REG:
5354     case CONST_INT:
5355     case CONST:
5356     case CONST_DOUBLE:
5357     case SYMBOL_REF:
5358     case LABEL_REF:
5359     case PC:
5360     case CC0:
5361     case ADDR_VEC:
5362     case ADDR_DIFF_VEC:
5363     case USE:
5364     case CLOBBER:
5365       return;
5366
5367     case MEM:
5368       {
5369         rtx src_reg;
5370         rtx add_val;
5371         rtx mult_val;
5372         int benefit;
5373
5374         /* This code used to disable creating GIVs with mult_val == 1 and
5375            add_val == 0.  However, this leads to lost optimizations when 
5376            it comes time to combine a set of related DEST_ADDR GIVs, since
5377            this one would not be seen.   */
5378
5379         if (general_induction_var (XEXP (x, 0), &src_reg, &add_val,
5380                                    &mult_val, 1, &benefit))
5381           {
5382             /* Found one; record it.  */
5383             struct induction *v
5384               = (struct induction *) oballoc (sizeof (struct induction));
5385
5386             record_giv (v, insn, src_reg, addr_placeholder, mult_val,
5387                         add_val, benefit, DEST_ADDR, not_every_iteration,
5388                         maybe_multiple, &XEXP (x, 0), loop_start, loop_end);
5389
5390             v->mem_mode = GET_MODE (x);
5391           }
5392       }
5393       return;
5394
5395     default:
5396       break;
5397     }
5398
5399   /* Recursively scan the subexpressions for other mem refs.  */
5400
5401   fmt = GET_RTX_FORMAT (code);
5402   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5403     if (fmt[i] == 'e')
5404       find_mem_givs (XEXP (x, i), insn, not_every_iteration, maybe_multiple,
5405                      loop_start, loop_end);
5406     else if (fmt[i] == 'E')
5407       for (j = 0; j < XVECLEN (x, i); j++)
5408         find_mem_givs (XVECEXP (x, i, j), insn, not_every_iteration,
5409                        maybe_multiple, loop_start, loop_end);
5410 }
5411 \f
5412 /* Fill in the data about one biv update.
5413    V is the `struct induction' in which we record the biv.  (It is
5414    allocated by the caller, with alloca.)
5415    INSN is the insn that sets it.
5416    DEST_REG is the biv's reg.
5417
5418    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5419    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
5420    being set to INC_VAL.
5421
5422    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5423    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5424    can be executed more than once per iteration.  If MAYBE_MULTIPLE
5425    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5426    executed exactly once per iteration.  */
5427
5428 static void
5429 record_biv (v, insn, dest_reg, inc_val, mult_val, location,
5430             not_every_iteration, maybe_multiple)
5431      struct induction *v;
5432      rtx insn;
5433      rtx dest_reg;
5434      rtx inc_val;
5435      rtx mult_val;
5436      rtx *location;
5437      int not_every_iteration;
5438      int maybe_multiple;
5439 {
5440   struct iv_class *bl;
5441
5442   v->insn = insn;
5443   v->src_reg = dest_reg;
5444   v->dest_reg = dest_reg;
5445   v->mult_val = mult_val;
5446   v->add_val = inc_val;
5447   v->location = location;
5448   v->mode = GET_MODE (dest_reg);
5449   v->always_computable = ! not_every_iteration;
5450   v->always_executed = ! not_every_iteration;
5451   v->maybe_multiple = maybe_multiple;
5452
5453   /* Add this to the reg's iv_class, creating a class
5454      if this is the first incrementation of the reg.  */
5455
5456   bl = reg_biv_class[REGNO (dest_reg)];
5457   if (bl == 0)
5458     {
5459       /* Create and initialize new iv_class.  */
5460
5461       bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
5462
5463       bl->regno = REGNO (dest_reg);
5464       bl->biv = 0;
5465       bl->giv = 0;
5466       bl->biv_count = 0;
5467       bl->giv_count = 0;
5468
5469       /* Set initial value to the reg itself.  */
5470       bl->initial_value = dest_reg;
5471       /* We haven't seen the initializing insn yet */
5472       bl->init_insn = 0;
5473       bl->init_set = 0;
5474       bl->initial_test = 0;
5475       bl->incremented = 0;
5476       bl->eliminable = 0;
5477       bl->nonneg = 0;
5478       bl->reversed = 0;
5479       bl->total_benefit = 0;
5480
5481       /* Add this class to loop_iv_list.  */
5482       bl->next = loop_iv_list;
5483       loop_iv_list = bl;
5484
5485       /* Put it in the array of biv register classes.  */
5486       reg_biv_class[REGNO (dest_reg)] = bl;
5487     }
5488
5489   /* Update IV_CLASS entry for this biv.  */
5490   v->next_iv = bl->biv;
5491   bl->biv = v;
5492   bl->biv_count++;
5493   if (mult_val == const1_rtx)
5494     bl->incremented = 1;
5495
5496   if (loop_dump_stream)
5497     {
5498       fprintf (loop_dump_stream,
5499                "Insn %d: possible biv, reg %d,",
5500                INSN_UID (insn), REGNO (dest_reg));
5501       if (GET_CODE (inc_val) == CONST_INT)
5502         {
5503           fprintf (loop_dump_stream, " const =");
5504           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (inc_val));
5505           fputc ('\n', loop_dump_stream);
5506         }
5507       else
5508         {
5509           fprintf (loop_dump_stream, " const = ");
5510           print_rtl (loop_dump_stream, inc_val);
5511           fprintf (loop_dump_stream, "\n");
5512         }
5513     }
5514 }
5515 \f
5516 /* Fill in the data about one giv.
5517    V is the `struct induction' in which we record the giv.  (It is
5518    allocated by the caller, with alloca.)
5519    INSN is the insn that sets it.
5520    BENEFIT estimates the savings from deleting this insn.
5521    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5522    into a register or is used as a memory address.
5523
5524    SRC_REG is the biv reg which the giv is computed from.
5525    DEST_REG is the giv's reg (if the giv is stored in a reg).
5526    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5527    LOCATION points to the place where this giv's value appears in INSN.  */
5528
5529 static void
5530 record_giv (v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
5531             type, not_every_iteration, maybe_multiple, location, loop_start,
5532             loop_end)
5533      struct induction *v;
5534      rtx insn;
5535      rtx src_reg;
5536      rtx dest_reg;
5537      rtx mult_val, add_val;
5538      int benefit;
5539      enum g_types type;
5540      int not_every_iteration, maybe_multiple;
5541      rtx *location;
5542      rtx loop_start, loop_end;
5543 {
5544   struct induction *b;
5545   struct iv_class *bl;
5546   rtx set = single_set (insn);
5547
5548   v->insn = insn;
5549   v->src_reg = src_reg;
5550   v->giv_type = type;
5551   v->dest_reg = dest_reg;
5552   v->mult_val = mult_val;
5553   v->add_val = add_val;
5554   v->benefit = benefit;
5555   v->location = location;
5556   v->cant_derive = 0;
5557   v->combined_with = 0;
5558   v->maybe_multiple = maybe_multiple;
5559   v->maybe_dead = 0;
5560   v->derive_adjustment = 0;
5561   v->same = 0;
5562   v->ignore = 0;
5563   v->new_reg = 0;
5564   v->final_value = 0;
5565   v->same_insn = 0;
5566   v->auto_inc_opt = 0;
5567   v->unrolled = 0;
5568   v->shared = 0;
5569   v->derived_from = 0;
5570   v->last_use = 0;
5571
5572   /* The v->always_computable field is used in update_giv_derive, to
5573      determine whether a giv can be used to derive another giv.  For a
5574      DEST_REG giv, INSN computes a new value for the giv, so its value
5575      isn't computable if INSN insn't executed every iteration.
5576      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5577      it does not compute a new value.  Hence the value is always computable
5578      regardless of whether INSN is executed each iteration.  */
5579
5580   if (type == DEST_ADDR)
5581     v->always_computable = 1;
5582   else
5583     v->always_computable = ! not_every_iteration;
5584
5585   v->always_executed = ! not_every_iteration;
5586
5587   if (type == DEST_ADDR)
5588     {
5589       v->mode = GET_MODE (*location);
5590       v->lifetime = 1;
5591     }
5592   else /* type == DEST_REG */
5593     {
5594       v->mode = GET_MODE (SET_DEST (set));
5595
5596       v->lifetime = (uid_luid[REGNO_LAST_UID (REGNO (dest_reg))]
5597                      - uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))]);
5598
5599       /* If the lifetime is zero, it means that this register is
5600          really a dead store.  So mark this as a giv that can be
5601          ignored.  This will not prevent the biv from being eliminated.  */
5602       if (v->lifetime == 0)
5603         v->ignore = 1;
5604
5605       REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
5606       REG_IV_INFO (REGNO (dest_reg)) = v;
5607     }
5608
5609   /* Add the giv to the class of givs computed from one biv.  */
5610
5611   bl = reg_biv_class[REGNO (src_reg)];
5612   if (bl)
5613     {
5614       v->next_iv = bl->giv;
5615       bl->giv = v;
5616       /* Don't count DEST_ADDR.  This is supposed to count the number of
5617          insns that calculate givs.  */
5618       if (type == DEST_REG)
5619         bl->giv_count++;
5620       bl->total_benefit += benefit;
5621     }
5622   else
5623     /* Fatal error, biv missing for this giv?  */
5624     abort ();
5625
5626   if (type == DEST_ADDR)
5627     v->replaceable = 1;
5628   else
5629     {
5630       /* The giv can be replaced outright by the reduced register only if all
5631          of the following conditions are true:
5632          - the insn that sets the giv is always executed on any iteration
5633            on which the giv is used at all
5634            (there are two ways to deduce this:
5635             either the insn is executed on every iteration,
5636             or all uses follow that insn in the same basic block),
5637          - the giv is not used outside the loop
5638          - no assignments to the biv occur during the giv's lifetime.  */
5639
5640       if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5641           /* Previous line always fails if INSN was moved by loop opt.  */
5642           && uid_luid[REGNO_LAST_UID (REGNO (dest_reg))] < INSN_LUID (loop_end)
5643           && (! not_every_iteration
5644               || last_use_this_basic_block (dest_reg, insn)))
5645         {
5646           /* Now check that there are no assignments to the biv within the
5647              giv's lifetime.  This requires two separate checks.  */
5648
5649           /* Check each biv update, and fail if any are between the first
5650              and last use of the giv.
5651              
5652              If this loop contains an inner loop that was unrolled, then
5653              the insn modifying the biv may have been emitted by the loop
5654              unrolling code, and hence does not have a valid luid.  Just
5655              mark the biv as not replaceable in this case.  It is not very
5656              useful as a biv, because it is used in two different loops.
5657              It is very unlikely that we would be able to optimize the giv
5658              using this biv anyways.  */
5659
5660           v->replaceable = 1;
5661           for (b = bl->biv; b; b = b->next_iv)
5662             {
5663               if (INSN_UID (b->insn) >= max_uid_for_loop
5664                   || ((uid_luid[INSN_UID (b->insn)]
5665                        >= uid_luid[REGNO_FIRST_UID (REGNO (dest_reg))])
5666                       && (uid_luid[INSN_UID (b->insn)]
5667                           <= uid_luid[REGNO_LAST_UID (REGNO (dest_reg))])))
5668                 {
5669                   v->replaceable = 0;
5670                   v->not_replaceable = 1;
5671                   break;
5672                 }
5673             }
5674
5675           /* If there are any backwards branches that go from after the
5676              biv update to before it, then this giv is not replaceable.  */
5677           if (v->replaceable)
5678             for (b = bl->biv; b; b = b->next_iv)
5679               if (back_branch_in_range_p (b->insn, loop_start, loop_end))
5680                 {
5681                   v->replaceable = 0;
5682                   v->not_replaceable = 1;
5683                   break;
5684                 }
5685         }
5686       else
5687         {
5688           /* May still be replaceable, we don't have enough info here to
5689              decide.  */
5690           v->replaceable = 0;
5691           v->not_replaceable = 0;
5692         }
5693     }
5694
5695   /* Record whether the add_val contains a const_int, for later use by
5696      combine_givs.  */
5697   {
5698     rtx tem = add_val;
5699
5700     v->no_const_addval = 1;
5701     if (tem == const0_rtx)
5702       ;
5703     else if (GET_CODE (tem) == CONST_INT)
5704       v->no_const_addval = 0;
5705     else if (GET_CODE (tem) == PLUS)
5706       {
5707         while (1)
5708           {
5709             if (GET_CODE (XEXP (tem, 0)) == PLUS)
5710               tem = XEXP (tem, 0);
5711             else if (GET_CODE (XEXP (tem, 1)) == PLUS)
5712               tem = XEXP (tem, 1);
5713             else
5714               break;
5715           }
5716         if (GET_CODE (XEXP (tem, 1)) == CONST_INT)
5717           v->no_const_addval = 0;
5718       }
5719   }
5720
5721   if (loop_dump_stream)
5722     {
5723       if (type == DEST_REG)
5724         fprintf (loop_dump_stream, "Insn %d: giv reg %d",
5725                  INSN_UID (insn), REGNO (dest_reg));
5726       else
5727         fprintf (loop_dump_stream, "Insn %d: dest address",
5728                  INSN_UID (insn));
5729
5730       fprintf (loop_dump_stream, " src reg %d benefit %d",
5731                REGNO (src_reg), v->benefit);
5732       fprintf (loop_dump_stream, " lifetime %d",
5733                v->lifetime);
5734
5735       if (v->replaceable)
5736         fprintf (loop_dump_stream, " replaceable");
5737
5738       if (v->no_const_addval)
5739         fprintf (loop_dump_stream, " ncav");
5740
5741       if (GET_CODE (mult_val) == CONST_INT)
5742         {
5743           fprintf (loop_dump_stream, " mult ");
5744           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (mult_val));
5745         }
5746       else
5747         {
5748           fprintf (loop_dump_stream, " mult ");
5749           print_rtl (loop_dump_stream, mult_val);
5750         }
5751
5752       if (GET_CODE (add_val) == CONST_INT)
5753         {
5754           fprintf (loop_dump_stream, " add ");
5755           fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (add_val));
5756         }
5757       else
5758         {
5759           fprintf (loop_dump_stream, " add ");
5760           print_rtl (loop_dump_stream, add_val);
5761         }
5762     }
5763
5764   if (loop_dump_stream)
5765     fprintf (loop_dump_stream, "\n");
5766
5767 }
5768
5769
5770 /* All this does is determine whether a giv can be made replaceable because
5771    its final value can be calculated.  This code can not be part of record_giv
5772    above, because final_giv_value requires that the number of loop iterations
5773    be known, and that can not be accurately calculated until after all givs
5774    have been identified.  */
5775
5776 static void
5777 check_final_value (v, loop_start, loop_end, n_iterations)
5778      struct induction *v;
5779      rtx loop_start, loop_end;
5780      unsigned HOST_WIDE_INT n_iterations;
5781 {
5782   struct iv_class *bl;
5783   rtx final_value = 0;
5784
5785   bl = reg_biv_class[REGNO (v->src_reg)];
5786
5787   /* DEST_ADDR givs will never reach here, because they are always marked
5788      replaceable above in record_giv.  */
5789
5790   /* The giv can be replaced outright by the reduced register only if all
5791      of the following conditions are true:
5792      - the insn that sets the giv is always executed on any iteration
5793        on which the giv is used at all
5794        (there are two ways to deduce this:
5795         either the insn is executed on every iteration,
5796         or all uses follow that insn in the same basic block),
5797      - its final value can be calculated (this condition is different
5798        than the one above in record_giv)
5799      - no assignments to the biv occur during the giv's lifetime.  */
5800
5801 #if 0
5802   /* This is only called now when replaceable is known to be false.  */
5803   /* Clear replaceable, so that it won't confuse final_giv_value.  */
5804   v->replaceable = 0;
5805 #endif
5806
5807   if ((final_value = final_giv_value (v, loop_start, loop_end, n_iterations))
5808       && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
5809     {
5810       int biv_increment_seen = 0;
5811       rtx p = v->insn;
5812       rtx last_giv_use;
5813
5814       v->replaceable = 1;
5815
5816       /* When trying to determine whether or not a biv increment occurs
5817          during the lifetime of the giv, we can ignore uses of the variable
5818          outside the loop because final_value is true.  Hence we can not
5819          use regno_last_uid and regno_first_uid as above in record_giv.  */
5820
5821       /* Search the loop to determine whether any assignments to the
5822          biv occur during the giv's lifetime.  Start with the insn
5823          that sets the giv, and search around the loop until we come
5824          back to that insn again.
5825
5826          Also fail if there is a jump within the giv's lifetime that jumps
5827          to somewhere outside the lifetime but still within the loop.  This
5828          catches spaghetti code where the execution order is not linear, and
5829          hence the above test fails.  Here we assume that the giv lifetime
5830          does not extend from one iteration of the loop to the next, so as
5831          to make the test easier.  Since the lifetime isn't known yet,
5832          this requires two loops.  See also record_giv above.  */
5833
5834       last_giv_use = v->insn;
5835
5836       while (1)
5837         {
5838           p = NEXT_INSN (p);
5839           if (p == loop_end)
5840             p = NEXT_INSN (loop_start);
5841           if (p == v->insn)
5842             break;
5843
5844           if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5845               || GET_CODE (p) == CALL_INSN)
5846             {
5847               if (biv_increment_seen)
5848                 {
5849                   if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5850                     {
5851                       v->replaceable = 0;
5852                       v->not_replaceable = 1;
5853                       break;
5854                     }
5855                 }
5856               else if (reg_set_p (v->src_reg, PATTERN (p)))
5857                 biv_increment_seen = 1;
5858               else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
5859                 last_giv_use = p;
5860             }
5861         }
5862       
5863       /* Now that the lifetime of the giv is known, check for branches
5864          from within the lifetime to outside the lifetime if it is still
5865          replaceable.  */
5866
5867       if (v->replaceable)
5868         {
5869           p = v->insn;
5870           while (1)
5871             {
5872               p = NEXT_INSN (p);
5873               if (p == loop_end)
5874                 p = NEXT_INSN (loop_start);
5875               if (p == last_giv_use)
5876                 break;
5877
5878               if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
5879                   && LABEL_NAME (JUMP_LABEL (p))
5880                   && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
5881                        && loop_insn_first_p (loop_start, JUMP_LABEL (p)))
5882                       || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
5883                           && loop_insn_first_p (JUMP_LABEL (p), loop_end))))
5884                 {
5885                   v->replaceable = 0;
5886                   v->not_replaceable = 1;
5887
5888                   if (loop_dump_stream)
5889                     fprintf (loop_dump_stream,
5890                              "Found branch outside giv lifetime.\n");
5891
5892                   break;
5893                 }
5894             }
5895         }
5896
5897       /* If it is replaceable, then save the final value.  */
5898       if (v->replaceable)
5899         v->final_value = final_value;
5900     }
5901
5902   if (loop_dump_stream && v->replaceable)
5903     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
5904              INSN_UID (v->insn), REGNO (v->dest_reg));
5905 }
5906 \f
5907 /* Update the status of whether a giv can derive other givs.
5908
5909    We need to do something special if there is or may be an update to the biv
5910    between the time the giv is defined and the time it is used to derive
5911    another giv.
5912
5913    In addition, a giv that is only conditionally set is not allowed to
5914    derive another giv once a label has been passed.
5915
5916    The cases we look at are when a label or an update to a biv is passed.  */
5917
5918 static void
5919 update_giv_derive (p)
5920      rtx p;
5921 {
5922   struct iv_class *bl;
5923   struct induction *biv, *giv;
5924   rtx tem;
5925   int dummy;
5926
5927   /* Search all IV classes, then all bivs, and finally all givs.
5928
5929      There are three cases we are concerned with.  First we have the situation
5930      of a giv that is only updated conditionally.  In that case, it may not
5931      derive any givs after a label is passed.
5932
5933      The second case is when a biv update occurs, or may occur, after the
5934      definition of a giv.  For certain biv updates (see below) that are
5935      known to occur between the giv definition and use, we can adjust the
5936      giv definition.  For others, or when the biv update is conditional,
5937      we must prevent the giv from deriving any other givs.  There are two
5938      sub-cases within this case.
5939
5940      If this is a label, we are concerned with any biv update that is done
5941      conditionally, since it may be done after the giv is defined followed by
5942      a branch here (actually, we need to pass both a jump and a label, but
5943      this extra tracking doesn't seem worth it).
5944
5945      If this is a jump, we are concerned about any biv update that may be
5946      executed multiple times.  We are actually only concerned about
5947      backward jumps, but it is probably not worth performing the test
5948      on the jump again here.
5949
5950      If this is a biv update, we must adjust the giv status to show that a
5951      subsequent biv update was performed.  If this adjustment cannot be done,
5952      the giv cannot derive further givs.  */
5953
5954   for (bl = loop_iv_list; bl; bl = bl->next)
5955     for (biv = bl->biv; biv; biv = biv->next_iv)
5956       if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
5957           || biv->insn == p)
5958         {
5959           for (giv = bl->giv; giv; giv = giv->next_iv)
5960             {
5961               /* If cant_derive is already true, there is no point in
5962                  checking all of these conditions again.  */
5963               if (giv->cant_derive)
5964                 continue;
5965
5966               /* If this giv is conditionally set and we have passed a label,
5967                  it cannot derive anything.  */
5968               if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
5969                 giv->cant_derive = 1;
5970
5971               /* Skip givs that have mult_val == 0, since
5972                  they are really invariants.  Also skip those that are
5973                  replaceable, since we know their lifetime doesn't contain
5974                  any biv update.  */
5975               else if (giv->mult_val == const0_rtx || giv->replaceable)
5976                 continue;
5977
5978               /* The only way we can allow this giv to derive another
5979                  is if this is a biv increment and we can form the product
5980                  of biv->add_val and giv->mult_val.  In this case, we will
5981                  be able to compute a compensation.  */
5982               else if (biv->insn == p)
5983                 {
5984                   tem = 0;
5985
5986                   if (biv->mult_val == const1_rtx)
5987                     tem = simplify_giv_expr (gen_rtx_MULT (giv->mode,
5988                                                            biv->add_val,
5989                                                            giv->mult_val),
5990                                              &dummy);
5991
5992                   if (tem && giv->derive_adjustment)
5993                     tem = simplify_giv_expr
5994                       (gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
5995                        &dummy);
5996
5997                   if (tem)
5998                     giv->derive_adjustment = tem;
5999                   else
6000                     giv->cant_derive = 1;
6001                 }
6002               else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
6003                        || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
6004                 giv->cant_derive = 1;
6005             }
6006         }
6007 }
6008 \f
6009 /* Check whether an insn is an increment legitimate for a basic induction var.
6010    X is the source of insn P, or a part of it.
6011    MODE is the mode in which X should be interpreted.
6012
6013    DEST_REG is the putative biv, also the destination of the insn.
6014    We accept patterns of these forms:
6015      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
6016      REG = INVARIANT + REG
6017
6018    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
6019    store the additive term into *INC_VAL, and store the place where
6020    we found the additive term into *LOCATION.
6021
6022    If X is an assignment of an invariant into DEST_REG, we set
6023    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
6024
6025    We also want to detect a BIV when it corresponds to a variable
6026    whose mode was promoted via PROMOTED_MODE.  In that case, an increment
6027    of the variable may be a PLUS that adds a SUBREG of that variable to
6028    an invariant and then sign- or zero-extends the result of the PLUS
6029    into the variable.
6030
6031    Most GIVs in such cases will be in the promoted mode, since that is the
6032    probably the natural computation mode (and almost certainly the mode
6033    used for addresses) on the machine.  So we view the pseudo-reg containing
6034    the variable as the BIV, as if it were simply incremented.
6035
6036    Note that treating the entire pseudo as a BIV will result in making
6037    simple increments to any GIVs based on it.  However, if the variable
6038    overflows in its declared mode but not its promoted mode, the result will
6039    be incorrect.  This is acceptable if the variable is signed, since 
6040    overflows in such cases are undefined, but not if it is unsigned, since
6041    those overflows are defined.  So we only check for SIGN_EXTEND and
6042    not ZERO_EXTEND.
6043
6044    If we cannot find a biv, we return 0.  */
6045
6046 static int
6047 basic_induction_var (x, mode, dest_reg, p, inc_val, mult_val, location)
6048      register rtx x;
6049      enum machine_mode mode;
6050      rtx p;
6051      rtx dest_reg;
6052      rtx *inc_val;
6053      rtx *mult_val;
6054      rtx **location;
6055 {
6056   register enum rtx_code code;
6057   rtx *argp, arg;
6058   rtx insn, set = 0;
6059
6060   code = GET_CODE (x);
6061   *location = NULL;
6062   switch (code)
6063     {
6064     case PLUS:
6065       if (rtx_equal_p (XEXP (x, 0), dest_reg)
6066           || (GET_CODE (XEXP (x, 0)) == SUBREG
6067               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
6068               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
6069         {
6070           argp = &XEXP (x, 1);
6071         }
6072       else if (rtx_equal_p (XEXP (x, 1), dest_reg)
6073                || (GET_CODE (XEXP (x, 1)) == SUBREG
6074                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
6075                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
6076         {
6077           argp = &XEXP (x, 0);
6078         }
6079       else
6080         return 0;
6081
6082       arg = *argp;
6083       if (invariant_p (arg) != 1)
6084         return 0;
6085
6086       *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
6087       *mult_val = const1_rtx;
6088       *location = argp;
6089       return 1;
6090
6091     case SUBREG:
6092       /* If this is a SUBREG for a promoted variable, check the inner
6093          value.  */
6094       if (SUBREG_PROMOTED_VAR_P (x))
6095         return basic_induction_var (SUBREG_REG (x), GET_MODE (SUBREG_REG (x)),
6096                                     dest_reg, p, inc_val, mult_val, location);
6097       return 0;
6098
6099     case REG:
6100       /* If this register is assigned in a previous insn, look at its
6101          source, but don't go outside the loop or past a label.  */
6102
6103       insn = p;
6104       while (1)
6105         {
6106           do {
6107             insn = PREV_INSN (insn);
6108           } while (insn && GET_CODE (insn) == NOTE
6109                    && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6110
6111           if (!insn)
6112             break;
6113           set = single_set (insn);
6114           if (set == 0)
6115             break;
6116
6117           if ((SET_DEST (set) == x
6118                || (GET_CODE (SET_DEST (set)) == SUBREG
6119                    && (GET_MODE_SIZE (GET_MODE (SET_DEST (set)))
6120                        <= UNITS_PER_WORD)
6121                    && (GET_MODE_CLASS (GET_MODE (SET_DEST (set)))
6122                        == MODE_INT)
6123                    && SUBREG_REG (SET_DEST (set)) == x))
6124               && basic_induction_var (SET_SRC (set),
6125                                       (GET_MODE (SET_SRC (set)) == VOIDmode
6126                                        ? GET_MODE (x)
6127                                        : GET_MODE (SET_SRC (set))),
6128                                       dest_reg, insn,
6129                                       inc_val, mult_val, location))
6130             return 1;
6131         }
6132       /* ... fall through ...  */
6133
6134       /* Can accept constant setting of biv only when inside inner most loop.
6135          Otherwise, a biv of an inner loop may be incorrectly recognized
6136          as a biv of the outer loop,
6137          causing code to be moved INTO the inner loop.  */
6138     case MEM:
6139       if (invariant_p (x) != 1)
6140         return 0;
6141     case CONST_INT:
6142     case SYMBOL_REF:
6143     case CONST:
6144       /* convert_modes aborts if we try to convert to or from CCmode, so just
6145          exclude that case.  It is very unlikely that a condition code value
6146          would be a useful iterator anyways.  */
6147       if (this_loop_info.loops_enclosed == 1
6148           && GET_MODE_CLASS (mode) != MODE_CC
6149           && GET_MODE_CLASS (GET_MODE (dest_reg)) != MODE_CC)
6150         {
6151           /* Possible bug here?  Perhaps we don't know the mode of X.  */
6152           *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6153           *mult_val = const0_rtx;
6154           return 1;
6155         }
6156       else
6157         return 0;
6158
6159     case SIGN_EXTEND:
6160       return basic_induction_var (XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6161                                   dest_reg, p, inc_val, mult_val, location);
6162
6163     case ASHIFTRT:
6164       /* Similar, since this can be a sign extension.  */
6165       for (insn = PREV_INSN (p);
6166            (insn && GET_CODE (insn) == NOTE
6167             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6168            insn = PREV_INSN (insn))
6169         ;
6170
6171       if (insn)
6172         set = single_set (insn);
6173
6174       if (set && SET_DEST (set) == XEXP (x, 0)
6175           && GET_CODE (XEXP (x, 1)) == CONST_INT
6176           && INTVAL (XEXP (x, 1)) >= 0
6177           && GET_CODE (SET_SRC (set)) == ASHIFT
6178           && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
6179         return basic_induction_var (XEXP (SET_SRC (set), 0),
6180                                     GET_MODE (XEXP (x, 0)),
6181                                     dest_reg, insn, inc_val, mult_val,
6182                                     location);
6183       return 0;
6184
6185     default:
6186       return 0;
6187     }
6188 }
6189 \f
6190 /* A general induction variable (giv) is any quantity that is a linear
6191    function   of a basic induction variable,
6192    i.e. giv = biv * mult_val + add_val.
6193    The coefficients can be any loop invariant quantity.
6194    A giv need not be computed directly from the biv;
6195    it can be computed by way of other givs.  */
6196
6197 /* Determine whether X computes a giv.
6198    If it does, return a nonzero value
6199      which is the benefit from eliminating the computation of X;
6200    set *SRC_REG to the register of the biv that it is computed from;
6201    set *ADD_VAL and *MULT_VAL to the coefficients,
6202      such that the value of X is biv * mult + add;  */
6203
6204 static int
6205 general_induction_var (x, src_reg, add_val, mult_val, is_addr, pbenefit)
6206      rtx x;
6207      rtx *src_reg;
6208      rtx *add_val;
6209      rtx *mult_val;
6210      int is_addr;
6211      int *pbenefit;
6212 {
6213   rtx orig_x = x;
6214   char *storage;
6215
6216   /* If this is an invariant, forget it, it isn't a giv.  */
6217   if (invariant_p (x) == 1)
6218     return 0;
6219
6220   /* See if the expression could be a giv and get its form.
6221      Mark our place on the obstack in case we don't find a giv.  */
6222   storage = (char *) oballoc (0);
6223   *pbenefit = 0;
6224   x = simplify_giv_expr (x, pbenefit);
6225   if (x == 0)
6226     {
6227       obfree (storage);
6228       return 0;
6229     }
6230
6231   switch (GET_CODE (x))
6232     {
6233     case USE:
6234     case CONST_INT:
6235       /* Since this is now an invariant and wasn't before, it must be a giv
6236          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
6237          with.  */
6238       *src_reg = loop_iv_list->biv->dest_reg;
6239       *mult_val = const0_rtx;
6240       *add_val = x;
6241       break;
6242
6243     case REG:
6244       /* This is equivalent to a BIV.  */
6245       *src_reg = x;
6246       *mult_val = const1_rtx;
6247       *add_val = const0_rtx;
6248       break;
6249
6250     case PLUS:
6251       /* Either (plus (biv) (invar)) or
6252          (plus (mult (biv) (invar_1)) (invar_2)).  */
6253       if (GET_CODE (XEXP (x, 0)) == MULT)
6254         {
6255           *src_reg = XEXP (XEXP (x, 0), 0);
6256           *mult_val = XEXP (XEXP (x, 0), 1);
6257         }
6258       else
6259         {
6260           *src_reg = XEXP (x, 0);
6261           *mult_val = const1_rtx;
6262         }
6263       *add_val = XEXP (x, 1);
6264       break;
6265
6266     case MULT:
6267       /* ADD_VAL is zero.  */
6268       *src_reg = XEXP (x, 0);
6269       *mult_val = XEXP (x, 1);
6270       *add_val = const0_rtx;
6271       break;
6272
6273     default:
6274       abort ();
6275     }
6276
6277   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6278      unless they are CONST_INT).  */
6279   if (GET_CODE (*add_val) == USE)
6280     *add_val = XEXP (*add_val, 0);
6281   if (GET_CODE (*mult_val) == USE)
6282     *mult_val = XEXP (*mult_val, 0);
6283
6284   if (is_addr)
6285     {
6286 #ifdef ADDRESS_COST
6287       *pbenefit += ADDRESS_COST (orig_x) - reg_address_cost;
6288 #else
6289       *pbenefit += rtx_cost (orig_x, MEM) - reg_address_cost;
6290 #endif
6291     }
6292   else
6293     *pbenefit += rtx_cost (orig_x, SET);
6294
6295   /* Always return true if this is a giv so it will be detected as such,
6296      even if the benefit is zero or negative.  This allows elimination  
6297      of bivs that might otherwise not be eliminated.  */                
6298   return 1;                                                             
6299 }
6300 \f
6301 /* Given an expression, X, try to form it as a linear function of a biv.
6302    We will canonicalize it to be of the form
6303         (plus (mult (BIV) (invar_1))
6304               (invar_2))
6305    with possible degeneracies.
6306
6307    The invariant expressions must each be of a form that can be used as a
6308    machine operand.  We surround then with a USE rtx (a hack, but localized
6309    and certainly unambiguous!) if not a CONST_INT for simplicity in this
6310    routine; it is the caller's responsibility to strip them.
6311
6312    If no such canonicalization is possible (i.e., two biv's are used or an
6313    expression that is neither invariant nor a biv or giv), this routine
6314    returns 0.
6315
6316    For a non-zero return, the result will have a code of CONST_INT, USE,
6317    REG (for a BIV), PLUS, or MULT.  No other codes will occur.  
6318
6319    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
6320
6321 static rtx sge_plus PARAMS ((enum machine_mode, rtx, rtx));
6322 static rtx sge_plus_constant PARAMS ((rtx, rtx));
6323 static int cmp_combine_givs_stats PARAMS ((const PTR, const PTR));
6324 static int cmp_recombine_givs_stats PARAMS ((const PTR, const PTR));
6325
6326 static rtx
6327 simplify_giv_expr (x, benefit)
6328      rtx x;
6329      int *benefit;
6330 {
6331   enum machine_mode mode = GET_MODE (x);
6332   rtx arg0, arg1;
6333   rtx tem;
6334
6335   /* If this is not an integer mode, or if we cannot do arithmetic in this
6336      mode, this can't be a giv.  */
6337   if (mode != VOIDmode
6338       && (GET_MODE_CLASS (mode) != MODE_INT
6339           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6340     return NULL_RTX;
6341
6342   switch (GET_CODE (x))
6343     {
6344     case PLUS:
6345       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
6346       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
6347       if (arg0 == 0 || arg1 == 0)
6348         return NULL_RTX;
6349
6350       /* Put constant last, CONST_INT last if both constant.  */
6351       if ((GET_CODE (arg0) == USE
6352            || GET_CODE (arg0) == CONST_INT)
6353           && ! ((GET_CODE (arg0) == USE
6354                  && GET_CODE (arg1) == USE)
6355                 || GET_CODE (arg1) == CONST_INT))
6356         tem = arg0, arg0 = arg1, arg1 = tem;
6357
6358       /* Handle addition of zero, then addition of an invariant.  */
6359       if (arg1 == const0_rtx)
6360         return arg0;
6361       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6362         switch (GET_CODE (arg0))
6363           {
6364           case CONST_INT:
6365           case USE:
6366             /* Adding two invariants must result in an invariant, so enclose
6367                addition operation inside a USE and return it.  */
6368             if (GET_CODE (arg0) == USE)
6369               arg0 = XEXP (arg0, 0);
6370             if (GET_CODE (arg1) == USE)
6371               arg1 = XEXP (arg1, 0);
6372
6373             if (GET_CODE (arg0) == CONST_INT)
6374               tem = arg0, arg0 = arg1, arg1 = tem;
6375             if (GET_CODE (arg1) == CONST_INT)
6376               tem = sge_plus_constant (arg0, arg1);
6377             else
6378               tem = sge_plus (mode, arg0, arg1);
6379
6380             if (GET_CODE (tem) != CONST_INT)
6381               tem = gen_rtx_USE (mode, tem);
6382             return tem;
6383
6384           case REG:
6385           case MULT:
6386             /* biv + invar or mult + invar.  Return sum.  */
6387             return gen_rtx_PLUS (mode, arg0, arg1);
6388
6389           case PLUS:
6390             /* (a + invar_1) + invar_2.  Associate.  */
6391             return
6392               simplify_giv_expr (gen_rtx_PLUS (mode,
6393                                                XEXP (arg0, 0),
6394                                                gen_rtx_PLUS (mode,
6395                                                              XEXP (arg0, 1),
6396                                                              arg1)),
6397                                  benefit);
6398
6399           default:
6400             abort ();
6401           }
6402
6403       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
6404          MULT to reduce cases.  */
6405       if (GET_CODE (arg0) == REG)
6406         arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6407       if (GET_CODE (arg1) == REG)
6408         arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6409
6410       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6411          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6412          Recurse to associate the second PLUS.  */
6413       if (GET_CODE (arg1) == MULT)
6414         tem = arg0, arg0 = arg1, arg1 = tem;
6415
6416       if (GET_CODE (arg1) == PLUS)
6417           return
6418             simplify_giv_expr (gen_rtx_PLUS (mode,
6419                                              gen_rtx_PLUS (mode, arg0,
6420                                                            XEXP (arg1, 0)),
6421                                              XEXP (arg1, 1)),
6422                                benefit);
6423
6424       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
6425       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6426         return NULL_RTX;
6427
6428       if (!rtx_equal_p (arg0, arg1))
6429         return NULL_RTX;
6430
6431       return simplify_giv_expr (gen_rtx_MULT (mode,
6432                                               XEXP (arg0, 0),
6433                                               gen_rtx_PLUS (mode,
6434                                                             XEXP (arg0, 1),
6435                                                             XEXP (arg1, 1))),
6436                                 benefit);
6437
6438     case MINUS:
6439       /* Handle "a - b" as "a + b * (-1)".  */
6440       return simplify_giv_expr (gen_rtx_PLUS (mode,
6441                                               XEXP (x, 0),
6442                                               gen_rtx_MULT (mode,
6443                                                             XEXP (x, 1),
6444                                                             constm1_rtx)),
6445                                 benefit);
6446
6447     case MULT:
6448       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
6449       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
6450       if (arg0 == 0 || arg1 == 0)
6451         return NULL_RTX;
6452
6453       /* Put constant last, CONST_INT last if both constant.  */
6454       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6455           && GET_CODE (arg1) != CONST_INT)
6456         tem = arg0, arg0 = arg1, arg1 = tem;
6457
6458       /* If second argument is not now constant, not giv.  */
6459       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6460         return NULL_RTX;
6461
6462       /* Handle multiply by 0 or 1.  */
6463       if (arg1 == const0_rtx)
6464         return const0_rtx;
6465
6466       else if (arg1 == const1_rtx)
6467         return arg0;
6468
6469       switch (GET_CODE (arg0))
6470         {
6471         case REG:
6472           /* biv * invar.  Done.  */
6473           return gen_rtx_MULT (mode, arg0, arg1);
6474
6475         case CONST_INT:
6476           /* Product of two constants.  */
6477           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6478
6479         case USE:
6480           /* invar * invar.  It is a giv, but very few of these will 
6481              actually pay off, so limit to simple registers.  */
6482           if (GET_CODE (arg1) != CONST_INT)
6483             return NULL_RTX;
6484
6485           arg0 = XEXP (arg0, 0);
6486           if (GET_CODE (arg0) == REG)
6487             tem = gen_rtx_MULT (mode, arg0, arg1);
6488           else if (GET_CODE (arg0) == MULT
6489                    && GET_CODE (XEXP (arg0, 0)) == REG
6490                    && GET_CODE (XEXP (arg0, 1)) == CONST_INT)
6491             {
6492               tem = gen_rtx_MULT (mode, XEXP (arg0, 0), 
6493                                   GEN_INT (INTVAL (XEXP (arg0, 1))
6494                                            * INTVAL (arg1)));
6495             }
6496           else
6497             return NULL_RTX;
6498           return gen_rtx_USE (mode, tem);
6499
6500         case MULT:
6501           /* (a * invar_1) * invar_2.  Associate.  */
6502           return simplify_giv_expr (gen_rtx_MULT (mode,
6503                                                   XEXP (arg0, 0),
6504                                                   gen_rtx_MULT (mode,
6505                                                                 XEXP (arg0, 1),
6506                                                                 arg1)),
6507                                     benefit);
6508
6509         case PLUS:
6510           /* (a + invar_1) * invar_2.  Distribute.  */
6511           return simplify_giv_expr (gen_rtx_PLUS (mode,
6512                                                   gen_rtx_MULT (mode,
6513                                                                 XEXP (arg0, 0),
6514                                                                 arg1),
6515                                                   gen_rtx_MULT (mode,
6516                                                                 XEXP (arg0, 1),
6517                                                                 arg1)),
6518                                     benefit);
6519
6520         default:
6521           abort ();
6522         }
6523
6524     case ASHIFT:
6525       /* Shift by constant is multiply by power of two.  */
6526       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6527         return 0;
6528
6529       return
6530         simplify_giv_expr (gen_rtx_MULT (mode,
6531                                          XEXP (x, 0),
6532                                          GEN_INT ((HOST_WIDE_INT) 1
6533                                                   << INTVAL (XEXP (x, 1)))),
6534                            benefit);
6535
6536     case NEG:
6537       /* "-a" is "a * (-1)" */
6538       return simplify_giv_expr (gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6539                                 benefit);
6540
6541     case NOT:
6542       /* "~a" is "-a - 1". Silly, but easy.  */
6543       return simplify_giv_expr (gen_rtx_MINUS (mode,
6544                                                gen_rtx_NEG (mode, XEXP (x, 0)),
6545                                                const1_rtx),
6546                                 benefit);
6547
6548     case USE:
6549       /* Already in proper form for invariant.  */
6550       return x;
6551
6552     case REG:
6553       /* If this is a new register, we can't deal with it.  */
6554       if (REGNO (x) >= max_reg_before_loop)
6555         return 0;
6556
6557       /* Check for biv or giv.  */
6558       switch (REG_IV_TYPE (REGNO (x)))
6559         {
6560         case BASIC_INDUCT:
6561           return x;
6562         case GENERAL_INDUCT:
6563           {
6564             struct induction *v = REG_IV_INFO (REGNO (x));
6565
6566             /* Form expression from giv and add benefit.  Ensure this giv
6567                can derive another and subtract any needed adjustment if so.  */
6568             *benefit += v->benefit;
6569             if (v->cant_derive)
6570               return 0;
6571
6572             tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6573                                                     v->src_reg, v->mult_val),
6574                                 v->add_val);
6575
6576             if (v->derive_adjustment)
6577               tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6578             return simplify_giv_expr (tem, benefit);
6579           }
6580
6581         default:
6582           /* If it isn't an induction variable, and it is invariant, we
6583              may be able to simplify things further by looking through
6584              the bits we just moved outside the loop.  */
6585           if (invariant_p (x) == 1)
6586             {
6587               struct movable *m;
6588
6589               for (m = the_movables; m ; m = m->next)
6590                 if (rtx_equal_p (x, m->set_dest))
6591                   {
6592                     /* Ok, we found a match.  Substitute and simplify.  */
6593
6594                     /* If we match another movable, we must use that, as 
6595                        this one is going away.  */
6596                     if (m->match)
6597                       return simplify_giv_expr (m->match->set_dest, benefit);
6598
6599                     /* If consec is non-zero, this is a member of a group of
6600                        instructions that were moved together.  We handle this
6601                        case only to the point of seeking to the last insn and
6602                        looking for a REG_EQUAL.  Fail if we don't find one.  */
6603                     if (m->consec != 0)
6604                       {
6605                         int i = m->consec;
6606                         tem = m->insn;
6607                         do { tem = NEXT_INSN (tem); } while (--i > 0);
6608
6609                         tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6610                         if (tem)
6611                           tem = XEXP (tem, 0);
6612                       }
6613                     else
6614                       {
6615                         tem = single_set (m->insn);
6616                         if (tem)
6617                           tem = SET_SRC (tem);
6618                       }
6619
6620                     if (tem)
6621                       {
6622                         /* What we are most interested in is pointer
6623                            arithmetic on invariants -- only take
6624                            patterns we may be able to do something with.  */
6625                         if (GET_CODE (tem) == PLUS
6626                             || GET_CODE (tem) == MULT
6627                             || GET_CODE (tem) == ASHIFT
6628                             || GET_CODE (tem) == CONST_INT
6629                             || GET_CODE (tem) == SYMBOL_REF)
6630                           {
6631                             tem = simplify_giv_expr (tem, benefit);
6632                             if (tem)
6633                               return tem;
6634                           }
6635                         else if (GET_CODE (tem) == CONST
6636                             && GET_CODE (XEXP (tem, 0)) == PLUS
6637                             && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
6638                             && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
6639                           {
6640                             tem = simplify_giv_expr (XEXP (tem, 0), benefit);
6641                             if (tem)
6642                               return tem;
6643                           }
6644                       }
6645                     break;
6646                   }
6647             }
6648           break;
6649         }
6650
6651       /* Fall through to general case.  */
6652     default:
6653       /* If invariant, return as USE (unless CONST_INT).
6654          Otherwise, not giv.  */
6655       if (GET_CODE (x) == USE)
6656         x = XEXP (x, 0);
6657
6658       if (invariant_p (x) == 1)
6659         {
6660           if (GET_CODE (x) == CONST_INT)
6661             return x;
6662           if (GET_CODE (x) == CONST
6663               && GET_CODE (XEXP (x, 0)) == PLUS
6664               && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
6665               && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
6666             x = XEXP (x, 0);
6667           return gen_rtx_USE (mode, x);
6668         }
6669       else
6670         return 0;
6671     }
6672 }
6673
6674 /* This routine folds invariants such that there is only ever one
6675    CONST_INT in the summation.  It is only used by simplify_giv_expr.  */
6676
6677 static rtx
6678 sge_plus_constant (x, c)
6679      rtx x, c;
6680 {
6681   if (GET_CODE (x) == CONST_INT)
6682     return GEN_INT (INTVAL (x) + INTVAL (c));
6683   else if (GET_CODE (x) != PLUS)
6684     return gen_rtx_PLUS (GET_MODE (x), x, c);
6685   else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6686     {
6687       return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
6688                            GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
6689     }
6690   else if (GET_CODE (XEXP (x, 0)) == PLUS
6691            || GET_CODE (XEXP (x, 1)) != PLUS)
6692     {
6693       return gen_rtx_PLUS (GET_MODE (x),
6694                            sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
6695     }
6696   else
6697     {
6698       return gen_rtx_PLUS (GET_MODE (x),
6699                            sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
6700     }
6701 }
6702
6703 static rtx
6704 sge_plus (mode, x, y)
6705      enum machine_mode mode;
6706      rtx x, y;
6707 {
6708   while (GET_CODE (y) == PLUS)
6709     {
6710       rtx a = XEXP (y, 0);
6711       if (GET_CODE (a) == CONST_INT)
6712         x = sge_plus_constant (x, a);
6713       else
6714         x = gen_rtx_PLUS (mode, x, a);
6715       y = XEXP (y, 1);
6716     }
6717   if (GET_CODE (y) == CONST_INT)
6718     x = sge_plus_constant (x, y);
6719   else
6720     x = gen_rtx_PLUS (mode, x, y);
6721   return x;
6722 }
6723 \f
6724 /* Help detect a giv that is calculated by several consecutive insns;
6725    for example,
6726       giv = biv * M
6727       giv = giv + A
6728    The caller has already identified the first insn P as having a giv as dest;
6729    we check that all other insns that set the same register follow
6730    immediately after P, that they alter nothing else,
6731    and that the result of the last is still a giv.
6732
6733    The value is 0 if the reg set in P is not really a giv.
6734    Otherwise, the value is the amount gained by eliminating
6735    all the consecutive insns that compute the value.
6736
6737    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
6738    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
6739
6740    The coefficients of the ultimate giv value are stored in
6741    *MULT_VAL and *ADD_VAL.  */
6742
6743 static int
6744 consec_sets_giv (first_benefit, p, src_reg, dest_reg,
6745                  add_val, mult_val, last_consec_insn)
6746      int first_benefit;
6747      rtx p;
6748      rtx src_reg;
6749      rtx dest_reg;
6750      rtx *add_val;
6751      rtx *mult_val;
6752      rtx *last_consec_insn;
6753 {
6754   int count;
6755   enum rtx_code code;
6756   int benefit;
6757   rtx temp;
6758   rtx set;
6759
6760   /* Indicate that this is a giv so that we can update the value produced in
6761      each insn of the multi-insn sequence. 
6762
6763      This induction structure will be used only by the call to
6764      general_induction_var below, so we can allocate it on our stack.
6765      If this is a giv, our caller will replace the induct var entry with
6766      a new induction structure.  */
6767   struct induction *v
6768     = (struct induction *) alloca (sizeof (struct induction));
6769   v->src_reg = src_reg;
6770   v->mult_val = *mult_val;
6771   v->add_val = *add_val;
6772   v->benefit = first_benefit;
6773   v->cant_derive = 0;
6774   v->derive_adjustment = 0;
6775
6776   REG_IV_TYPE (REGNO (dest_reg)) = GENERAL_INDUCT;
6777   REG_IV_INFO (REGNO (dest_reg)) = v;
6778
6779   count = VARRAY_INT (n_times_set, REGNO (dest_reg)) - 1;
6780
6781   while (count > 0)
6782     {
6783       p = NEXT_INSN (p);
6784       code = GET_CODE (p);
6785
6786       /* If libcall, skip to end of call sequence.  */
6787       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
6788         p = XEXP (temp, 0);
6789
6790       if (code == INSN
6791           && (set = single_set (p))
6792           && GET_CODE (SET_DEST (set)) == REG
6793           && SET_DEST (set) == dest_reg
6794           && (general_induction_var (SET_SRC (set), &src_reg,
6795                                      add_val, mult_val, 0, &benefit)
6796               /* Giv created by equivalent expression.  */
6797               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
6798                   && general_induction_var (XEXP (temp, 0), &src_reg,
6799                                             add_val, mult_val, 0, &benefit)))
6800           && src_reg == v->src_reg)
6801         {
6802           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
6803             benefit += libcall_benefit (p);
6804
6805           count--;
6806           v->mult_val = *mult_val;
6807           v->add_val = *add_val;
6808           v->benefit = benefit;
6809         }
6810       else if (code != NOTE)
6811         {
6812           /* Allow insns that set something other than this giv to a
6813              constant.  Such insns are needed on machines which cannot
6814              include long constants and should not disqualify a giv.  */
6815           if (code == INSN
6816               && (set = single_set (p))
6817               && SET_DEST (set) != dest_reg
6818               && CONSTANT_P (SET_SRC (set)))
6819             continue;
6820
6821           REG_IV_TYPE (REGNO (dest_reg)) = UNKNOWN_INDUCT;
6822           return 0;
6823         }
6824     }
6825
6826   *last_consec_insn = p;
6827   return v->benefit;
6828 }
6829 \f
6830 /* Return an rtx, if any, that expresses giv G2 as a function of the register
6831    represented by G1.  If no such expression can be found, or it is clear that
6832    it cannot possibly be a valid address, 0 is returned. 
6833
6834    To perform the computation, we note that
6835         G1 = x * v + a          and
6836         G2 = y * v + b
6837    where `v' is the biv.
6838
6839    So G2 = (y/b) * G1 + (b - a*y/x).
6840
6841    Note that MULT = y/x.
6842
6843    Update: A and B are now allowed to be additive expressions such that
6844    B contains all variables in A.  That is, computing B-A will not require
6845    subtracting variables.  */
6846
6847 static rtx
6848 express_from_1 (a, b, mult)
6849      rtx a, b, mult;
6850 {
6851   /* If MULT is zero, then A*MULT is zero, and our expression is B.  */
6852
6853   if (mult == const0_rtx)
6854     return b;
6855
6856   /* If MULT is not 1, we cannot handle A with non-constants, since we
6857      would then be required to subtract multiples of the registers in A.
6858      This is theoretically possible, and may even apply to some Fortran
6859      constructs, but it is a lot of work and we do not attempt it here.  */
6860
6861   if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
6862     return NULL_RTX;
6863
6864   /* In general these structures are sorted top to bottom (down the PLUS
6865      chain), but not left to right across the PLUS.  If B is a higher
6866      order giv than A, we can strip one level and recurse.  If A is higher
6867      order, we'll eventually bail out, but won't know that until the end.
6868      If they are the same, we'll strip one level around this loop.  */
6869
6870   while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
6871     {
6872       rtx ra, rb, oa, ob, tmp;
6873
6874       ra = XEXP (a, 0), oa = XEXP (a, 1);
6875       if (GET_CODE (ra) == PLUS)
6876         tmp = ra, ra = oa, oa = tmp;
6877
6878       rb = XEXP (b, 0), ob = XEXP (b, 1);
6879       if (GET_CODE (rb) == PLUS)
6880         tmp = rb, rb = ob, ob = tmp;
6881
6882       if (rtx_equal_p (ra, rb))
6883         /* We matched: remove one reg completely.  */
6884         a = oa, b = ob;
6885       else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
6886         /* An alternate match.  */
6887         a = oa, b = rb;
6888       else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
6889         /* An alternate match.  */
6890         a = ra, b = ob;
6891       else
6892         {
6893           /* Indicates an extra register in B.  Strip one level from B and 
6894              recurse, hoping B was the higher order expression.  */
6895           ob = express_from_1 (a, ob, mult);
6896           if (ob == NULL_RTX)
6897             return NULL_RTX;
6898           return gen_rtx_PLUS (GET_MODE (b), rb, ob);
6899         }
6900     }
6901
6902   /* Here we are at the last level of A, go through the cases hoping to
6903      get rid of everything but a constant.  */
6904
6905   if (GET_CODE (a) == PLUS)
6906     {
6907       rtx ra, oa;
6908
6909       ra = XEXP (a, 0), oa = XEXP (a, 1);
6910       if (rtx_equal_p (oa, b))
6911         oa = ra;
6912       else if (!rtx_equal_p (ra, b))
6913         return NULL_RTX;
6914
6915       if (GET_CODE (oa) != CONST_INT)
6916         return NULL_RTX;
6917
6918       return GEN_INT (-INTVAL (oa) * INTVAL (mult));
6919     }
6920   else if (GET_CODE (a) == CONST_INT)
6921     {
6922       return plus_constant (b, -INTVAL (a) * INTVAL (mult));
6923     }
6924   else if (GET_CODE (b) == PLUS)
6925     {
6926       if (rtx_equal_p (a, XEXP (b, 0)))
6927         return XEXP (b, 1);
6928       else if (rtx_equal_p (a, XEXP (b, 1)))
6929         return XEXP (b, 0);
6930       else
6931         return NULL_RTX;
6932     }
6933   else if (rtx_equal_p (a, b))
6934     return const0_rtx;
6935
6936   return NULL_RTX;
6937 }
6938
6939 rtx
6940 express_from (g1, g2)
6941      struct induction *g1, *g2;
6942 {
6943   rtx mult, add;
6944
6945   /* The value that G1 will be multiplied by must be a constant integer.  Also,
6946      the only chance we have of getting a valid address is if b*c/a (see above
6947      for notation) is also an integer.  */
6948   if (GET_CODE (g1->mult_val) == CONST_INT
6949       && GET_CODE (g2->mult_val) == CONST_INT)
6950     {
6951       if (g1->mult_val == const0_rtx
6952           || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
6953         return NULL_RTX;
6954       mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
6955     }
6956   else if (rtx_equal_p (g1->mult_val, g2->mult_val))
6957     mult = const1_rtx;
6958   else
6959     {
6960       /* ??? Find out if the one is a multiple of the other?  */
6961       return NULL_RTX;
6962     }
6963
6964   add = express_from_1 (g1->add_val, g2->add_val, mult);
6965   if (add == NULL_RTX)
6966     {
6967       /* Failed.  If we've got a multiplication factor between G1 and G2,
6968          scale G1's addend and try again.  */
6969       if (INTVAL (mult) > 1)
6970         {
6971           rtx g1_add_val = g1->add_val;
6972           if (GET_CODE (g1_add_val) == MULT
6973               && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
6974             {
6975               HOST_WIDE_INT m;
6976               m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
6977               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
6978                                          XEXP (g1_add_val, 0), GEN_INT (m));
6979             }
6980           else
6981             {
6982               g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
6983                                          mult);
6984             }
6985
6986           add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
6987         }
6988     }
6989   if (add == NULL_RTX)
6990     return NULL_RTX;
6991
6992   /* Form simplified final result.  */
6993   if (mult == const0_rtx)
6994     return add;
6995   else if (mult == const1_rtx)
6996     mult = g1->dest_reg;
6997   else
6998     mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
6999
7000   if (add == const0_rtx)
7001     return mult;
7002   else
7003     {
7004       if (GET_CODE (add) == PLUS
7005           && CONSTANT_P (XEXP (add, 1)))
7006         {
7007           rtx tem = XEXP (add, 1);
7008           mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
7009           add = tem;
7010         }
7011       
7012       return gen_rtx_PLUS (g2->mode, mult, add);
7013     }
7014   
7015 }
7016 \f
7017 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7018    represented by G1.  This indicates that G2 should be combined with G1 and
7019    that G2 can use (either directly or via an address expression) a register
7020    used to represent G1.  */
7021
7022 static rtx
7023 combine_givs_p (g1, g2)
7024      struct induction *g1, *g2;
7025 {
7026   rtx tem = express_from (g1, g2);
7027
7028   /* If these givs are identical, they can be combined.  We use the results
7029      of express_from because the addends are not in a canonical form, so
7030      rtx_equal_p is a weaker test.  */
7031   /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
7032      combination to be the other way round.  */
7033   if (tem == g1->dest_reg
7034       && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
7035     {
7036       return g1->dest_reg;
7037     }
7038
7039   /* If G2 can be expressed as a function of G1 and that function is valid
7040      as an address and no more expensive than using a register for G2,
7041      the expression of G2 in terms of G1 can be used.  */
7042   if (tem != NULL_RTX
7043       && g2->giv_type == DEST_ADDR
7044       && memory_address_p (g2->mem_mode, tem)
7045       /* ??? Looses, especially with -fforce-addr, where *g2->location
7046          will always be a register, and so anything more complicated
7047          gets discarded.  */
7048 #if 0
7049 #ifdef ADDRESS_COST
7050       && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location)
7051 #else
7052       && rtx_cost (tem, MEM) <= rtx_cost (*g2->location, MEM)
7053 #endif
7054 #endif
7055       )
7056     {
7057       return tem;
7058     }
7059
7060   return NULL_RTX;
7061 }
7062 \f
7063 struct combine_givs_stats
7064 {
7065   int giv_number;
7066   int total_benefit;
7067 };
7068
7069 static int
7070 cmp_combine_givs_stats (xp, yp)
7071      const PTR xp;
7072      const PTR yp;
7073 {
7074   const struct combine_givs_stats * const x =
7075     (const struct combine_givs_stats *) xp;
7076   const struct combine_givs_stats * const y =
7077     (const struct combine_givs_stats *) yp;
7078   int d;
7079   d = y->total_benefit - x->total_benefit;
7080   /* Stabilize the sort.  */
7081   if (!d)
7082     d = x->giv_number - y->giv_number;
7083   return d;
7084 }
7085
7086 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7087    any other.  If so, point SAME to the giv combined with and set NEW_REG to
7088    be an expression (in terms of the other giv's DEST_REG) equivalent to the
7089    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
7090
7091 static void
7092 combine_givs (bl)
7093      struct iv_class *bl;
7094 {
7095   /* Additional benefit to add for being combined multiple times.  */
7096   const int extra_benefit = 3;
7097
7098   struct induction *g1, *g2, **giv_array;
7099   int i, j, k, giv_count;
7100   struct combine_givs_stats *stats;
7101   rtx *can_combine;
7102
7103   /* Count givs, because bl->giv_count is incorrect here.  */
7104   giv_count = 0;
7105   for (g1 = bl->giv; g1; g1 = g1->next_iv)
7106     if (!g1->ignore)
7107       giv_count++;
7108
7109   giv_array
7110     = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7111   i = 0;
7112   for (g1 = bl->giv; g1; g1 = g1->next_iv)
7113     if (!g1->ignore)
7114       giv_array[i++] = g1;
7115
7116   stats = (struct combine_givs_stats *) alloca (giv_count * sizeof (*stats));
7117   bzero ((char *) stats, giv_count * sizeof (*stats));
7118
7119   can_combine = (rtx *) alloca (giv_count * giv_count * sizeof(rtx));
7120   bzero ((char *) can_combine, giv_count * giv_count * sizeof(rtx));
7121
7122   for (i = 0; i < giv_count; i++)
7123     {
7124       int this_benefit;
7125       rtx single_use;
7126
7127       g1 = giv_array[i];
7128       stats[i].giv_number = i;
7129
7130       /* If a DEST_REG GIV is used only once, do not allow it to combine
7131          with anything, for in doing so we will gain nothing that cannot
7132          be had by simply letting the GIV with which we would have combined
7133          to be reduced on its own.  The losage shows up in particular with 
7134          DEST_ADDR targets on hosts with reg+reg addressing, though it can
7135          be seen elsewhere as well.  */
7136       if (g1->giv_type == DEST_REG
7137           && (single_use = VARRAY_RTX (reg_single_usage, REGNO (g1->dest_reg)))
7138           && single_use != const0_rtx)
7139         continue;
7140
7141       this_benefit = g1->benefit;
7142       /* Add an additional weight for zero addends.  */
7143       if (g1->no_const_addval)
7144         this_benefit += 1;
7145
7146       for (j = 0; j < giv_count; j++)
7147         {
7148           rtx this_combine;
7149
7150           g2 = giv_array[j];
7151           if (g1 != g2
7152               && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7153             {
7154               can_combine[i*giv_count + j] = this_combine;
7155               this_benefit += g2->benefit + extra_benefit;
7156             }
7157         }
7158       stats[i].total_benefit = this_benefit;
7159     }
7160
7161   /* Iterate, combining until we can't.  */
7162 restart:
7163   qsort (stats, giv_count, sizeof(*stats), cmp_combine_givs_stats);
7164
7165   if (loop_dump_stream)
7166     {
7167       fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7168       for (k = 0; k < giv_count; k++)
7169         {
7170           g1 = giv_array[stats[k].giv_number];
7171           if (!g1->combined_with && !g1->same)
7172             fprintf (loop_dump_stream, " {%d, %d}", 
7173                      INSN_UID (giv_array[stats[k].giv_number]->insn),
7174                      stats[k].total_benefit);
7175         }
7176       putc ('\n', loop_dump_stream);
7177     }
7178
7179   for (k = 0; k < giv_count; k++)
7180     {
7181       int g1_add_benefit = 0;
7182
7183       i = stats[k].giv_number;
7184       g1 = giv_array[i];
7185
7186       /* If it has already been combined, skip.  */
7187       if (g1->combined_with || g1->same)
7188         continue;
7189
7190       for (j = 0; j < giv_count; j++)
7191         {
7192           g2 = giv_array[j];
7193           if (g1 != g2 && can_combine[i*giv_count + j]
7194               /* If it has already been combined, skip.  */
7195               && ! g2->same && ! g2->combined_with)
7196             {
7197               int l;
7198
7199               g2->new_reg = can_combine[i*giv_count + j];
7200               g2->same = g1;
7201               g1->combined_with++;
7202               g1->lifetime += g2->lifetime;
7203
7204               g1_add_benefit += g2->benefit;
7205
7206               /* ??? The new final_[bg]iv_value code does a much better job
7207                  of finding replaceable giv's, and hence this code may no
7208                  longer be necessary.  */
7209               if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7210                 g1_add_benefit -= copy_cost;
7211                 
7212               /* To help optimize the next set of combinations, remove
7213                  this giv from the benefits of other potential mates.  */
7214               for (l = 0; l < giv_count; ++l)
7215                 {
7216                   int m = stats[l].giv_number;
7217                   if (can_combine[m*giv_count + j])
7218                     stats[l].total_benefit -= g2->benefit + extra_benefit;
7219                 }
7220
7221               if (loop_dump_stream)
7222                 fprintf (loop_dump_stream,
7223                          "giv at %d combined with giv at %d\n",
7224                          INSN_UID (g2->insn), INSN_UID (g1->insn));
7225             }
7226         }
7227
7228       /* To help optimize the next set of combinations, remove
7229          this giv from the benefits of other potential mates.  */
7230       if (g1->combined_with)
7231         {
7232           for (j = 0; j < giv_count; ++j)
7233             {
7234               int m = stats[j].giv_number;
7235               if (can_combine[m*giv_count + i])
7236                 stats[j].total_benefit -= g1->benefit + extra_benefit;
7237             }
7238
7239           g1->benefit += g1_add_benefit;
7240
7241           /* We've finished with this giv, and everything it touched.
7242              Restart the combination so that proper weights for the 
7243              rest of the givs are properly taken into account.  */
7244           /* ??? Ideally we would compact the arrays at this point, so
7245              as to not cover old ground.  But sanely compacting
7246              can_combine is tricky.  */
7247           goto restart;
7248         }
7249     }
7250 }
7251 \f
7252 struct recombine_givs_stats
7253 {
7254   int giv_number;
7255   int start_luid, end_luid;
7256 };
7257
7258 /* Used below as comparison function for qsort.  We want a ascending luid
7259    when scanning the array starting at the end, thus the arguments are
7260    used in reverse.  */
7261 static int
7262 cmp_recombine_givs_stats (xp, yp)
7263      const PTR xp;
7264      const PTR yp;
7265 {
7266   const struct recombine_givs_stats * const x =
7267     (const struct recombine_givs_stats *) xp;
7268   const struct recombine_givs_stats * const y =
7269     (const struct recombine_givs_stats *) yp;
7270   int d;
7271   d = y->start_luid - x->start_luid;
7272   /* Stabilize the sort.  */
7273   if (!d)
7274     d = y->giv_number - x->giv_number;
7275   return d;
7276 }
7277
7278 /* Scan X, which is a part of INSN, for the end of life of a giv.  Also
7279    look for the start of life of a giv where the start has not been seen
7280    yet to unlock the search for the end of its life.
7281    Only consider givs that belong to BIV.
7282    Return the total number of lifetime ends that have been found.  */
7283 static int
7284 find_life_end (x, stats, insn, biv)
7285      rtx x, insn, biv;
7286      struct recombine_givs_stats *stats;
7287 {
7288   enum rtx_code code;
7289   const char *fmt;
7290   int i, j;
7291   int retval;
7292
7293   code = GET_CODE (x);
7294   switch (code)
7295     {
7296     case SET:
7297       {
7298         rtx reg = SET_DEST (x);
7299         if (GET_CODE (reg) == REG)
7300           {
7301             int regno = REGNO (reg);
7302             struct induction *v = REG_IV_INFO (regno);
7303
7304             if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7305                 && ! v->ignore
7306                 && v->src_reg == biv
7307                 && stats[v->ix].end_luid <= 0)
7308               {
7309                 /* If we see a 0 here for end_luid, it means that we have
7310                    scanned the entire loop without finding any use at all.
7311                    We must not predicate this code on a start_luid match
7312                    since that would make the test fail for givs that have
7313                    been hoisted out of inner loops.  */
7314                 if (stats[v->ix].end_luid == 0)
7315                   {
7316                     stats[v->ix].end_luid = stats[v->ix].start_luid;
7317                     return 1 + find_life_end (SET_SRC (x), stats, insn, biv);
7318                   }
7319                 else if (stats[v->ix].start_luid == INSN_LUID (insn))
7320                   stats[v->ix].end_luid = 0;
7321               }
7322             return find_life_end (SET_SRC (x), stats, insn, biv);
7323           }
7324         break;
7325       }
7326     case REG:
7327       {
7328         int regno = REGNO (x);
7329         struct induction *v = REG_IV_INFO (regno);
7330
7331         if (REG_IV_TYPE (regno) == GENERAL_INDUCT
7332             && ! v->ignore
7333             && v->src_reg == biv
7334             && stats[v->ix].end_luid == 0)
7335           {
7336             while (INSN_UID (insn) >= max_uid_for_loop)
7337               insn = NEXT_INSN (insn);
7338             stats[v->ix].end_luid = INSN_LUID (insn);
7339             return 1;
7340           }
7341         return 0;
7342       }
7343     case LABEL_REF:
7344     case CONST_DOUBLE:
7345     case CONST_INT:
7346     case CONST:
7347       return 0;
7348     default:
7349       break;
7350     }
7351   fmt = GET_RTX_FORMAT (code);
7352   retval = 0;
7353   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7354     {
7355       if (fmt[i] == 'e')
7356         retval += find_life_end (XEXP (x, i), stats, insn, biv);
7357
7358       else if (fmt[i] == 'E')
7359         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
7360           retval += find_life_end (XVECEXP (x, i, j), stats, insn, biv);
7361     }
7362   return retval;
7363 }
7364
7365 /* For each giv that has been combined with another, look if
7366    we can combine it with the most recently used one instead.
7367    This tends to shorten giv lifetimes, and helps the next step:
7368    try to derive givs from other givs.  */
7369 static void
7370 recombine_givs (bl, loop_start, loop_end, unroll_p)
7371      struct iv_class *bl;
7372      rtx loop_start, loop_end;
7373      int unroll_p;
7374 {
7375   struct induction *v, **giv_array, *last_giv;
7376   struct recombine_givs_stats *stats;
7377   int giv_count;
7378   int i, rescan;
7379   int ends_need_computing;
7380
7381   for (giv_count = 0, v = bl->giv; v; v = v->next_iv)
7382     {
7383       if (! v->ignore)
7384         giv_count++;
7385     }
7386   giv_array
7387     = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7388   stats = (struct recombine_givs_stats *) alloca (giv_count * sizeof *stats);
7389
7390   /* Initialize stats and set up the ix field for each giv in stats to name
7391      the corresponding index into stats.  */
7392   for (i = 0, v = bl->giv; v; v = v->next_iv)
7393     {
7394       rtx p;
7395
7396       if (v->ignore)
7397         continue;
7398       giv_array[i] = v;
7399       stats[i].giv_number = i;
7400       /* If this giv has been hoisted out of an inner loop, use the luid of
7401          the previous insn.  */
7402       for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7403         p = PREV_INSN (p);
7404       stats[i].start_luid = INSN_LUID (p);
7405       i++;
7406     }
7407
7408   qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7409
7410   /* Set up the ix field for each giv in stats to name
7411      the corresponding index into stats, and
7412      do the actual most-recently-used recombination.  */
7413   for (last_giv = 0, i = giv_count - 1; i >= 0; i--)
7414     {
7415       v = giv_array[stats[i].giv_number];
7416       v->ix = i;
7417       if (v->same)
7418         {
7419           struct induction *old_same = v->same;
7420           rtx new_combine;
7421
7422           /* combine_givs_p actually says if we can make this transformation.
7423              The other tests are here only to avoid keeping a giv alive
7424              that could otherwise be eliminated.  */
7425           if (last_giv
7426               && ((old_same->maybe_dead && ! old_same->combined_with)
7427                   || ! last_giv->maybe_dead
7428                   || last_giv->combined_with)
7429               && (new_combine = combine_givs_p (last_giv, v)))
7430             {
7431               old_same->combined_with--;
7432               v->new_reg = new_combine;
7433               v->same = last_giv;
7434               last_giv->combined_with++;
7435               /* No need to update lifetimes / benefits here since we have
7436                  already decided what to reduce.  */
7437
7438               if (loop_dump_stream)
7439                 {
7440                   fprintf (loop_dump_stream,
7441                            "giv at %d recombined with giv at %d as ",
7442                            INSN_UID (v->insn), INSN_UID (last_giv->insn));
7443                   print_rtl (loop_dump_stream, v->new_reg);
7444                   putc ('\n', loop_dump_stream);
7445                 }
7446               continue;
7447             }
7448           v = v->same;
7449         }
7450       else if (v->giv_type != DEST_REG)
7451         continue;
7452       if (! last_giv
7453           || (last_giv->maybe_dead && ! last_giv->combined_with)
7454           || ! v->maybe_dead
7455           || v->combined_with)
7456         last_giv = v;
7457     }
7458
7459   ends_need_computing = 0;
7460   /* For each DEST_REG giv, compute lifetime starts, and try to compute
7461      lifetime ends from regscan info.  */
7462   for (i = giv_count - 1; i >= 0; i--)
7463     {
7464       v = giv_array[stats[i].giv_number];
7465       if (v->ignore)
7466         continue;
7467       if (v->giv_type == DEST_ADDR)
7468         {
7469           /* Loop unrolling of an inner loop can even create new DEST_REG
7470              givs.  */
7471           rtx p;
7472           for (p = v->insn; INSN_UID (p) >= max_uid_for_loop; )
7473             p = PREV_INSN (p);
7474           stats[i].start_luid = stats[i].end_luid = INSN_LUID (p);
7475           if (p != v->insn)
7476             stats[i].end_luid++;
7477         }
7478       else /* v->giv_type == DEST_REG */
7479         {
7480           if (v->last_use)
7481             {
7482               stats[i].start_luid = INSN_LUID (v->insn);
7483               stats[i].end_luid = INSN_LUID (v->last_use);
7484             }
7485           else if (INSN_UID (v->insn) >= max_uid_for_loop)
7486             {
7487               rtx p;
7488               /* This insn has been created by loop optimization on an inner
7489                  loop.  We don't have a proper start_luid that will match
7490                  when we see the first set.  But we do know that there will
7491                  be no use before the set, so we can set end_luid to 0 so that
7492                  we'll start looking for the last use right away.  */
7493               for (p = PREV_INSN (v->insn); INSN_UID (p) >= max_uid_for_loop; )
7494                 p = PREV_INSN (p);
7495               stats[i].start_luid = INSN_LUID (p);
7496               stats[i].end_luid = 0;
7497               ends_need_computing++;
7498             }
7499           else
7500             {
7501               int regno = REGNO (v->dest_reg);
7502               int count = VARRAY_INT (n_times_set, regno) - 1;
7503               rtx p = v->insn;
7504
7505               /* Find the first insn that sets the giv, so that we can verify
7506                  if this giv's lifetime wraps around the loop.  We also need
7507                  the luid of the first setting insn in order to detect the
7508                  last use properly.  */
7509               while (count)
7510                 {
7511                   p = prev_nonnote_insn (p);
7512                   if (reg_set_p (v->dest_reg, p))
7513                   count--;
7514                 }
7515
7516               stats[i].start_luid = INSN_LUID (p);
7517               if (stats[i].start_luid > uid_luid[REGNO_FIRST_UID (regno)])
7518                 {
7519                   stats[i].end_luid = -1;
7520                   ends_need_computing++;
7521                 }
7522               else
7523                 {
7524                   stats[i].end_luid = uid_luid[REGNO_LAST_UID (regno)];
7525                   if (stats[i].end_luid > INSN_LUID (loop_end))
7526                     {
7527                       stats[i].end_luid = -1;
7528                       ends_need_computing++;
7529                     }
7530                 }
7531             }
7532         }
7533     }
7534
7535   /* If the regscan information was unconclusive for one or more DEST_REG
7536      givs, scan the all insn in the loop to find out lifetime ends.  */
7537   if (ends_need_computing)
7538     {
7539       rtx biv = bl->biv->src_reg;
7540       rtx p = loop_end;
7541
7542       do
7543         {
7544           if (p == loop_start)
7545             p = loop_end;
7546           p = PREV_INSN (p);
7547           if (GET_RTX_CLASS (GET_CODE (p)) != 'i')
7548             continue;
7549           ends_need_computing -= find_life_end (PATTERN (p), stats, p, biv);
7550         }
7551       while (ends_need_computing);
7552     }
7553
7554   /* Set start_luid back to the last insn that sets the giv.  This allows
7555      more combinations.  */
7556   for (i = giv_count - 1; i >= 0; i--)
7557     {
7558       v = giv_array[stats[i].giv_number];
7559       if (v->ignore)
7560         continue;
7561       if (INSN_UID (v->insn) < max_uid_for_loop)
7562         stats[i].start_luid = INSN_LUID (v->insn);
7563     }
7564
7565   /* Now adjust lifetime ends by taking combined givs into account.  */
7566   for (i = giv_count - 1; i >= 0; i--)
7567     {
7568       unsigned luid;
7569       int j;
7570
7571       v = giv_array[stats[i].giv_number];
7572       if (v->ignore)
7573         continue;
7574       if (v->same && ! v->same->ignore)
7575         {
7576           j = v->same->ix;
7577           luid = stats[i].start_luid;
7578           /* Use unsigned arithmetic to model loop wrap-around.  */
7579           if (luid - stats[j].start_luid
7580               > (unsigned) stats[j].end_luid - stats[j].start_luid)
7581             stats[j].end_luid = luid;
7582         }
7583     }
7584
7585   qsort (stats, giv_count, sizeof(*stats), cmp_recombine_givs_stats);
7586
7587   /* Try to derive DEST_REG givs from previous DEST_REG givs with the
7588      same mult_val and non-overlapping lifetime.  This reduces register
7589      pressure.
7590      Once we find a DEST_REG giv that is suitable to derive others from,
7591      we set last_giv to this giv, and try to derive as many other DEST_REG
7592      givs from it without joining overlapping lifetimes.  If we then
7593      encounter a DEST_REG giv that we can't derive, we set rescan to the
7594      index for this giv (unless rescan is already set).
7595      When we are finished with the current LAST_GIV (i.e. the inner loop
7596      terminates), we start again with rescan, which then becomes the new
7597      LAST_GIV.  */
7598   for (i = giv_count - 1; i >= 0; i = rescan)
7599     {
7600       int life_start, life_end;
7601
7602       for (last_giv = 0, rescan = -1; i >= 0; i--)
7603         {
7604           rtx sum;
7605
7606           v = giv_array[stats[i].giv_number];
7607           if (v->giv_type != DEST_REG || v->derived_from || v->same)
7608             continue;
7609           if (! last_giv)
7610             {
7611               /* Don't use a giv that's likely to be dead to derive
7612                  others - that would be likely to keep that giv alive.  */
7613               if (! v->maybe_dead || v->combined_with)
7614                 {
7615                   last_giv = v;
7616                   life_start = stats[i].start_luid;
7617                   life_end = stats[i].end_luid;
7618                 }
7619               continue;
7620             }
7621           /* Use unsigned arithmetic to model loop wrap around.  */
7622           if (((unsigned) stats[i].start_luid - life_start
7623                >= (unsigned) life_end - life_start)
7624               && ((unsigned) stats[i].end_luid - life_start
7625                   > (unsigned) life_end - life_start)
7626               /*  Check that the giv insn we're about to use for deriving
7627                   precedes all uses of that giv.  Note that initializing the
7628                   derived giv would defeat the purpose of reducing register
7629                   pressure.
7630                   ??? We could arrange to move the insn.  */
7631               && ((unsigned) stats[i].end_luid - INSN_LUID (loop_start)
7632                   > (unsigned) stats[i].start_luid - INSN_LUID (loop_start))
7633               && rtx_equal_p (last_giv->mult_val, v->mult_val)
7634               /* ??? Could handle libcalls, but would need more logic.  */
7635               && ! find_reg_note (v->insn, REG_RETVAL, NULL_RTX)
7636               /* We would really like to know if for any giv that v
7637                  is combined with, v->insn or any intervening biv increment
7638                  dominates that combined giv.  However, we
7639                  don't have this detailed control flow information.
7640                  N.B. since last_giv will be reduced, it is valid
7641                  anywhere in the loop, so we don't need to check the
7642                  validity of last_giv.
7643                  We rely here on the fact that v->always_executed implies that
7644                  there is no jump to someplace else in the loop before the
7645                  giv insn, and hence any insn that is executed before the
7646                  giv insn in the loop will have a lower luid.  */
7647               && (v->always_executed || ! v->combined_with)
7648               && (sum = express_from (last_giv, v))
7649               /* Make sure we don't make the add more expensive.  ADD_COST
7650                  doesn't take different costs of registers and constants into
7651                  account, so compare the cost of the actual SET_SRCs.  */
7652               && (rtx_cost (sum, SET)
7653                   <= rtx_cost (SET_SRC (single_set (v->insn)), SET))
7654               /* ??? unroll can't understand anything but reg + const_int
7655                  sums.  It would be cleaner to fix unroll.  */
7656               && ((GET_CODE (sum) == PLUS
7657                    && GET_CODE (XEXP (sum, 0)) == REG
7658                    && GET_CODE (XEXP (sum, 1)) == CONST_INT)
7659                   || ! unroll_p)
7660               && validate_change (v->insn, &PATTERN (v->insn),
7661                                   gen_rtx_SET (VOIDmode, v->dest_reg, sum), 0))
7662             {
7663               v->derived_from = last_giv;
7664               life_end = stats[i].end_luid;
7665
7666               if (loop_dump_stream)
7667                 {
7668                   fprintf (loop_dump_stream,
7669                            "giv at %d derived from %d as ",
7670                            INSN_UID (v->insn), INSN_UID (last_giv->insn));
7671                   print_rtl (loop_dump_stream, sum);
7672                   putc ('\n', loop_dump_stream);
7673                 }
7674             }
7675           else if (rescan < 0)
7676             rescan = i;
7677         }
7678     }
7679 }
7680 \f
7681 /* EMIT code before INSERT_BEFORE to set REG = B * M + A.  */
7682
7683 void
7684 emit_iv_add_mult (b, m, a, reg, insert_before)
7685      rtx b;          /* initial value of basic induction variable */
7686      rtx m;          /* multiplicative constant */
7687      rtx a;          /* additive constant */
7688      rtx reg;        /* destination register */
7689      rtx insert_before;
7690 {
7691   rtx seq;
7692   rtx result;
7693
7694   /* Prevent unexpected sharing of these rtx.  */
7695   a = copy_rtx (a);
7696   b = copy_rtx (b);
7697
7698   /* Increase the lifetime of any invariants moved further in code.  */
7699   update_reg_last_use (a, insert_before);
7700   update_reg_last_use (b, insert_before);
7701   update_reg_last_use (m, insert_before);
7702
7703   start_sequence ();
7704   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
7705   if (reg != result)
7706     emit_move_insn (reg, result);
7707   seq = gen_sequence ();
7708   end_sequence ();
7709
7710   emit_insn_before (seq, insert_before);
7711
7712   /* It is entirely possible that the expansion created lots of new 
7713      registers.  Iterate over the sequence we just created and 
7714      record them all.  */
7715
7716   if (GET_CODE (seq) == SEQUENCE)
7717     {
7718       int i;
7719       for (i = 0; i < XVECLEN (seq, 0); ++i)
7720         {
7721           rtx set = single_set (XVECEXP (seq, 0, i));
7722           if (set && GET_CODE (SET_DEST (set)) == REG)
7723             record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7724         }
7725     }
7726   else if (GET_CODE (seq) == SET
7727            && GET_CODE (SET_DEST (seq)) == REG)
7728     record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
7729 }
7730 \f
7731 /* Test whether A * B can be computed without
7732    an actual multiply insn.  Value is 1 if so.  */
7733
7734 static int
7735 product_cheap_p (a, b)
7736      rtx a;
7737      rtx b;
7738 {
7739   int i;
7740   rtx tmp;
7741   struct obstack *old_rtl_obstack = rtl_obstack;
7742   char *storage = (char *) obstack_alloc (&temp_obstack, 0);
7743   int win = 1;
7744
7745   /* If only one is constant, make it B.  */
7746   if (GET_CODE (a) == CONST_INT)
7747     tmp = a, a = b, b = tmp;
7748
7749   /* If first constant, both constant, so don't need multiply.  */
7750   if (GET_CODE (a) == CONST_INT)
7751     return 1;
7752
7753   /* If second not constant, neither is constant, so would need multiply.  */
7754   if (GET_CODE (b) != CONST_INT)
7755     return 0;
7756
7757   /* One operand is constant, so might not need multiply insn.  Generate the
7758      code for the multiply and see if a call or multiply, or long sequence
7759      of insns is generated.  */
7760
7761   rtl_obstack = &temp_obstack;
7762   start_sequence ();
7763   expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
7764   tmp = gen_sequence ();
7765   end_sequence ();
7766
7767   if (GET_CODE (tmp) == SEQUENCE)
7768     {
7769       if (XVEC (tmp, 0) == 0)
7770         win = 1;
7771       else if (XVECLEN (tmp, 0) > 3)
7772         win = 0;
7773       else
7774         for (i = 0; i < XVECLEN (tmp, 0); i++)
7775           {
7776             rtx insn = XVECEXP (tmp, 0, i);
7777
7778             if (GET_CODE (insn) != INSN
7779                 || (GET_CODE (PATTERN (insn)) == SET
7780                     && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
7781                 || (GET_CODE (PATTERN (insn)) == PARALLEL
7782                     && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
7783                     && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
7784               {
7785                 win = 0;
7786                 break;
7787               }
7788           }
7789     }
7790   else if (GET_CODE (tmp) == SET
7791            && GET_CODE (SET_SRC (tmp)) == MULT)
7792     win = 0;
7793   else if (GET_CODE (tmp) == PARALLEL
7794            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
7795            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
7796     win = 0;
7797
7798   /* Free any storage we obtained in generating this multiply and restore rtl
7799      allocation to its normal obstack.  */
7800   obstack_free (&temp_obstack, storage);
7801   rtl_obstack = old_rtl_obstack;
7802
7803   return win;
7804 }
7805 \f
7806 /* Check to see if loop can be terminated by a "decrement and branch until
7807    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
7808    Also try reversing an increment loop to a decrement loop
7809    to see if the optimization can be performed.
7810    Value is nonzero if optimization was performed.  */
7811
7812 /* This is useful even if the architecture doesn't have such an insn,
7813    because it might change a loops which increments from 0 to n to a loop
7814    which decrements from n to 0.  A loop that decrements to zero is usually
7815    faster than one that increments from zero.  */
7816
7817 /* ??? This could be rewritten to use some of the loop unrolling procedures,
7818    such as approx_final_value, biv_total_increment, loop_iterations, and
7819    final_[bg]iv_value.  */
7820
7821 static int
7822 check_dbra_loop (loop_end, insn_count, loop_start, loop_info)
7823      rtx loop_end;
7824      int insn_count;
7825      rtx loop_start;
7826      struct loop_info *loop_info;
7827 {
7828   struct iv_class *bl;
7829   rtx reg;
7830   rtx jump_label;
7831   rtx final_value;
7832   rtx start_value;
7833   rtx new_add_val;
7834   rtx comparison;
7835   rtx before_comparison;
7836   rtx p;
7837   rtx jump;
7838   rtx first_compare;
7839   int compare_and_branch;
7840
7841   /* If last insn is a conditional branch, and the insn before tests a
7842      register value, try to optimize it.  Otherwise, we can't do anything.  */
7843
7844   jump = PREV_INSN (loop_end);
7845   comparison = get_condition_for_loop (jump);
7846   if (comparison == 0)
7847     return 0;
7848
7849   /* Try to compute whether the compare/branch at the loop end is one or
7850      two instructions.  */
7851   get_condition (jump, &first_compare);
7852   if (first_compare == jump)
7853     compare_and_branch = 1;
7854   else if (first_compare == prev_nonnote_insn (jump))
7855     compare_and_branch = 2;
7856   else
7857     return 0;
7858
7859   /* Check all of the bivs to see if the compare uses one of them.
7860      Skip biv's set more than once because we can't guarantee that
7861      it will be zero on the last iteration.  Also skip if the biv is
7862      used between its update and the test insn.  */
7863
7864   for (bl = loop_iv_list; bl; bl = bl->next)
7865     {
7866       if (bl->biv_count == 1
7867           && bl->biv->dest_reg == XEXP (comparison, 0)
7868           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
7869                                    first_compare))
7870         break;
7871     }
7872
7873   if (! bl)
7874     return 0;
7875
7876   /* Look for the case where the basic induction variable is always
7877      nonnegative, and equals zero on the last iteration.
7878      In this case, add a reg_note REG_NONNEG, which allows the
7879      m68k DBRA instruction to be used.  */
7880
7881   if (((GET_CODE (comparison) == GT
7882         && GET_CODE (XEXP (comparison, 1)) == CONST_INT
7883         && INTVAL (XEXP (comparison, 1)) == -1)
7884        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
7885       && GET_CODE (bl->biv->add_val) == CONST_INT
7886       && INTVAL (bl->biv->add_val) < 0)
7887     {
7888       /* Initial value must be greater than 0,
7889          init_val % -dec_value == 0 to ensure that it equals zero on
7890          the last iteration */
7891
7892       if (GET_CODE (bl->initial_value) == CONST_INT
7893           && INTVAL (bl->initial_value) > 0
7894           && (INTVAL (bl->initial_value)
7895               % (-INTVAL (bl->biv->add_val))) == 0)
7896         {
7897           /* register always nonnegative, add REG_NOTE to branch */
7898           REG_NOTES (PREV_INSN (loop_end))
7899             = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7900                                  REG_NOTES (PREV_INSN (loop_end)));
7901           bl->nonneg = 1;
7902
7903           return 1;
7904         }
7905
7906       /* If the decrement is 1 and the value was tested as >= 0 before
7907          the loop, then we can safely optimize.  */
7908       for (p = loop_start; p; p = PREV_INSN (p))
7909         {
7910           if (GET_CODE (p) == CODE_LABEL)
7911             break;
7912           if (GET_CODE (p) != JUMP_INSN)
7913             continue;
7914
7915           before_comparison = get_condition_for_loop (p);
7916           if (before_comparison
7917               && XEXP (before_comparison, 0) == bl->biv->dest_reg
7918               && GET_CODE (before_comparison) == LT
7919               && XEXP (before_comparison, 1) == const0_rtx
7920               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
7921               && INTVAL (bl->biv->add_val) == -1)
7922             {
7923               REG_NOTES (PREV_INSN (loop_end))
7924                 = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
7925                                      REG_NOTES (PREV_INSN (loop_end)));
7926               bl->nonneg = 1;
7927
7928               return 1;
7929             }
7930         }
7931     }
7932   else if (GET_CODE (bl->biv->add_val) == CONST_INT
7933            && INTVAL (bl->biv->add_val) > 0)
7934     {
7935       /* Try to change inc to dec, so can apply above optimization.  */
7936       /* Can do this if:
7937          all registers modified are induction variables or invariant,
7938          all memory references have non-overlapping addresses
7939          (obviously true if only one write)
7940          allow 2 insns for the compare/jump at the end of the loop.  */
7941       /* Also, we must avoid any instructions which use both the reversed
7942          biv and another biv.  Such instructions will fail if the loop is
7943          reversed.  We meet this condition by requiring that either
7944          no_use_except_counting is true, or else that there is only
7945          one biv.  */
7946       int num_nonfixed_reads = 0;
7947       /* 1 if the iteration var is used only to count iterations.  */
7948       int no_use_except_counting = 0;
7949       /* 1 if the loop has no memory store, or it has a single memory store
7950          which is reversible.  */
7951       int reversible_mem_store = 1;
7952
7953       if (bl->giv_count == 0
7954           && ! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
7955         {
7956           rtx bivreg = regno_reg_rtx[bl->regno];
7957
7958           /* If there are no givs for this biv, and the only exit is the
7959              fall through at the end of the loop, then
7960              see if perhaps there are no uses except to count.  */
7961           no_use_except_counting = 1;
7962           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
7963             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
7964               {
7965                 rtx set = single_set (p);
7966
7967                 if (set && GET_CODE (SET_DEST (set)) == REG
7968                     && REGNO (SET_DEST (set)) == bl->regno)
7969                   /* An insn that sets the biv is okay.  */
7970                   ;
7971                 else if ((p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
7972                           || p == prev_nonnote_insn (loop_end))
7973                          && reg_mentioned_p (bivreg, PATTERN (p)))
7974                   {
7975                     /* If either of these insns uses the biv and sets a pseudo
7976                        that has more than one usage, then the biv has uses
7977                        other than counting since it's used to derive a value
7978                        that is used more than one time.  */
7979                     note_set_pseudo_multiple_uses_retval = 0;
7980                     note_stores (PATTERN (p), note_set_pseudo_multiple_uses);
7981                     if (note_set_pseudo_multiple_uses_retval)
7982                       {
7983                         no_use_except_counting = 0;
7984                         break;
7985                       }
7986                   }
7987                 else if (reg_mentioned_p (bivreg, PATTERN (p)))
7988                   {
7989                     no_use_except_counting = 0;
7990                     break;
7991                   }
7992               }
7993         }
7994
7995       if (no_use_except_counting)
7996         ; /* no need to worry about MEMs.  */
7997       else if (num_mem_sets <= 1)
7998         {
7999           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8000             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8001               num_nonfixed_reads += count_nonfixed_reads (PATTERN (p));
8002
8003           /* If the loop has a single store, and the destination address is
8004              invariant, then we can't reverse the loop, because this address
8005              might then have the wrong value at loop exit.
8006              This would work if the source was invariant also, however, in that
8007              case, the insn should have been moved out of the loop.  */
8008
8009           if (num_mem_sets == 1)
8010             {
8011               struct induction *v;
8012
8013               reversible_mem_store
8014                 = (! unknown_address_altered
8015                    && ! invariant_p (XEXP (XEXP (loop_store_mems, 0), 0)));
8016
8017               /* If the store depends on a register that is set after the
8018                  store, it depends on the initial value, and is thus not
8019                  reversible.  */
8020               for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
8021                 {
8022                   if (v->giv_type == DEST_REG
8023                       && reg_mentioned_p (v->dest_reg,
8024                                           XEXP (loop_store_mems, 0))
8025                       && loop_insn_first_p (first_loop_store_insn, v->insn))
8026                     reversible_mem_store = 0;
8027                 }
8028             }
8029         }
8030       else
8031         return 0;
8032
8033       /* This code only acts for innermost loops.  Also it simplifies
8034          the memory address check by only reversing loops with
8035          zero or one memory access.
8036          Two memory accesses could involve parts of the same array,
8037          and that can't be reversed.
8038          If the biv is used only for counting, than we don't need to worry
8039          about all these things.  */
8040
8041       if ((num_nonfixed_reads <= 1
8042            && ! loop_info->has_call
8043            && ! loop_info->has_volatile
8044            && reversible_mem_store
8045            && (bl->giv_count + bl->biv_count + num_mem_sets
8046               + num_movables + compare_and_branch == insn_count)
8047            && (bl == loop_iv_list && bl->next == 0))
8048           || no_use_except_counting)
8049         {
8050           rtx tem;
8051
8052           /* Loop can be reversed.  */
8053           if (loop_dump_stream)
8054             fprintf (loop_dump_stream, "Can reverse loop\n");
8055
8056           /* Now check other conditions:
8057
8058              The increment must be a constant, as must the initial value,
8059              and the comparison code must be LT. 
8060
8061              This test can probably be improved since +/- 1 in the constant
8062              can be obtained by changing LT to LE and vice versa; this is
8063              confusing.  */
8064
8065           if (comparison
8066               /* for constants, LE gets turned into LT */
8067               && (GET_CODE (comparison) == LT
8068                   || (GET_CODE (comparison) == LE
8069                       && no_use_except_counting)))
8070             {
8071               HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8072               rtx initial_value, comparison_value;
8073               int nonneg = 0;
8074               enum rtx_code cmp_code;
8075               int comparison_const_width;
8076               unsigned HOST_WIDE_INT comparison_sign_mask;
8077
8078               add_val = INTVAL (bl->biv->add_val);
8079               comparison_value = XEXP (comparison, 1);
8080               if (GET_MODE (comparison_value) == VOIDmode)
8081                 comparison_const_width
8082                   = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8083               else
8084                 comparison_const_width
8085                   = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8086               if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8087                 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8088               comparison_sign_mask
8089                 = (unsigned HOST_WIDE_INT)1 << (comparison_const_width - 1);
8090
8091               /* If the comparison value is not a loop invariant, then we
8092                  can not reverse this loop.
8093
8094                  ??? If the insns which initialize the comparison value as
8095                  a whole compute an invariant result, then we could move
8096                  them out of the loop and proceed with loop reversal.  */
8097               if (!invariant_p (comparison_value))
8098                 return 0;
8099
8100               if (GET_CODE (comparison_value) == CONST_INT)
8101                 comparison_val = INTVAL (comparison_value);
8102               initial_value = bl->initial_value;
8103                 
8104               /* Normalize the initial value if it is an integer and 
8105                  has no other use except as a counter.  This will allow
8106                  a few more loops to be reversed.  */
8107               if (no_use_except_counting
8108                   && GET_CODE (comparison_value) == CONST_INT
8109                   && GET_CODE (initial_value) == CONST_INT)
8110                 {
8111                   comparison_val = comparison_val - INTVAL (bl->initial_value);
8112                   /* The code below requires comparison_val to be a multiple
8113                      of add_val in order to do the loop reversal, so
8114                      round up comparison_val to a multiple of add_val.
8115                      Since comparison_value is constant, we know that the
8116                      current comparison code is LT.  */
8117                   comparison_val = comparison_val + add_val - 1;
8118                   comparison_val
8119                     -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8120                   /* We postpone overflow checks for COMPARISON_VAL here;
8121                      even if there is an overflow, we might still be able to
8122                      reverse the loop, if converting the loop exit test to
8123                      NE is possible.  */
8124                   initial_value = const0_rtx;
8125                 }
8126
8127               /* First check if we can do a vanilla loop reversal.  */
8128               if (initial_value == const0_rtx
8129                   /* If we have a decrement_and_branch_on_count,
8130                      prefer the NE test, since this will allow that
8131                      instruction to be generated.  Note that we must
8132                      use a vanilla loop reversal if the biv is used to
8133                      calculate a giv or has a non-counting use.  */
8134 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8135 && defined (HAVE_decrement_and_branch_on_count)
8136                   && (! (add_val == 1 && loop_info->vtop
8137                          && (bl->biv_count == 0
8138                              || no_use_except_counting)))
8139 #endif
8140                   && GET_CODE (comparison_value) == CONST_INT
8141                      /* Now do postponed overflow checks on COMPARISON_VAL.  */
8142                   && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8143                         & comparison_sign_mask))
8144                 {
8145                   /* Register will always be nonnegative, with value
8146                      0 on last iteration */
8147                   add_adjust = add_val;
8148                   nonneg = 1;
8149                   cmp_code = GE;
8150                 }
8151               else if (add_val == 1 && loop_info->vtop
8152                        && (bl->biv_count == 0
8153                            || no_use_except_counting))
8154                 {
8155                   add_adjust = 0;
8156                   cmp_code = NE;
8157                 }
8158               else
8159                 return 0;
8160
8161               if (GET_CODE (comparison) == LE)
8162                 add_adjust -= add_val;
8163
8164               /* If the initial value is not zero, or if the comparison
8165                  value is not an exact multiple of the increment, then we
8166                  can not reverse this loop.  */
8167               if (initial_value == const0_rtx
8168                   && GET_CODE (comparison_value) == CONST_INT)
8169                 {
8170                   if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8171                     return 0;
8172                 }
8173               else
8174                 {
8175                   if (! no_use_except_counting || add_val != 1)
8176                     return 0;
8177                 }
8178
8179               final_value = comparison_value;
8180
8181               /* Reset these in case we normalized the initial value
8182                  and comparison value above.  */
8183               if (GET_CODE (comparison_value) == CONST_INT
8184                   && GET_CODE (initial_value) == CONST_INT)
8185                 {
8186                   comparison_value = GEN_INT (comparison_val);
8187                   final_value
8188                     = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8189                 }
8190               bl->initial_value = initial_value;
8191
8192               /* Save some info needed to produce the new insns.  */
8193               reg = bl->biv->dest_reg;
8194               jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
8195               if (jump_label == pc_rtx)
8196                 jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 2);
8197               new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
8198
8199               /* Set start_value; if this is not a CONST_INT, we need
8200                  to generate a SUB.
8201                  Initialize biv to start_value before loop start.
8202                  The old initializing insn will be deleted as a
8203                  dead store by flow.c.  */
8204               if (initial_value == const0_rtx
8205                   && GET_CODE (comparison_value) == CONST_INT)
8206                 {
8207                   start_value = GEN_INT (comparison_val - add_adjust);
8208                   emit_insn_before (gen_move_insn (reg, start_value),
8209                                     loop_start);
8210                 }
8211               else if (GET_CODE (initial_value) == CONST_INT)
8212                 {
8213                   rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8214                   enum machine_mode mode = GET_MODE (reg);
8215                   enum insn_code icode
8216                     = add_optab->handlers[(int) mode].insn_code;
8217
8218                   if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8219                       || ! ((*insn_data[icode].operand[1].predicate)
8220                             (comparison_value, mode))
8221                       || ! ((*insn_data[icode].operand[2].predicate)
8222                             (offset, mode)))
8223                     return 0;
8224                   start_value
8225                     = gen_rtx_PLUS (mode, comparison_value, offset);
8226                   emit_insn_before ((GEN_FCN (icode)
8227                                      (reg, comparison_value, offset)),
8228                                     loop_start);
8229                   if (GET_CODE (comparison) == LE)
8230                     final_value = gen_rtx_PLUS (mode, comparison_value,
8231                                                 GEN_INT (add_val));
8232                 }
8233               else if (! add_adjust)
8234                 {
8235                   enum machine_mode mode = GET_MODE (reg);
8236                   enum insn_code icode
8237                     = sub_optab->handlers[(int) mode].insn_code;
8238                   if (! (*insn_data[icode].operand[0].predicate) (reg, mode)
8239                       || ! ((*insn_data[icode].operand[1].predicate)
8240                             (comparison_value, mode))
8241                       || ! ((*insn_data[icode].operand[2].predicate)
8242                             (initial_value, mode)))
8243                     return 0;
8244                   start_value
8245                     = gen_rtx_MINUS (mode, comparison_value, initial_value);
8246                   emit_insn_before ((GEN_FCN (icode)
8247                                      (reg, comparison_value, initial_value)),
8248                                     loop_start);
8249                 }
8250               else
8251                 /* We could handle the other cases too, but it'll be
8252                    better to have a testcase first.  */
8253                 return 0;
8254
8255               /* We may not have a single insn which can increment a reg, so
8256                  create a sequence to hold all the insns from expand_inc.  */
8257               start_sequence ();
8258               expand_inc (reg, new_add_val);
8259               tem = gen_sequence ();
8260               end_sequence ();
8261
8262               p = emit_insn_before (tem, bl->biv->insn);
8263               delete_insn (bl->biv->insn);
8264                       
8265               /* Update biv info to reflect its new status.  */
8266               bl->biv->insn = p;
8267               bl->initial_value = start_value;
8268               bl->biv->add_val = new_add_val;
8269
8270               /* Update loop info.  */
8271               loop_info->initial_value = reg;
8272               loop_info->initial_equiv_value = reg;
8273               loop_info->final_value = const0_rtx;
8274               loop_info->final_equiv_value = const0_rtx;
8275               loop_info->comparison_value = const0_rtx;
8276               loop_info->comparison_code = cmp_code;
8277               loop_info->increment = new_add_val;
8278
8279               /* Inc LABEL_NUSES so that delete_insn will
8280                  not delete the label.  */
8281               LABEL_NUSES (XEXP (jump_label, 0)) ++;
8282
8283               /* Emit an insn after the end of the loop to set the biv's
8284                  proper exit value if it is used anywhere outside the loop.  */
8285               if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8286                   || ! bl->init_insn
8287                   || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8288                 emit_insn_after (gen_move_insn (reg, final_value),
8289                                  loop_end);
8290
8291               /* Delete compare/branch at end of loop.  */
8292               delete_insn (PREV_INSN (loop_end));
8293               if (compare_and_branch == 2)
8294                 delete_insn (first_compare);
8295
8296               /* Add new compare/branch insn at end of loop.  */
8297               start_sequence ();
8298               emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8299                                        GET_MODE (reg), 0, 0, 
8300                                        XEXP (jump_label, 0));
8301               tem = gen_sequence ();
8302               end_sequence ();
8303               emit_jump_insn_before (tem, loop_end);
8304
8305               for (tem = PREV_INSN (loop_end);
8306                    tem && GET_CODE (tem) != JUMP_INSN;
8307                    tem = PREV_INSN (tem))
8308                 ;
8309
8310               if (tem)
8311                 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8312
8313               if (nonneg)
8314                 {
8315                   if (tem)
8316                     {
8317                       /* Increment of LABEL_NUSES done above.  */
8318                       /* Register is now always nonnegative,
8319                          so add REG_NONNEG note to the branch.  */
8320                       REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, NULL_RTX,
8321                                                            REG_NOTES (tem));
8322                     }
8323                   bl->nonneg = 1;
8324                 }
8325
8326               /* No insn may reference both the reversed and another biv or it
8327                  will fail (see comment near the top of the loop reversal
8328                  code).
8329                  Earlier on, we have verified that the biv has no use except
8330                  counting, or it is the only biv in this function.
8331                  However, the code that computes no_use_except_counting does
8332                  not verify reg notes.  It's possible to have an insn that
8333                  references another biv, and has a REG_EQUAL note with an
8334                  expression based on the reversed biv.  To avoid this case,
8335                  remove all REG_EQUAL notes based on the reversed biv
8336                  here.  */
8337               for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8338                 if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
8339                   {
8340                     rtx *pnote;
8341                     rtx set = single_set (p);
8342                     /* If this is a set of a GIV based on the reversed biv, any
8343                        REG_EQUAL notes should still be correct.  */
8344                     if (! set
8345                         || GET_CODE (SET_DEST (set)) != REG
8346                         || (size_t) REGNO (SET_DEST (set)) >= reg_iv_type->num_elements
8347                         || REG_IV_TYPE (REGNO (SET_DEST (set))) != GENERAL_INDUCT
8348                         || REG_IV_INFO (REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8349                       for (pnote = &REG_NOTES (p); *pnote;)
8350                         {
8351                           if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8352                               && reg_mentioned_p (regno_reg_rtx[bl->regno],
8353                                                   XEXP (*pnote, 0)))
8354                             *pnote = XEXP (*pnote, 1);
8355                           else
8356                             pnote = &XEXP (*pnote, 1);
8357                         }
8358                   }
8359
8360               /* Mark that this biv has been reversed.  Each giv which depends
8361                  on this biv, and which is also live past the end of the loop
8362                  will have to be fixed up.  */
8363
8364               bl->reversed = 1;
8365
8366               if (loop_dump_stream)
8367                 {
8368                   fprintf (loop_dump_stream, "Reversed loop");
8369                   if (bl->nonneg)
8370                     fprintf (loop_dump_stream, " and added reg_nonneg\n");
8371                   else
8372                     fprintf (loop_dump_stream, "\n");
8373                 }
8374
8375               return 1;
8376             }
8377         }
8378     }
8379
8380   return 0;
8381 }
8382 \f
8383 /* Verify whether the biv BL appears to be eliminable,
8384    based on the insns in the loop that refer to it.
8385    LOOP_START is the first insn of the loop, and END is the end insn.
8386
8387    If ELIMINATE_P is non-zero, actually do the elimination.
8388
8389    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8390    determine whether invariant insns should be placed inside or at the
8391    start of the loop.  */
8392
8393 static int
8394 maybe_eliminate_biv (bl, loop_start, end, eliminate_p, threshold, insn_count)
8395      struct iv_class *bl;
8396      rtx loop_start;
8397      rtx end;
8398      int eliminate_p;
8399      int threshold, insn_count;
8400 {
8401   rtx reg = bl->biv->dest_reg;
8402   rtx p;
8403
8404   /* Scan all insns in the loop, stopping if we find one that uses the
8405      biv in a way that we cannot eliminate.  */
8406
8407   for (p = loop_start; p != end; p = NEXT_INSN (p))
8408     {
8409       enum rtx_code code = GET_CODE (p);
8410       rtx where = threshold >= insn_count ? loop_start : p;
8411
8412       /* If this is a libcall that sets a giv, skip ahead to its end.  */
8413       if (GET_RTX_CLASS (code) == 'i')
8414         {
8415           rtx note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8416
8417           if (note)
8418             {
8419               rtx last = XEXP (note, 0);
8420               rtx set = single_set (last);
8421
8422               if (set && GET_CODE (SET_DEST (set)) == REG)
8423                 {
8424                   int regno = REGNO (SET_DEST (set));
8425
8426                   if (regno < max_reg_before_loop
8427                       && REG_IV_TYPE (regno) == GENERAL_INDUCT
8428                       && REG_IV_INFO (regno)->src_reg == bl->biv->src_reg)
8429                     p = last;
8430                 }
8431             }
8432         }
8433       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8434           && reg_mentioned_p (reg, PATTERN (p))
8435           && ! maybe_eliminate_biv_1 (PATTERN (p), p, bl, eliminate_p, where))
8436         {
8437           if (loop_dump_stream)
8438             fprintf (loop_dump_stream,
8439                      "Cannot eliminate biv %d: biv used in insn %d.\n",
8440                      bl->regno, INSN_UID (p));
8441           break;
8442         }
8443     }
8444
8445   if (p == end)
8446     {
8447       if (loop_dump_stream)
8448         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8449                  bl->regno, eliminate_p ? "was" : "can be");
8450       return 1;
8451     }
8452
8453   return 0;
8454 }
8455 \f
8456 /* INSN and REFERENCE are instructions in the same insn chain.
8457    Return non-zero if INSN is first.  */
8458
8459 int
8460 loop_insn_first_p (insn, reference)
8461      rtx insn, reference;
8462 {
8463   rtx p, q;
8464
8465   for (p = insn, q = reference; ;)
8466     {
8467       /* Start with test for not first so that INSN == REFERENCE yields not
8468          first.  */
8469       if (q == insn || ! p)
8470         return 0;
8471       if (p == reference || ! q)
8472         return 1;
8473
8474       /* Either of P or Q might be a NOTE.  Notes have the same LUID as the
8475          previous insn, hence the <= comparison below does not work if
8476          P is a note.  */
8477       if (INSN_UID (p) < max_uid_for_loop
8478           && INSN_UID (q) < max_uid_for_loop
8479           && GET_CODE (p) != NOTE)
8480         return INSN_LUID (p) <= INSN_LUID (q);
8481
8482       if (INSN_UID (p) >= max_uid_for_loop
8483           || GET_CODE (p) == NOTE)
8484         p = NEXT_INSN (p);
8485       if (INSN_UID (q) >= max_uid_for_loop)
8486         q = NEXT_INSN (q);
8487     }
8488 }
8489
8490 /* We are trying to eliminate BIV in INSN using GIV.  Return non-zero if
8491    the offset that we have to take into account due to auto-increment /
8492    div derivation is zero.  */
8493 static int
8494 biv_elimination_giv_has_0_offset (biv, giv, insn)
8495      struct induction *biv, *giv;
8496      rtx insn;
8497 {
8498   /* If the giv V had the auto-inc address optimization applied
8499      to it, and INSN occurs between the giv insn and the biv
8500      insn, then we'd have to adjust the value used here.
8501      This is rare, so we don't bother to make this possible.  */
8502   if (giv->auto_inc_opt
8503       && ((loop_insn_first_p (giv->insn, insn)
8504            && loop_insn_first_p (insn, biv->insn))
8505           || (loop_insn_first_p (biv->insn, insn)
8506               && loop_insn_first_p (insn, giv->insn))))
8507     return 0;
8508
8509   /* If the giv V was derived from another giv, and INSN does
8510      not occur between the giv insn and the biv insn, then we'd
8511      have to adjust the value used here.  This is rare, so we don't
8512      bother to make this possible.  */
8513   if (giv->derived_from
8514       && ! (giv->always_executed
8515             && loop_insn_first_p (giv->insn, insn)
8516             && loop_insn_first_p (insn, biv->insn)))
8517     return 0;
8518   if (giv->same
8519       && giv->same->derived_from
8520       && ! (giv->same->always_executed
8521             && loop_insn_first_p (giv->same->insn, insn)
8522             && loop_insn_first_p (insn, biv->insn)))
8523     return 0;
8524
8525   return 1;
8526 }
8527
8528 /* If BL appears in X (part of the pattern of INSN), see if we can
8529    eliminate its use.  If so, return 1.  If not, return 0.
8530
8531    If BIV does not appear in X, return 1.
8532
8533    If ELIMINATE_P is non-zero, actually do the elimination.  WHERE indicates
8534    where extra insns should be added.  Depending on how many items have been
8535    moved out of the loop, it will either be before INSN or at the start of
8536    the loop.  */
8537
8538 static int
8539 maybe_eliminate_biv_1 (x, insn, bl, eliminate_p, where)
8540      rtx x, insn;
8541      struct iv_class *bl;
8542      int eliminate_p;
8543      rtx where;
8544 {
8545   enum rtx_code code = GET_CODE (x);
8546   rtx reg = bl->biv->dest_reg;
8547   enum machine_mode mode = GET_MODE (reg);
8548   struct induction *v;
8549   rtx arg, tem;
8550 #ifdef HAVE_cc0
8551   rtx new;
8552 #endif
8553   int arg_operand;
8554   const char *fmt;
8555   int i, j;
8556
8557   switch (code)
8558     {
8559     case REG:
8560       /* If we haven't already been able to do something with this BIV,
8561          we can't eliminate it.  */
8562       if (x == reg)
8563         return 0;
8564       return 1;
8565
8566     case SET:
8567       /* If this sets the BIV, it is not a problem.  */
8568       if (SET_DEST (x) == reg)
8569         return 1;
8570
8571       /* If this is an insn that defines a giv, it is also ok because
8572          it will go away when the giv is reduced.  */
8573       for (v = bl->giv; v; v = v->next_iv)
8574         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8575           return 1;
8576
8577 #ifdef HAVE_cc0
8578       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8579         {
8580           /* Can replace with any giv that was reduced and
8581              that has (MULT_VAL != 0) and (ADD_VAL == 0).
8582              Require a constant for MULT_VAL, so we know it's nonzero.
8583              ??? We disable this optimization to avoid potential
8584              overflows.  */
8585
8586           for (v = bl->giv; v; v = v->next_iv)
8587             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
8588                 && v->add_val == const0_rtx
8589                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8590                 && v->mode == mode
8591                 && 0)
8592               {
8593                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8594                   continue;
8595
8596                 if (! eliminate_p)
8597                   return 1;
8598
8599                 /* If the giv has the opposite direction of change,
8600                    then reverse the comparison.  */
8601                 if (INTVAL (v->mult_val) < 0)
8602                   new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8603                                          const0_rtx, v->new_reg);
8604                 else
8605                   new = v->new_reg;
8606
8607                 /* We can probably test that giv's reduced reg.  */
8608                 if (validate_change (insn, &SET_SRC (x), new, 0))
8609                   return 1;
8610               }
8611
8612           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8613              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8614              Require a constant for MULT_VAL, so we know it's nonzero.
8615              ??? Do this only if ADD_VAL is a pointer to avoid a potential
8616              overflow problem.  */
8617
8618           for (v = bl->giv; v; v = v->next_iv)
8619             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
8620                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8621                 && v->mode == mode
8622                 && (GET_CODE (v->add_val) == SYMBOL_REF
8623                     || GET_CODE (v->add_val) == LABEL_REF
8624                     || GET_CODE (v->add_val) == CONST
8625                     || (GET_CODE (v->add_val) == REG
8626                         && REGNO_POINTER_FLAG (REGNO (v->add_val)))))
8627               {
8628                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8629                   continue;
8630
8631                 if (! eliminate_p)
8632                   return 1;
8633
8634                 /* If the giv has the opposite direction of change,
8635                    then reverse the comparison.  */
8636                 if (INTVAL (v->mult_val) < 0)
8637                   new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8638                                          v->new_reg);
8639                 else
8640                   new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8641                                          copy_rtx (v->add_val));
8642
8643                 /* Replace biv with the giv's reduced register.  */
8644                 update_reg_last_use (v->add_val, insn);
8645                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8646                   return 1;
8647
8648                 /* Insn doesn't support that constant or invariant.  Copy it
8649                    into a register (it will be a loop invariant.)  */
8650                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8651
8652                 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
8653                                   where);
8654
8655                 /* Substitute the new register for its invariant value in
8656                    the compare expression. */
8657                 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8658                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8659                   return 1;
8660               }
8661         }
8662 #endif
8663       break;
8664
8665     case COMPARE:
8666     case EQ:  case NE:
8667     case GT:  case GE:  case GTU:  case GEU:
8668     case LT:  case LE:  case LTU:  case LEU:
8669       /* See if either argument is the biv.  */
8670       if (XEXP (x, 0) == reg)
8671         arg = XEXP (x, 1), arg_operand = 1;
8672       else if (XEXP (x, 1) == reg)
8673         arg = XEXP (x, 0), arg_operand = 0;
8674       else
8675         break;
8676
8677       if (CONSTANT_P (arg))
8678         {
8679           /* First try to replace with any giv that has constant positive
8680              mult_val and constant add_val.  We might be able to support
8681              negative mult_val, but it seems complex to do it in general.  */
8682
8683           for (v = bl->giv; v; v = v->next_iv)
8684             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8685                 && (GET_CODE (v->add_val) == SYMBOL_REF
8686                     || GET_CODE (v->add_val) == LABEL_REF
8687                     || GET_CODE (v->add_val) == CONST
8688                     || (GET_CODE (v->add_val) == REG
8689                         && REGNO_POINTER_FLAG (REGNO (v->add_val))))
8690                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8691                 && v->mode == mode)
8692               {
8693                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8694                   continue;
8695
8696                 if (! eliminate_p)
8697                   return 1;
8698
8699                 /* Replace biv with the giv's reduced reg.  */
8700                 XEXP (x, 1-arg_operand) = v->new_reg;
8701
8702                 /* If all constants are actually constant integers and
8703                    the derived constant can be directly placed in the COMPARE,
8704                    do so.  */
8705                 if (GET_CODE (arg) == CONST_INT
8706                     && GET_CODE (v->mult_val) == CONST_INT
8707                     && GET_CODE (v->add_val) == CONST_INT
8708                     && validate_change (insn, &XEXP (x, arg_operand),
8709                                         GEN_INT (INTVAL (arg)
8710                                                  * INTVAL (v->mult_val)
8711                                                  + INTVAL (v->add_val)), 0))
8712                   return 1;
8713
8714                 /* Otherwise, load it into a register.  */
8715                 tem = gen_reg_rtx (mode);
8716                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8717                 if (validate_change (insn, &XEXP (x, arg_operand), tem, 0))
8718                   return 1;
8719
8720                 /* If that failed, put back the change we made above.  */
8721                 XEXP (x, 1-arg_operand) = reg;
8722               }
8723           
8724           /* Look for giv with positive constant mult_val and nonconst add_val.
8725              Insert insns to calculate new compare value.  
8726              ??? Turn this off due to possible overflow.  */
8727
8728           for (v = bl->giv; v; v = v->next_iv)
8729             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8730                 && ! v->ignore && ! v->maybe_dead && v->always_computable
8731                 && v->mode == mode
8732                 && 0)
8733               {
8734                 rtx tem;
8735
8736                 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8737                   continue;
8738
8739                 if (! eliminate_p)
8740                   return 1;
8741
8742                 tem = gen_reg_rtx (mode);
8743
8744                 /* Replace biv with giv's reduced register.  */
8745                 validate_change (insn, &XEXP (x, 1 - arg_operand),
8746                                  v->new_reg, 1);
8747
8748                 /* Compute value to compare against.  */
8749                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
8750                 /* Use it in this insn.  */
8751                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8752                 if (apply_change_group ())
8753                   return 1;
8754               }
8755         }
8756       else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
8757         {
8758           if (invariant_p (arg) == 1)
8759             {
8760               /* Look for giv with constant positive mult_val and nonconst
8761                  add_val. Insert insns to compute new compare value. 
8762                  ??? Turn this off due to possible overflow.  */
8763
8764               for (v = bl->giv; v; v = v->next_iv)
8765                 if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
8766                     && ! v->ignore && ! v->maybe_dead && v->always_computable
8767                     && v->mode == mode
8768                     && 0)
8769                   {
8770                     rtx tem;
8771
8772                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8773                       continue;
8774
8775                     if (! eliminate_p)
8776                       return 1;
8777
8778                     tem = gen_reg_rtx (mode);
8779
8780                     /* Replace biv with giv's reduced register.  */
8781                     validate_change (insn, &XEXP (x, 1 - arg_operand),
8782                                      v->new_reg, 1);
8783
8784                     /* Compute value to compare against.  */
8785                     emit_iv_add_mult (arg, v->mult_val, v->add_val,
8786                                       tem, where);
8787                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
8788                     if (apply_change_group ())
8789                       return 1;
8790                   }
8791             }
8792
8793           /* This code has problems.  Basically, you can't know when
8794              seeing if we will eliminate BL, whether a particular giv
8795              of ARG will be reduced.  If it isn't going to be reduced,
8796              we can't eliminate BL.  We can try forcing it to be reduced,
8797              but that can generate poor code.
8798
8799              The problem is that the benefit of reducing TV, below should
8800              be increased if BL can actually be eliminated, but this means
8801              we might have to do a topological sort of the order in which
8802              we try to process biv.  It doesn't seem worthwhile to do
8803              this sort of thing now.  */
8804
8805 #if 0
8806           /* Otherwise the reg compared with had better be a biv.  */
8807           if (GET_CODE (arg) != REG
8808               || REG_IV_TYPE (REGNO (arg)) != BASIC_INDUCT)
8809             return 0;
8810
8811           /* Look for a pair of givs, one for each biv,
8812              with identical coefficients.  */
8813           for (v = bl->giv; v; v = v->next_iv)
8814             {
8815               struct induction *tv;
8816
8817               if (v->ignore || v->maybe_dead || v->mode != mode)
8818                 continue;
8819
8820               for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
8821                 if (! tv->ignore && ! tv->maybe_dead
8822                     && rtx_equal_p (tv->mult_val, v->mult_val)
8823                     && rtx_equal_p (tv->add_val, v->add_val)
8824                     && tv->mode == mode)
8825                   {
8826                     if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8827                       continue;
8828
8829                     if (! eliminate_p)
8830                       return 1;
8831
8832                     /* Replace biv with its giv's reduced reg.  */
8833                     XEXP (x, 1-arg_operand) = v->new_reg;
8834                     /* Replace other operand with the other giv's
8835                        reduced reg.  */
8836                     XEXP (x, arg_operand) = tv->new_reg;
8837                     return 1;
8838                   }
8839             }
8840 #endif
8841         }
8842
8843       /* If we get here, the biv can't be eliminated.  */
8844       return 0;
8845
8846     case MEM:
8847       /* If this address is a DEST_ADDR giv, it doesn't matter if the
8848          biv is used in it, since it will be replaced.  */
8849       for (v = bl->giv; v; v = v->next_iv)
8850         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
8851           return 1;
8852       break;
8853
8854     default:
8855       break;
8856     }
8857
8858   /* See if any subexpression fails elimination.  */
8859   fmt = GET_RTX_FORMAT (code);
8860   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
8861     {
8862       switch (fmt[i])
8863         {
8864         case 'e':
8865           if (! maybe_eliminate_biv_1 (XEXP (x, i), insn, bl, 
8866                                        eliminate_p, where))
8867             return 0;
8868           break;
8869
8870         case 'E':
8871           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8872             if (! maybe_eliminate_biv_1 (XVECEXP (x, i, j), insn, bl,
8873                                          eliminate_p, where))
8874               return 0;
8875           break;
8876         }
8877     }
8878
8879   return 1;
8880 }  
8881 \f
8882 /* Return nonzero if the last use of REG
8883    is in an insn following INSN in the same basic block.  */
8884
8885 static int
8886 last_use_this_basic_block (reg, insn)
8887      rtx reg;
8888      rtx insn;
8889 {
8890   rtx n;
8891   for (n = insn;
8892        n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
8893        n = NEXT_INSN (n))
8894     {
8895       if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
8896         return 1;
8897     }
8898   return 0;
8899 }
8900 \f
8901 /* Called via `note_stores' to record the initial value of a biv.  Here we
8902    just record the location of the set and process it later.  */
8903
8904 static void
8905 record_initial (dest, set)
8906      rtx dest;
8907      rtx set;
8908 {
8909   struct iv_class *bl;
8910
8911   if (GET_CODE (dest) != REG
8912       || REGNO (dest) >= max_reg_before_loop
8913       || REG_IV_TYPE (REGNO (dest)) != BASIC_INDUCT)
8914     return;
8915
8916   bl = reg_biv_class[REGNO (dest)];
8917
8918   /* If this is the first set found, record it.  */
8919   if (bl->init_insn == 0)
8920     {
8921       bl->init_insn = note_insn;
8922       bl->init_set = set;
8923     }
8924 }
8925 \f
8926 /* If any of the registers in X are "old" and currently have a last use earlier
8927    than INSN, update them to have a last use of INSN.  Their actual last use
8928    will be the previous insn but it will not have a valid uid_luid so we can't
8929    use it.  */
8930
8931 static void
8932 update_reg_last_use (x, insn)
8933      rtx x;
8934      rtx insn;
8935 {
8936   /* Check for the case where INSN does not have a valid luid.  In this case,
8937      there is no need to modify the regno_last_uid, as this can only happen
8938      when code is inserted after the loop_end to set a pseudo's final value,
8939      and hence this insn will never be the last use of x.  */
8940   if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
8941       && INSN_UID (insn) < max_uid_for_loop
8942       && uid_luid[REGNO_LAST_UID (REGNO (x))] < uid_luid[INSN_UID (insn)])
8943     REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
8944   else
8945     {
8946       register int i, j;
8947       register const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
8948       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8949         {
8950           if (fmt[i] == 'e')
8951             update_reg_last_use (XEXP (x, i), insn);
8952           else if (fmt[i] == 'E')
8953             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8954               update_reg_last_use (XVECEXP (x, i, j), insn);
8955         }
8956     }
8957 }
8958 \f
8959 /* Given a jump insn JUMP, return the condition that will cause it to branch
8960    to its JUMP_LABEL.  If the condition cannot be understood, or is an
8961    inequality floating-point comparison which needs to be reversed, 0 will
8962    be returned.
8963
8964    If EARLIEST is non-zero, it is a pointer to a place where the earliest
8965    insn used in locating the condition was found.  If a replacement test
8966    of the condition is desired, it should be placed in front of that
8967    insn and we will be sure that the inputs are still valid.
8968
8969    The condition will be returned in a canonical form to simplify testing by
8970    callers.  Specifically:
8971
8972    (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
8973    (2) Both operands will be machine operands; (cc0) will have been replaced.
8974    (3) If an operand is a constant, it will be the second operand.
8975    (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
8976        for GE, GEU, and LEU.  */
8977
8978 rtx
8979 get_condition (jump, earliest)
8980      rtx jump;
8981      rtx *earliest;
8982 {
8983   enum rtx_code code;
8984   rtx prev = jump;
8985   rtx set;
8986   rtx tem;
8987   rtx op0, op1;
8988   int reverse_code = 0;
8989   int did_reverse_condition = 0;
8990   enum machine_mode mode;
8991
8992   /* If this is not a standard conditional jump, we can't parse it.  */
8993   if (GET_CODE (jump) != JUMP_INSN
8994       || ! condjump_p (jump) || simplejump_p (jump))
8995     return 0;
8996
8997   code = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 0));
8998   mode = GET_MODE (XEXP (SET_SRC (PATTERN (jump)), 0));
8999   op0 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 0);
9000   op1 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 1);
9001
9002   if (earliest)
9003     *earliest = jump;
9004
9005   /* If this branches to JUMP_LABEL when the condition is false, reverse
9006      the condition.  */
9007   if (GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 2)) == LABEL_REF
9008       && XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump))
9009     code = reverse_condition (code), did_reverse_condition ^= 1;
9010
9011   /* If we are comparing a register with zero, see if the register is set
9012      in the previous insn to a COMPARE or a comparison operation.  Perform
9013      the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
9014      in cse.c  */
9015
9016   while (GET_RTX_CLASS (code) == '<' && op1 == CONST0_RTX (GET_MODE (op0)))
9017     {
9018       /* Set non-zero when we find something of interest.  */
9019       rtx x = 0;
9020
9021 #ifdef HAVE_cc0
9022       /* If comparison with cc0, import actual comparison from compare
9023          insn.  */
9024       if (op0 == cc0_rtx)
9025         {
9026           if ((prev = prev_nonnote_insn (prev)) == 0
9027               || GET_CODE (prev) != INSN
9028               || (set = single_set (prev)) == 0
9029               || SET_DEST (set) != cc0_rtx)
9030             return 0;
9031
9032           op0 = SET_SRC (set);
9033           op1 = CONST0_RTX (GET_MODE (op0));
9034           if (earliest)
9035             *earliest = prev;
9036         }
9037 #endif
9038
9039       /* If this is a COMPARE, pick up the two things being compared.  */
9040       if (GET_CODE (op0) == COMPARE)
9041         {
9042           op1 = XEXP (op0, 1);
9043           op0 = XEXP (op0, 0);
9044           continue;
9045         }
9046       else if (GET_CODE (op0) != REG)
9047         break;
9048
9049       /* Go back to the previous insn.  Stop if it is not an INSN.  We also
9050          stop if it isn't a single set or if it has a REG_INC note because
9051          we don't want to bother dealing with it.  */
9052
9053       if ((prev = prev_nonnote_insn (prev)) == 0
9054           || GET_CODE (prev) != INSN
9055           || FIND_REG_INC_NOTE (prev, 0)
9056           || (set = single_set (prev)) == 0)
9057         break;
9058
9059       /* If this is setting OP0, get what it sets it to if it looks
9060          relevant.  */
9061       if (rtx_equal_p (SET_DEST (set), op0))
9062         {
9063           enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
9064
9065           /* ??? We may not combine comparisons done in a CCmode with
9066              comparisons not done in a CCmode.  This is to aid targets
9067              like Alpha that have an IEEE compliant EQ instruction, and
9068              a non-IEEE compliant BEQ instruction.  The use of CCmode is
9069              actually artificial, simply to prevent the combination, but
9070              should not affect other platforms.
9071
9072              However, we must allow VOIDmode comparisons to match either
9073              CCmode or non-CCmode comparison, because some ports have
9074              modeless comparisons inside branch patterns.
9075
9076              ??? This mode check should perhaps look more like the mode check
9077              in simplify_comparison in combine.  */
9078
9079           if ((GET_CODE (SET_SRC (set)) == COMPARE
9080                || (((code == NE
9081                      || (code == LT
9082                          && GET_MODE_CLASS (inner_mode) == MODE_INT
9083                          && (GET_MODE_BITSIZE (inner_mode)
9084                              <= HOST_BITS_PER_WIDE_INT)
9085                          && (STORE_FLAG_VALUE
9086                              & ((HOST_WIDE_INT) 1
9087                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9088 #ifdef FLOAT_STORE_FLAG_VALUE
9089                      || (code == LT
9090                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9091                          && FLOAT_STORE_FLAG_VALUE < 0)
9092 #endif
9093                      ))
9094                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
9095               && (((GET_MODE_CLASS (mode) == MODE_CC)
9096                    == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9097                   || mode == VOIDmode || inner_mode == VOIDmode))
9098             x = SET_SRC (set);
9099           else if (((code == EQ
9100                      || (code == GE
9101                          && (GET_MODE_BITSIZE (inner_mode)
9102                              <= HOST_BITS_PER_WIDE_INT)
9103                          && GET_MODE_CLASS (inner_mode) == MODE_INT
9104                          && (STORE_FLAG_VALUE
9105                              & ((HOST_WIDE_INT) 1
9106                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9107 #ifdef FLOAT_STORE_FLAG_VALUE
9108                      || (code == GE
9109                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9110                          && FLOAT_STORE_FLAG_VALUE < 0)
9111 #endif
9112                      ))
9113                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
9114                    && (((GET_MODE_CLASS (mode) == MODE_CC)
9115                         == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9116                        || mode == VOIDmode || inner_mode == VOIDmode))
9117
9118             {
9119               /* We might have reversed a LT to get a GE here.  But this wasn't
9120                  actually the comparison of data, so we don't flag that we
9121                  have had to reverse the condition.  */
9122               did_reverse_condition ^= 1;
9123               reverse_code = 1;
9124               x = SET_SRC (set);
9125             }
9126           else
9127             break;
9128         }
9129
9130       else if (reg_set_p (op0, prev))
9131         /* If this sets OP0, but not directly, we have to give up.  */
9132         break;
9133
9134       if (x)
9135         {
9136           if (GET_RTX_CLASS (GET_CODE (x)) == '<')
9137             code = GET_CODE (x);
9138           if (reverse_code)
9139             {
9140               code = reverse_condition (code);
9141               did_reverse_condition ^= 1;
9142               reverse_code = 0;
9143             }
9144
9145           op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9146           if (earliest)
9147             *earliest = prev;
9148         }
9149     }
9150
9151   /* If constant is first, put it last.  */
9152   if (CONSTANT_P (op0))
9153     code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9154
9155   /* If OP0 is the result of a comparison, we weren't able to find what
9156      was really being compared, so fail.  */
9157   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9158     return 0;
9159
9160   /* Canonicalize any ordered comparison with integers involving equality
9161      if we can do computations in the relevant mode and we do not
9162      overflow.  */
9163
9164   if (GET_CODE (op1) == CONST_INT
9165       && GET_MODE (op0) != VOIDmode
9166       && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9167     {
9168       HOST_WIDE_INT const_val = INTVAL (op1);
9169       unsigned HOST_WIDE_INT uconst_val = const_val;
9170       unsigned HOST_WIDE_INT max_val
9171         = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9172
9173       switch (code)
9174         {
9175         case LE:
9176           if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9177             code = LT,  op1 = GEN_INT (const_val + 1);
9178           break;
9179
9180         /* When cross-compiling, const_val might be sign-extended from
9181            BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9182         case GE:
9183           if ((HOST_WIDE_INT) (const_val & max_val)
9184               != (((HOST_WIDE_INT) 1
9185                    << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9186             code = GT, op1 = GEN_INT (const_val - 1);
9187           break;
9188
9189         case LEU:
9190           if (uconst_val < max_val)
9191             code = LTU, op1 = GEN_INT (uconst_val + 1);
9192           break;
9193
9194         case GEU:
9195           if (uconst_val != 0)
9196             code = GTU, op1 = GEN_INT (uconst_val - 1);
9197           break;
9198
9199         default:
9200           break;
9201         }
9202     }
9203
9204   /* If this was floating-point and we reversed anything other than an
9205      EQ or NE, return zero.  */
9206   if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
9207       && did_reverse_condition && code != NE && code != EQ
9208       && ! flag_fast_math
9209       && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
9210     return 0;
9211
9212 #ifdef HAVE_cc0
9213   /* Never return CC0; return zero instead.  */
9214   if (op0 == cc0_rtx)
9215     return 0;
9216 #endif
9217
9218   return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9219 }
9220
9221 /* Similar to above routine, except that we also put an invariant last
9222    unless both operands are invariants.  */
9223
9224 rtx
9225 get_condition_for_loop (x)
9226      rtx x;
9227 {
9228   rtx comparison = get_condition (x, NULL_PTR);
9229
9230   if (comparison == 0
9231       || ! invariant_p (XEXP (comparison, 0))
9232       || invariant_p (XEXP (comparison, 1)))
9233     return comparison;
9234
9235   return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9236                          XEXP (comparison, 1), XEXP (comparison, 0));
9237 }
9238
9239 #ifdef HAVE_decrement_and_branch_on_count
9240 /* Instrument loop for insertion of bct instruction.  We distinguish between
9241    loops with compile-time bounds and those with run-time bounds. 
9242    Information from loop_iterations() is used to compute compile-time bounds.
9243    Run-time bounds should use loop preconditioning, but currently ignored.
9244  */
9245
9246 static void
9247 insert_bct (loop_start, loop_end, loop_info)
9248      rtx loop_start, loop_end;
9249      struct loop_info *loop_info;
9250 {
9251   int i;
9252   unsigned HOST_WIDE_INT n_iterations;
9253
9254   int increment_direction, compare_direction;
9255
9256   /* If the loop condition is <= or >=, the number of iteration
9257       is 1 more than the range of the bounds of the loop.  */
9258   int add_iteration = 0;
9259
9260   enum machine_mode loop_var_mode = word_mode;
9261
9262   int loop_num = uid_loop_num [INSN_UID (loop_start)];
9263
9264   /* It's impossible to instrument a competely unrolled loop.  */
9265   if (loop_info->unroll_number == loop_info->n_iterations)
9266     return;
9267
9268   /* Make sure that the count register is not in use.  */
9269   if (loop_used_count_register [loop_num])
9270     {
9271       if (loop_dump_stream)
9272         fprintf (loop_dump_stream,
9273                  "insert_bct %d: BCT instrumentation failed: count register already in use\n",
9274                  loop_num);
9275       return;
9276     }
9277
9278   /* Make sure that the function has no indirect jumps.  */
9279   if (indirect_jump_in_function)
9280     {
9281       if (loop_dump_stream)
9282         fprintf (loop_dump_stream,
9283                  "insert_bct %d: BCT instrumentation failed: indirect jump in function\n",
9284                  loop_num);
9285       return;
9286     }
9287
9288   /* Make sure that the last loop insn is a conditional jump.  */
9289   if (GET_CODE (PREV_INSN (loop_end)) != JUMP_INSN
9290       || ! condjump_p (PREV_INSN (loop_end))
9291       || simplejump_p (PREV_INSN (loop_end)))
9292     {
9293       if (loop_dump_stream)
9294         fprintf (loop_dump_stream,
9295                  "insert_bct %d: BCT instrumentation failed: invalid jump at loop end\n",
9296                  loop_num);
9297       return;
9298     }
9299
9300   /* Make sure that the loop does not contain a function call
9301      (the count register might be altered by the called function).  */
9302   if (loop_info->has_call)
9303     {
9304       if (loop_dump_stream)
9305         fprintf (loop_dump_stream,
9306                  "insert_bct %d: BCT instrumentation failed: function call in loop\n",
9307                  loop_num);
9308       return;
9309     }
9310
9311   /* Make sure that the loop does not jump via a table.
9312      (the count register might be used to perform the branch on table).  */
9313   if (loop_info->has_tablejump)
9314     {
9315       if (loop_dump_stream)
9316         fprintf (loop_dump_stream,
9317                  "insert_bct %d: BCT instrumentation failed: computed branch in the loop\n",
9318                  loop_num);
9319       return;
9320     }
9321
9322   /* Account for loop unrolling in instrumented iteration count.  */
9323   if (loop_info->unroll_number > 1)
9324     n_iterations = loop_info->n_iterations / loop_info->unroll_number;
9325   else
9326     n_iterations = loop_info->n_iterations;
9327
9328   if (n_iterations != 0 && n_iterations < 3)
9329     {
9330       /* Allow an enclosing outer loop to benefit if possible.  */
9331       if (loop_dump_stream)
9332         fprintf (loop_dump_stream,
9333                  "insert_bct %d: Too few iterations to benefit from BCT optimization\n",
9334                  loop_num);
9335       return;
9336     }
9337
9338   /* Try to instrument the loop.  */
9339
9340   /* Handle the simpler case, where the bounds are known at compile time.  */
9341   if (n_iterations > 0)
9342     {
9343       /* Mark all enclosing loops that they cannot use count register.  */
9344       for (i = loop_num; i != -1; i = loop_outer_loop[i])
9345         loop_used_count_register[i] = 1;
9346       instrument_loop_bct (loop_start, loop_end, GEN_INT (n_iterations));
9347       return;
9348     }
9349
9350   /* Handle the more complex case, that the bounds are NOT known
9351      at compile time.  In this case we generate run_time calculation
9352      of the number of iterations.  */
9353
9354   if (loop_info->iteration_var == 0)
9355     {
9356       if (loop_dump_stream)
9357         fprintf (loop_dump_stream,
9358                  "insert_bct %d: BCT Runtime Instrumentation failed: no loop iteration variable found\n",
9359                  loop_num);
9360       return;
9361     }
9362
9363   if (GET_MODE_CLASS (GET_MODE (loop_info->iteration_var)) != MODE_INT
9364       || GET_MODE_SIZE (GET_MODE (loop_info->iteration_var)) != UNITS_PER_WORD)
9365     {
9366       if (loop_dump_stream)
9367         fprintf (loop_dump_stream,
9368                  "insert_bct %d: BCT Runtime Instrumentation failed: loop variable not integer\n",
9369                  loop_num);
9370       return;
9371     }
9372
9373   /* With runtime bounds, if the compare is of the form '!=' we give up */
9374   if (loop_info->comparison_code == NE)
9375     {
9376       if (loop_dump_stream)
9377         fprintf (loop_dump_stream,
9378                  "insert_bct %d: BCT Runtime Instrumentation failed: runtime bounds with != comparison\n",
9379                  loop_num);
9380       return;
9381     }
9382 /* Use common loop preconditioning code instead.  */
9383 #if 0
9384   else
9385     {
9386       /* We rely on the existence of run-time guard to ensure that the
9387          loop executes at least once.  */
9388       rtx sequence;
9389       rtx iterations_num_reg;
9390
9391       unsigned HOST_WIDE_INT increment_value_abs
9392         = INTVAL (increment) * increment_direction;
9393
9394       /* make sure that the increment is a power of two, otherwise (an
9395          expensive) divide is needed.  */
9396       if (exact_log2 (increment_value_abs) == -1)
9397         {
9398           if (loop_dump_stream)
9399             fprintf (loop_dump_stream,
9400                      "insert_bct: not instrumenting BCT because the increment is not power of 2\n");
9401           return;
9402         }
9403
9404       /* compute the number of iterations */
9405       start_sequence ();
9406       {
9407         rtx temp_reg;
9408
9409         /* Again, the number of iterations is calculated by:
9410            ;
9411            ;                  compare-val - initial-val + (increment -1) + additional-iteration
9412            ; num_iterations = -----------------------------------------------------------------
9413            ;                                           increment
9414          */
9415         /* ??? Do we have to call copy_rtx here before passing rtx to
9416            expand_binop?  */
9417         if (compare_direction > 0)
9418           {
9419             /* <, <= :the loop variable is increasing */
9420             temp_reg = expand_binop (loop_var_mode, sub_optab,
9421                                      comparison_value, initial_value,
9422                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
9423           }
9424         else
9425           {
9426             temp_reg = expand_binop (loop_var_mode, sub_optab,
9427                                      initial_value, comparison_value,
9428                                      NULL_RTX, 0, OPTAB_LIB_WIDEN);
9429           }
9430
9431         if (increment_value_abs - 1 + add_iteration != 0)
9432           temp_reg = expand_binop (loop_var_mode, add_optab, temp_reg,
9433                                    GEN_INT (increment_value_abs - 1
9434                                             + add_iteration),
9435                                    NULL_RTX, 0, OPTAB_LIB_WIDEN);
9436
9437         if (increment_value_abs != 1)
9438           iterations_num_reg = expand_binop (loop_var_mode, asr_optab,
9439                                              temp_reg,
9440                                              GEN_INT (exact_log2 (increment_value_abs)),
9441                                              NULL_RTX, 0, OPTAB_LIB_WIDEN);
9442         else
9443           iterations_num_reg = temp_reg;
9444       }
9445       sequence = gen_sequence ();
9446       end_sequence ();
9447       emit_insn_before (sequence, loop_start);
9448       instrument_loop_bct (loop_start, loop_end, iterations_num_reg);
9449     }
9450
9451   return;
9452 #endif /* Complex case */
9453 }
9454
9455 /* Instrument loop by inserting a bct in it as follows:
9456    1. A new counter register is created.
9457    2. In the head of the loop the new variable is initialized to the value
9458    passed in the loop_num_iterations parameter.
9459    3. At the end of the loop, comparison of the register with 0 is generated.
9460    The created comparison follows the pattern defined for the
9461    decrement_and_branch_on_count insn, so this insn will be generated.
9462    4. The branch on the old variable are deleted.  The compare must remain
9463    because it might be used elsewhere.  If the loop-variable or condition
9464    register are used elsewhere, they will be eliminated by flow.  */
9465
9466 static void
9467 instrument_loop_bct (loop_start, loop_end, loop_num_iterations)
9468      rtx loop_start, loop_end;
9469      rtx loop_num_iterations;
9470 {
9471   rtx counter_reg;
9472   rtx start_label;
9473   rtx sequence;
9474
9475   if (HAVE_decrement_and_branch_on_count)
9476     {
9477       if (loop_dump_stream)
9478         {
9479           fputs ("instrument_bct: Inserting BCT (", loop_dump_stream);
9480           if (GET_CODE (loop_num_iterations) == CONST_INT)
9481             fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC,
9482                      INTVAL (loop_num_iterations));
9483           else
9484             fputs ("runtime", loop_dump_stream);
9485           fputs (" iterations)", loop_dump_stream);
9486         }
9487
9488       /* Discard original jump to continue loop.  Original compare result
9489          may still be live, so it cannot be discarded explicitly.  */
9490       delete_insn (PREV_INSN (loop_end));
9491
9492       /* Insert the label which will delimit the start of the loop.  */
9493       start_label = gen_label_rtx ();
9494       emit_label_after (start_label, loop_start);
9495
9496       /* Insert initialization of the count register into the loop header.  */
9497       start_sequence ();
9498       counter_reg = gen_reg_rtx (word_mode);
9499       emit_insn (gen_move_insn (counter_reg, loop_num_iterations));
9500       sequence = gen_sequence ();
9501       end_sequence ();
9502       emit_insn_before (sequence, loop_start);
9503
9504       /* Insert new comparison on the count register instead of the
9505          old one, generating the needed BCT pattern (that will be
9506          later recognized by assembly generation phase).  */
9507       emit_jump_insn_before (gen_decrement_and_branch_on_count (counter_reg,
9508                                                                 start_label),
9509                              loop_end);
9510       LABEL_NUSES (start_label)++;
9511     }
9512
9513 }
9514 #endif /* HAVE_decrement_and_branch_on_count */
9515
9516 /* Scan the function and determine whether it has indirect (computed) jumps.
9517
9518    This is taken mostly from flow.c; similar code exists elsewhere
9519    in the compiler.  It may be useful to put this into rtlanal.c.  */
9520 static int
9521 indirect_jump_in_function_p (start)
9522      rtx start;
9523 {
9524   rtx insn;
9525
9526   for (insn = start; insn; insn = NEXT_INSN (insn))
9527     if (computed_jump_p (insn))
9528       return 1;
9529
9530   return 0;
9531 }
9532
9533 /* Add MEM to the LOOP_MEMS array, if appropriate.  See the
9534    documentation for LOOP_MEMS for the definition of `appropriate'.
9535    This function is called from prescan_loop via for_each_rtx.  */
9536
9537 static int
9538 insert_loop_mem (mem, data)
9539      rtx *mem;
9540      void *data ATTRIBUTE_UNUSED;
9541 {
9542   int i;
9543   rtx m = *mem;
9544
9545   if (m == NULL_RTX)
9546     return 0;
9547
9548   switch (GET_CODE (m))
9549     {
9550     case MEM:
9551       break;
9552
9553     case CONST_DOUBLE:
9554       /* We're not interested in the MEM associated with a
9555          CONST_DOUBLE, so there's no need to traverse into this.  */
9556       return -1;
9557
9558     default:
9559       /* This is not a MEM.  */
9560       return 0;
9561     }
9562
9563   /* See if we've already seen this MEM.  */
9564   for (i = 0; i < loop_mems_idx; ++i)
9565     if (rtx_equal_p (m, loop_mems[i].mem)) 
9566       {
9567         if (GET_MODE (m) != GET_MODE (loop_mems[i].mem))
9568           /* The modes of the two memory accesses are different.  If
9569              this happens, something tricky is going on, and we just
9570              don't optimize accesses to this MEM.  */
9571           loop_mems[i].optimize = 0;
9572
9573         return 0;
9574       }
9575
9576   /* Resize the array, if necessary.  */
9577   if (loop_mems_idx == loop_mems_allocated) 
9578     {
9579       if (loop_mems_allocated != 0)
9580         loop_mems_allocated *= 2;
9581       else
9582         loop_mems_allocated = 32;
9583
9584       loop_mems = (loop_mem_info*) 
9585         xrealloc (loop_mems,
9586                   loop_mems_allocated * sizeof (loop_mem_info)); 
9587     }
9588
9589   /* Actually insert the MEM.  */
9590   loop_mems[loop_mems_idx].mem = m;
9591   /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9592      because we can't put it in a register.  We still store it in the
9593      table, though, so that if we see the same address later, but in a
9594      non-BLK mode, we'll not think we can optimize it at that point.  */
9595   loop_mems[loop_mems_idx].optimize = (GET_MODE (m) != BLKmode);
9596   loop_mems[loop_mems_idx].reg = NULL_RTX;
9597   ++loop_mems_idx;
9598
9599   return 0;
9600 }
9601
9602 /* Like load_mems, but also ensures that SET_IN_LOOP,
9603    MAY_NOT_OPTIMIZE, REG_SINGLE_USAGE, and INSN_COUNT have the correct
9604    values after load_mems.  */
9605
9606 static void
9607 load_mems_and_recount_loop_regs_set (scan_start, end, loop_top, start,
9608                                      insn_count)
9609      rtx scan_start;
9610      rtx end;
9611      rtx loop_top;
9612      rtx start;
9613      int *insn_count;
9614 {
9615   int nregs = max_reg_num ();
9616
9617   load_mems (scan_start, end, loop_top, start);
9618   
9619   /* Recalculate set_in_loop and friends since load_mems may have
9620      created new registers.  */
9621   if (max_reg_num () > nregs)
9622     {
9623       int i;
9624       int old_nregs;
9625
9626       old_nregs = nregs;
9627       nregs = max_reg_num ();
9628
9629       if ((unsigned) nregs > set_in_loop->num_elements)
9630         {
9631           /* Grow all the arrays.  */
9632           VARRAY_GROW (set_in_loop, nregs);
9633           VARRAY_GROW (n_times_set, nregs);
9634           VARRAY_GROW (may_not_optimize, nregs);
9635           VARRAY_GROW (reg_single_usage, nregs);
9636         }
9637       /* Clear the arrays */
9638       bzero ((char *) &set_in_loop->data, nregs * sizeof (int));
9639       bzero ((char *) &may_not_optimize->data, nregs * sizeof (char));
9640       bzero ((char *) &reg_single_usage->data, nregs * sizeof (rtx));
9641
9642       count_loop_regs_set (loop_top ? loop_top : start, end,
9643                            may_not_optimize, reg_single_usage,
9644                            insn_count, nregs); 
9645
9646       for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9647         {
9648           VARRAY_CHAR (may_not_optimize, i) = 1;
9649           VARRAY_INT (set_in_loop, i) = 1;
9650         }
9651       
9652 #ifdef AVOID_CCMODE_COPIES
9653       /* Don't try to move insns which set CC registers if we should not
9654          create CCmode register copies.  */
9655       for (i = max_reg_num () - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9656         if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9657           VARRAY_CHAR (may_not_optimize, i) = 1;
9658 #endif
9659
9660       /* Set n_times_set for the new registers.  */
9661       bcopy ((char *) (&set_in_loop->data.i[0] + old_nregs),
9662              (char *) (&n_times_set->data.i[0] + old_nregs),
9663              (nregs - old_nregs) * sizeof (int));
9664     }
9665 }
9666
9667 /* Move MEMs into registers for the duration of the loop.  SCAN_START
9668    is the first instruction in the loop (as it is executed).  The
9669    other parameters are as for next_insn_in_loop.  */
9670
9671 static void
9672 load_mems (scan_start, end, loop_top, start)
9673      rtx scan_start;
9674      rtx end;
9675      rtx loop_top;
9676      rtx start;
9677 {
9678   int maybe_never = 0;
9679   int i;
9680   rtx p;
9681   rtx label = NULL_RTX;
9682   rtx end_label = NULL_RTX;
9683
9684   if (loop_mems_idx > 0) 
9685     {
9686       /* Nonzero if the next instruction may never be executed.  */
9687       int next_maybe_never = 0;
9688
9689       /* Check to see if it's possible that some instructions in the
9690          loop are never executed.  */
9691       for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top); 
9692            p != NULL_RTX && !maybe_never; 
9693            p = next_insn_in_loop (p, scan_start, end, loop_top))
9694         {
9695           if (GET_CODE (p) == CODE_LABEL)
9696             maybe_never = 1;
9697           else if (GET_CODE (p) == JUMP_INSN
9698                    /* If we enter the loop in the middle, and scan
9699                       around to the beginning, don't set maybe_never
9700                       for that.  This must be an unconditional jump,
9701                       otherwise the code at the top of the loop might
9702                       never be executed.  Unconditional jumps are
9703                       followed a by barrier then loop end.  */
9704                    && ! (GET_CODE (p) == JUMP_INSN 
9705                          && JUMP_LABEL (p) == loop_top
9706                          && NEXT_INSN (NEXT_INSN (p)) == end
9707                          && simplejump_p (p)))
9708             {
9709               if (!condjump_p (p))
9710                 /* Something complicated.  */
9711                 maybe_never = 1;
9712               else
9713                 /* If there are any more instructions in the loop, they
9714                    might not be reached.  */
9715                 next_maybe_never = 1; 
9716             } 
9717           else if (next_maybe_never)
9718             maybe_never = 1;
9719         }
9720
9721       /* Actually move the MEMs.  */
9722       for (i = 0; i < loop_mems_idx; ++i) 
9723         {
9724           int written = 0;
9725           rtx reg;
9726           rtx mem = loop_mems[i].mem;
9727           rtx mem_list_entry;
9728
9729           if (MEM_VOLATILE_P (mem) 
9730               || invariant_p (XEXP (mem, 0)) != 1)
9731             /* There's no telling whether or not MEM is modified.  */
9732             loop_mems[i].optimize = 0;
9733
9734           /* Go through the MEMs written to in the loop to see if this
9735              one is aliased by one of them.  */
9736           mem_list_entry = loop_store_mems;
9737           while (mem_list_entry)
9738             {
9739               if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9740                 written = 1;
9741               else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9742                                         mem, rtx_varies_p))
9743                 {
9744                   /* MEM is indeed aliased by this store.  */
9745                   loop_mems[i].optimize = 0;
9746                   break;
9747                 }
9748               mem_list_entry = XEXP (mem_list_entry, 1);
9749             }
9750           
9751           /* If this MEM is written to, we must be sure that there
9752              are no reads from another MEM that aliases this one.  */ 
9753           if (loop_mems[i].optimize && written)
9754             {
9755               int j;
9756
9757               for (j = 0; j < loop_mems_idx; ++j)
9758                 {
9759                   if (j == i)
9760                     continue;
9761                   else if (true_dependence (mem,
9762                                             VOIDmode,
9763                                             loop_mems[j].mem,
9764                                             rtx_varies_p))
9765                     {
9766                       /* It's not safe to hoist loop_mems[i] out of
9767                          the loop because writes to it might not be
9768                          seen by reads from loop_mems[j].  */
9769                       loop_mems[i].optimize = 0;
9770                       break;
9771                     }
9772                 }
9773             }
9774
9775           if (maybe_never && may_trap_p (mem))
9776             /* We can't access the MEM outside the loop; it might
9777                cause a trap that wouldn't have happened otherwise.  */
9778             loop_mems[i].optimize = 0;
9779           
9780           if (!loop_mems[i].optimize)
9781             /* We thought we were going to lift this MEM out of the
9782                loop, but later discovered that we could not.  */
9783             continue;
9784
9785           /* Allocate a pseudo for this MEM.  We set REG_USERVAR_P in
9786              order to keep scan_loop from moving stores to this MEM
9787              out of the loop just because this REG is neither a
9788              user-variable nor used in the loop test.  */
9789           reg = gen_reg_rtx (GET_MODE (mem));
9790           REG_USERVAR_P (reg) = 1;
9791           loop_mems[i].reg = reg;
9792
9793           /* Now, replace all references to the MEM with the
9794              corresponding pesudos.  */
9795           for (p = next_insn_in_loop (scan_start, scan_start, end, loop_top);
9796                p != NULL_RTX;
9797                p = next_insn_in_loop (p, scan_start, end, loop_top))
9798             {
9799               rtx_and_int ri;
9800               ri.r = p;
9801               ri.i = i;
9802               for_each_rtx (&p, replace_loop_mem, &ri);
9803             }
9804
9805           if (!apply_change_group ())
9806             /* We couldn't replace all occurrences of the MEM.  */
9807             loop_mems[i].optimize = 0;
9808           else
9809             {
9810               rtx set;
9811
9812               /* Load the memory immediately before START, which is
9813                  the NOTE_LOOP_BEG.  */
9814               set = gen_move_insn (reg, mem);
9815               emit_insn_before (set, start);
9816
9817               if (written)
9818                 {
9819                   if (label == NULL_RTX)
9820                     {
9821                       /* We must compute the former
9822                          right-after-the-end label before we insert
9823                          the new one.  */
9824                       end_label = next_label (end);
9825                       label = gen_label_rtx ();
9826                       emit_label_after (label, end);
9827                     }
9828
9829                   /* Store the memory immediately after END, which is
9830                    the NOTE_LOOP_END.  */
9831                   set = gen_move_insn (copy_rtx (mem), reg); 
9832                   emit_insn_after (set, label);
9833                 }
9834
9835               if (loop_dump_stream)
9836                 {
9837                   fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
9838                            REGNO (reg), (written ? "r/w" : "r/o"));
9839                   print_rtl (loop_dump_stream, mem);
9840                   fputc ('\n', loop_dump_stream);
9841                 }
9842             }
9843         }
9844     }
9845
9846   if (label != NULL_RTX)
9847     {
9848       /* Now, we need to replace all references to the previous exit
9849          label with the new one.  */
9850       rtx_pair rr; 
9851       rr.r1 = end_label;
9852       rr.r2 = label;
9853
9854       for (p = start; p != end; p = NEXT_INSN (p))
9855         {
9856           for_each_rtx (&p, replace_label, &rr);
9857
9858           /* If this is a JUMP_INSN, then we also need to fix the JUMP_LABEL
9859              field.  This is not handled by for_each_rtx because it doesn't
9860              handle unprinted ('0') fields.  We need to update JUMP_LABEL
9861              because the immediately following unroll pass will use it.
9862              replace_label would not work anyways, because that only handles
9863              LABEL_REFs.  */
9864           if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == end_label)
9865             JUMP_LABEL (p) = label;
9866         }
9867     }
9868 }
9869
9870 /* Replace MEM with its associated pseudo register.  This function is
9871    called from load_mems via for_each_rtx.  DATA is actually an
9872    rtx_and_int * describing the instruction currently being scanned
9873    and the MEM we are currently replacing.  */
9874
9875 static int
9876 replace_loop_mem (mem, data)
9877      rtx *mem;
9878      void *data;
9879 {
9880   rtx_and_int *ri; 
9881   rtx insn;
9882   int i;
9883   rtx m = *mem;
9884
9885   if (m == NULL_RTX)
9886     return 0;
9887
9888   switch (GET_CODE (m))
9889     {
9890     case MEM:
9891       break;
9892
9893     case CONST_DOUBLE:
9894       /* We're not interested in the MEM associated with a
9895          CONST_DOUBLE, so there's no need to traverse into one.  */
9896       return -1;
9897
9898     default:
9899       /* This is not a MEM.  */
9900       return 0;
9901     }
9902
9903   ri = (rtx_and_int*) data;
9904   i = ri->i;
9905
9906   if (!rtx_equal_p (loop_mems[i].mem, m))
9907     /* This is not the MEM we are currently replacing.  */
9908     return 0;
9909
9910   insn = ri->r;
9911
9912   /* Actually replace the MEM.  */
9913   validate_change (insn, mem, loop_mems[i].reg, 1);
9914
9915   return 0;
9916 }
9917
9918 /* Replace occurrences of the old exit label for the loop with the new
9919    one.  DATA is an rtx_pair containing the old and new labels,
9920    respectively.  */
9921
9922 static int
9923 replace_label (x, data)
9924      rtx *x;
9925      void *data;
9926 {
9927   rtx l = *x;
9928   rtx old_label = ((rtx_pair*) data)->r1;
9929   rtx new_label = ((rtx_pair*) data)->r2;
9930
9931   if (l == NULL_RTX)
9932     return 0;
9933
9934   if (GET_CODE (l) != LABEL_REF)
9935     return 0;
9936
9937   if (XEXP (l, 0) != old_label)
9938     return 0;
9939   
9940   XEXP (l, 0) = new_label;
9941   ++LABEL_NUSES (new_label);
9942   --LABEL_NUSES (old_label);
9943
9944   return 0;
9945 }
9946