OSDN Git Service

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