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