OSDN Git Service

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