OSDN Git Service

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