OSDN Git Service

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