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