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