OSDN Git Service

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