OSDN Git Service

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