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