OSDN Git Service

(tablejump_internal4+1): Fix typo in condition.
[pf3gnuchains/gcc-fork.git] / gcc / loop.c
1 /* Perform various loop optimizations, including strength reduction.
2    Copyright (C) 1987, 88, 89, 91-4, 1995 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21
22 /* This is the loop optimization pass of the compiler.
23    It finds invariant computations within loops and moves them
24    to the beginning of the loop.  Then it identifies basic and 
25    general induction variables.  Strength reduction is applied to the general
26    induction variables, and induction variable elimination is applied to
27    the basic induction variables.
28
29    It also finds cases where
30    a register is set within the loop by zero-extending a narrower value
31    and changes these to zero the entire register once before the loop
32    and merely copy the low part within the loop.
33
34    Most of the complexity is in heuristics to decide when it is worth
35    while to do these things.  */
36
37 #include <stdio.h>
38 #include "config.h"
39 #include "rtl.h"
40 #include "obstack.h"
41 #include "expr.h"
42 #include "insn-config.h"
43 #include "insn-flags.h"
44 #include "regs.h"
45 #include "hard-reg-set.h"
46 #include "recog.h"
47 #include "flags.h"
48 #include "real.h"
49 #include "loop.h"
50
51 /* Vector mapping INSN_UIDs to luids.
52    The luids are like uids but increase monotonically always.
53    We use them to see whether a jump comes from outside a given loop.  */
54
55 int *uid_luid;
56
57 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
58    number the insn is contained in.  */
59
60 int *uid_loop_num;
61
62 /* 1 + largest uid of any insn.  */
63
64 int max_uid_for_loop;
65
66 /* 1 + luid of last insn.  */
67
68 static int max_luid;
69
70 /* Number of loops detected in current function.  Used as index to the
71    next few tables.  */
72
73 static int max_loop_num;
74
75 /* Indexed by loop number, contains the first and last insn of each loop.  */
76
77 static rtx *loop_number_loop_starts, *loop_number_loop_ends;
78
79 /* For each loop, gives the containing loop number, -1 if none.  */
80
81 int *loop_outer_loop;
82
83 /* Indexed by loop number, contains a nonzero value if the "loop" isn't
84    really a loop (an insn outside the loop branches into it).  */
85
86 static char *loop_invalid;
87
88 /* Indexed by loop number, links together all LABEL_REFs which refer to
89    code labels outside the loop.  Used by routines that need to know all
90    loop exits, such as final_biv_value and final_giv_value.
91
92    This does not include loop exits due to return instructions.  This is
93    because all bivs and givs are pseudos, and hence must be dead after a
94    return, so the presense of a return does not affect any of the
95    optimizations that use this info.  It is simpler to just not include return
96    instructions on this list.  */
97
98 rtx *loop_number_exit_labels;
99
100 /* Indexed by loop number, counts the number of LABEL_REFs on
101    loop_number_exit_labels for this loop and all loops nested inside it.  */
102
103 int *loop_number_exit_count;
104
105 /* Holds the number of loop iterations.  It is zero if the number could not be
106    calculated.  Must be unsigned since the number of iterations can
107    be as high as 2^wordsize-1.  For loops with a wider iterator, this number
108    will will be zero if the number of loop iterations is too large for an
109    unsigned integer to hold.  */
110
111 unsigned HOST_WIDE_INT loop_n_iterations;
112
113 /* Nonzero if there is a subroutine call in the current loop.
114    (unknown_address_altered is also nonzero in this case.)  */
115
116 static int loop_has_call;
117
118 /* Nonzero if there is a volatile memory reference in the current
119    loop.  */
120
121 static int loop_has_volatile;
122
123 /* Added loop_continue which is the NOTE_INSN_LOOP_CONT of the
124    current loop.  A continue statement will generate a branch to
125    NEXT_INSN (loop_continue).  */
126
127 static rtx loop_continue;
128
129 /* Indexed by register number, contains the number of times the reg
130    is set during the loop being scanned.
131    During code motion, a negative value indicates a reg that has been
132    made a candidate; in particular -2 means that it is an candidate that
133    we know is equal to a constant and -1 means that it is an candidate
134    not known equal to a constant.
135    After code motion, regs moved have 0 (which is accurate now)
136    while the failed candidates have the original number of times set.
137
138    Therefore, at all times, == 0 indicates an invariant register;
139    < 0 a conditionally invariant one.  */
140
141 static short *n_times_set;
142
143 /* Original value of n_times_set; same except that this value
144    is not set negative for a reg whose sets have been made candidates
145    and not set to 0 for a reg that is moved.  */
146
147 static short *n_times_used;
148
149 /* Index by register number, 1 indicates that the register
150    cannot be moved or strength reduced.  */
151
152 static char *may_not_optimize;
153
154 /* Nonzero means reg N has already been moved out of one loop.
155    This reduces the desire to move it out of another.  */
156
157 static char *moved_once;
158
159 /* Array of MEMs that are stored in this loop. If there are too many to fit
160    here, we just turn on unknown_address_altered.  */
161
162 #define NUM_STORES 20
163 static rtx loop_store_mems[NUM_STORES];
164
165 /* Index of first available slot in above array.  */
166 static int loop_store_mems_idx;
167
168 /* Nonzero if we don't know what MEMs were changed in the current loop.
169    This happens if the loop contains a call (in which case `loop_has_call'
170    will also be set) or if we store into more than NUM_STORES MEMs.  */
171
172 static int unknown_address_altered;
173
174 /* Count of movable (i.e. invariant) instructions discovered in the loop.  */
175 static int num_movables;
176
177 /* Count of memory write instructions discovered in the loop.  */
178 static int num_mem_sets;
179
180 /* Number of loops contained within the current one, including itself.  */
181 static int loops_enclosed;
182
183 /* Bound on pseudo register number before loop optimization.
184    A pseudo has valid regscan info if its number is < max_reg_before_loop.  */
185 int max_reg_before_loop;
186
187 /* This obstack is used in product_cheap_p to allocate its rtl.  It
188    may call gen_reg_rtx which, in turn, may reallocate regno_reg_rtx.
189    If we used the same obstack that it did, we would be deallocating
190    that array.  */
191
192 static struct obstack temp_obstack;
193
194 /* This is where the pointer to the obstack being used for RTL is stored.  */
195
196 extern struct obstack *rtl_obstack;
197
198 #define obstack_chunk_alloc xmalloc
199 #define obstack_chunk_free free
200
201 extern char *oballoc ();
202 \f
203 /* During the analysis of a loop, a chain of `struct movable's
204    is made to record all the movable insns found.
205    Then the entire chain can be scanned to decide which to move.  */
206
207 struct movable
208 {
209   rtx insn;                     /* A movable insn */
210   rtx set_src;                  /* The expression this reg is set from. */
211   rtx set_dest;                 /* The destination of this SET. */
212   rtx dependencies;             /* When INSN is libcall, this is an EXPR_LIST
213                                    of any registers used within the LIBCALL. */
214   int consec;                   /* Number of consecutive following insns 
215                                    that must be moved with this one.  */
216   int regno;                    /* The register it sets */
217   short lifetime;               /* lifetime of that register;
218                                    may be adjusted when matching movables
219                                    that load the same value are found.  */
220   short savings;                /* Number of insns we can move for this reg,
221                                    including other movables that force this
222                                    or match this one.  */
223   unsigned int cond : 1;        /* 1 if only conditionally movable */
224   unsigned int force : 1;       /* 1 means MUST move this insn */
225   unsigned int global : 1;      /* 1 means reg is live outside this loop */
226                 /* If PARTIAL is 1, GLOBAL means something different:
227                    that the reg is live outside the range from where it is set
228                    to the following label.  */
229   unsigned int done : 1;        /* 1 inhibits further processing of this */
230   
231   unsigned int partial : 1;     /* 1 means this reg is used for zero-extending.
232                                    In particular, moving it does not make it
233                                    invariant.  */
234   unsigned int move_insn : 1;   /* 1 means that we call emit_move_insn to
235                                    load SRC, rather than copying INSN.  */
236   unsigned int is_equiv : 1;    /* 1 means a REG_EQUIV is present on INSN. */
237   enum machine_mode savemode;   /* Nonzero means it is a mode for a low part
238                                    that we should avoid changing when clearing
239                                    the rest of the reg.  */
240   struct movable *match;        /* First entry for same value */
241   struct movable *forces;       /* An insn that must be moved if this is */
242   struct movable *next;
243 };
244
245 FILE *loop_dump_stream;
246
247 /* Forward declarations.  */
248
249 static void find_and_verify_loops ();
250 static void mark_loop_jump ();
251 static void prescan_loop ();
252 static int reg_in_basic_block_p ();
253 static int consec_sets_invariant_p ();
254 static rtx libcall_other_reg ();
255 static int labels_in_range_p ();
256 static void count_loop_regs_set ();
257 static void note_addr_stored ();
258 static int loop_reg_used_before_p ();
259 static void scan_loop ();
260 static void replace_call_address ();
261 static rtx skip_consec_insns ();
262 static int libcall_benefit ();
263 static void ignore_some_movables ();
264 static void force_movables ();
265 static void combine_movables ();
266 static int rtx_equal_for_loop_p ();
267 static void move_movables ();
268 static void strength_reduce ();
269 static int valid_initial_value_p ();
270 static void find_mem_givs ();
271 static void record_biv ();
272 static void check_final_value ();
273 static void record_giv ();
274 static void update_giv_derive ();
275 static int basic_induction_var ();
276 static rtx simplify_giv_expr ();
277 static int general_induction_var ();
278 static int consec_sets_giv ();
279 static int check_dbra_loop ();
280 static rtx express_from ();
281 static int combine_givs_p ();
282 static void combine_givs ();
283 static int product_cheap_p ();
284 static int maybe_eliminate_biv ();
285 static int maybe_eliminate_biv_1 ();
286 static int last_use_this_basic_block ();
287 static void record_initial ();
288 static void update_reg_last_use ();
289 \f
290 /* Relative gain of eliminating various kinds of operations.  */
291 int add_cost;
292 #if 0
293 int shift_cost;
294 int mult_cost;
295 #endif
296
297 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
298    copy the value of the strength reduced giv to its original register.  */
299 int copy_cost;
300
301 void
302 init_loop ()
303 {
304   char *free_point = (char *) oballoc (1);
305   rtx reg = gen_rtx (REG, word_mode, LAST_VIRTUAL_REGISTER + 1);
306
307   add_cost = rtx_cost (gen_rtx (PLUS, word_mode, reg, reg), SET);
308
309   /* We multiply by 2 to reconcile the difference in scale between
310      these two ways of computing costs.  Otherwise the cost of a copy
311      will be far less than the cost of an add.  */
312
313   copy_cost = 2 * 2;
314
315   /* Free the objects we just allocated.  */
316   obfree (free_point);
317
318   /* Initialize the obstack used for rtl in product_cheap_p.  */
319   gcc_obstack_init (&temp_obstack);
320 }
321 \f
322 /* Entry point of this file.  Perform loop optimization
323    on the current function.  F is the first insn of the function
324    and DUMPFILE is a stream for output of a trace of actions taken
325    (or 0 if none should be output).  */
326
327 void
328 loop_optimize (f, dumpfile)
329      /* f is the first instruction of a chain of insns for one function */
330      rtx f;
331      FILE *dumpfile;
332 {
333   register rtx insn;
334   register int i;
335   rtx last_insn;
336
337   loop_dump_stream = dumpfile;
338
339   init_recog_no_volatile ();
340   init_alias_analysis ();
341
342   max_reg_before_loop = max_reg_num ();
343
344   moved_once = (char *) alloca (max_reg_before_loop);
345   bzero (moved_once, max_reg_before_loop);
346
347   regs_may_share = 0;
348
349   /* Count the number of loops. */
350
351   max_loop_num = 0;
352   for (insn = f; insn; insn = NEXT_INSN (insn))
353     {
354       if (GET_CODE (insn) == NOTE
355           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
356         max_loop_num++;
357     }
358
359   /* Don't waste time if no loops.  */
360   if (max_loop_num == 0)
361     return;
362
363   /* Get size to use for tables indexed by uids.
364      Leave some space for labels allocated by find_and_verify_loops.  */
365   max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
366
367   uid_luid = (int *) alloca (max_uid_for_loop * sizeof (int));
368   uid_loop_num = (int *) alloca (max_uid_for_loop * sizeof (int));
369
370   bzero ((char *) uid_luid, max_uid_for_loop * sizeof (int));
371   bzero ((char *) uid_loop_num, max_uid_for_loop * sizeof (int));
372
373   /* Allocate tables for recording each loop.  We set each entry, so they need
374      not be zeroed.  */
375   loop_number_loop_starts = (rtx *) alloca (max_loop_num * sizeof (rtx));
376   loop_number_loop_ends = (rtx *) alloca (max_loop_num * sizeof (rtx));
377   loop_outer_loop = (int *) alloca (max_loop_num * sizeof (int));
378   loop_invalid = (char *) alloca (max_loop_num * sizeof (char));
379   loop_number_exit_labels = (rtx *) alloca (max_loop_num * sizeof (rtx));
380   loop_number_exit_count = (int *) alloca (max_loop_num * sizeof (int));
381
382   /* Find and process each loop.
383      First, find them, and record them in order of their beginnings.  */
384   find_and_verify_loops (f);
385
386   /* Now find all register lifetimes.  This must be done after
387      find_and_verify_loops, because it might reorder the insns in the
388      function.  */
389   reg_scan (f, max_reg_num (), 1);
390
391   /* See if we went too far.  */
392   if (get_max_uid () > max_uid_for_loop)
393     abort ();
394
395   /* Compute the mapping from uids to luids.
396      LUIDs are numbers assigned to insns, like uids,
397      except that luids increase monotonically through the code.
398      Don't assign luids to line-number NOTEs, so that the distance in luids
399      between two insns is not affected by -g.  */
400
401   for (insn = f, i = 0; insn; insn = NEXT_INSN (insn))
402     {
403       last_insn = insn;
404       if (GET_CODE (insn) != NOTE
405           || NOTE_LINE_NUMBER (insn) <= 0)
406         uid_luid[INSN_UID (insn)] = ++i;
407       else
408         /* Give a line number note the same luid as preceding insn.  */
409         uid_luid[INSN_UID (insn)] = i;
410     }
411
412   max_luid = i + 1;
413
414   /* Don't leave gaps in uid_luid for insns that have been
415      deleted.  It is possible that the first or last insn
416      using some register has been deleted by cross-jumping.
417      Make sure that uid_luid for that former insn's uid
418      points to the general area where that insn used to be.  */
419   for (i = 0; i < max_uid_for_loop; i++)
420     {
421       uid_luid[0] = uid_luid[i];
422       if (uid_luid[0] != 0)
423         break;
424     }
425   for (i = 0; i < max_uid_for_loop; i++)
426     if (uid_luid[i] == 0)
427       uid_luid[i] = uid_luid[i - 1];
428
429   /* Create a mapping from loops to BLOCK tree nodes.  */
430   if (flag_unroll_loops && write_symbols != NO_DEBUG)
431     find_loop_tree_blocks ();
432
433   /* Now scan the loops, last ones first, since this means inner ones are done
434      before outer ones.  */
435   for (i = max_loop_num-1; i >= 0; i--)
436     if (! loop_invalid[i] && loop_number_loop_ends[i])
437       scan_loop (loop_number_loop_starts[i], loop_number_loop_ends[i],
438                  max_reg_num ());
439
440   /* If debugging and unrolling loops, we must replicate the tree nodes
441      corresponding to the blocks inside the loop, so that the original one
442      to one mapping will remain.  */
443   if (flag_unroll_loops && write_symbols != NO_DEBUG)
444     unroll_block_trees ();
445 }
446 \f
447 /* Optimize one loop whose start is LOOP_START and end is END.
448    LOOP_START is the NOTE_INSN_LOOP_BEG and END is the matching
449    NOTE_INSN_LOOP_END.  */
450
451 /* ??? Could also move memory writes out of loops if the destination address
452    is invariant, the source is invariant, the memory write is not volatile,
453    and if we can prove that no read inside the loop can read this address
454    before the write occurs.  If there is a read of this address after the
455    write, then we can also mark the memory read as invariant.  */
456
457 static void
458 scan_loop (loop_start, end, nregs)
459      rtx loop_start, end;
460      int nregs;
461 {
462   register int i;
463   register rtx p;
464   /* 1 if we are scanning insns that could be executed zero times.  */
465   int maybe_never = 0;
466   /* 1 if we are scanning insns that might never be executed
467      due to a subroutine call which might exit before they are reached.  */
468   int call_passed = 0;
469   /* For a rotated loop that is entered near the bottom,
470      this is the label at the top.  Otherwise it is zero.  */
471   rtx loop_top = 0;
472   /* Jump insn that enters the loop, or 0 if control drops in.  */
473   rtx loop_entry_jump = 0;
474   /* Place in the loop where control enters.  */
475   rtx scan_start;
476   /* Number of insns in the loop.  */
477   int insn_count;
478   int in_libcall = 0;
479   int tem;
480   rtx temp;
481   /* The SET from an insn, if it is the only SET in the insn.  */
482   rtx set, set1;
483   /* Chain describing insns movable in current loop.  */
484   struct movable *movables = 0;
485   /* Last element in `movables' -- so we can add elements at the end.  */
486   struct movable *last_movable = 0;
487   /* Ratio of extra register life span we can justify
488      for saving an instruction.  More if loop doesn't call subroutines
489      since in that case saving an insn makes more difference
490      and more registers are available.  */
491   int threshold;
492   /* If we have calls, contains the insn in which a register was used
493      if it was used exactly once; contains const0_rtx if it was used more
494      than once.  */
495   rtx *reg_single_usage = 0;
496   /* Nonzero if we are scanning instructions in a sub-loop.  */
497   int loop_depth = 0;
498
499   n_times_set = (short *) alloca (nregs * sizeof (short));
500   n_times_used = (short *) alloca (nregs * sizeof (short));
501   may_not_optimize = (char *) alloca (nregs);
502
503   /* Determine whether this loop starts with a jump down to a test at
504      the end.  This will occur for a small number of loops with a test
505      that is too complex to duplicate in front of the loop.
506
507      We search for the first insn or label in the loop, skipping NOTEs.
508      However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
509      (because we might have a loop executed only once that contains a
510      loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
511      (in case we have a degenerate loop).
512
513      Note that if we mistakenly think that a loop is entered at the top
514      when, in fact, it is entered at the exit test, the only effect will be
515      slightly poorer optimization.  Making the opposite error can generate
516      incorrect code.  Since very few loops now start with a jump to the 
517      exit test, the code here to detect that case is very conservative.  */
518
519   for (p = NEXT_INSN (loop_start);
520        p != end
521          && GET_CODE (p) != CODE_LABEL && GET_RTX_CLASS (GET_CODE (p)) != 'i'
522          && (GET_CODE (p) != NOTE
523              || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
524                  && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
525        p = NEXT_INSN (p))
526     ;
527
528   scan_start = p;
529
530   /* Set up variables describing this loop.  */
531   prescan_loop (loop_start, end);
532   threshold = (loop_has_call ? 1 : 2) * (1 + n_non_fixed_regs);
533
534   /* If loop has a jump before the first label,
535      the true entry is the target of that jump.
536      Start scan from there.
537      But record in LOOP_TOP the place where the end-test jumps
538      back to so we can scan that after the end of the loop.  */
539   if (GET_CODE (p) == JUMP_INSN)
540     {
541       loop_entry_jump = p;
542
543       /* Loop entry must be unconditional jump (and not a RETURN)  */
544       if (simplejump_p (p)
545           && JUMP_LABEL (p) != 0
546           /* Check to see whether the jump actually
547              jumps out of the loop (meaning it's no loop).
548              This case can happen for things like
549              do {..} while (0).  If this label was generated previously
550              by loop, we can't tell anything about it and have to reject
551              the loop.  */
552           && INSN_UID (JUMP_LABEL (p)) < max_uid_for_loop
553           && INSN_LUID (JUMP_LABEL (p)) >= INSN_LUID (loop_start)
554           && INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (end))
555         {
556           loop_top = next_label (scan_start);
557           scan_start = JUMP_LABEL (p);
558         }
559     }
560
561   /* If SCAN_START was an insn created by loop, we don't know its luid
562      as required by loop_reg_used_before_p.  So skip such loops.  (This
563      test may never be true, but it's best to play it safe.) 
564
565      Also, skip loops where we do not start scanning at a label.  This
566      test also rejects loops starting with a JUMP_INSN that failed the
567      test above.  */
568
569   if (INSN_UID (scan_start) >= max_uid_for_loop
570       || GET_CODE (scan_start) != CODE_LABEL)
571     {
572       if (loop_dump_stream)
573         fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
574                  INSN_UID (loop_start), INSN_UID (end));
575       return;
576     }
577
578   /* Count number of times each reg is set during this loop.
579      Set may_not_optimize[I] if it is not safe to move out
580      the setting of register I.  If this loop has calls, set
581      reg_single_usage[I].  */
582
583   bzero ((char *) n_times_set, nregs * sizeof (short));
584   bzero (may_not_optimize, nregs);
585
586   if (loop_has_call)
587     {
588       reg_single_usage = (rtx *) alloca (nregs * sizeof (rtx));
589       bzero ((char *) reg_single_usage, nregs * sizeof (rtx));
590     }
591
592   count_loop_regs_set (loop_top ? loop_top : loop_start, end,
593                        may_not_optimize, reg_single_usage, &insn_count, nregs);
594
595   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
596     may_not_optimize[i] = 1, n_times_set[i] = 1;
597   bcopy ((char *) n_times_set, (char *) n_times_used, nregs * sizeof (short));
598
599   if (loop_dump_stream)
600     {
601       fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
602                INSN_UID (loop_start), INSN_UID (end), insn_count);
603       if (loop_continue)
604         fprintf (loop_dump_stream, "Continue at insn %d.\n",
605                  INSN_UID (loop_continue));
606     }
607
608   /* Scan through the loop finding insns that are safe to move.
609      Set n_times_set negative for the reg being set, so that
610      this reg will be considered invariant for subsequent insns.
611      We consider whether subsequent insns use the reg
612      in deciding whether it is worth actually moving.
613
614      MAYBE_NEVER is nonzero if we have passed a conditional jump insn
615      and therefore it is possible that the insns we are scanning
616      would never be executed.  At such times, we must make sure
617      that it is safe to execute the insn once instead of zero times.
618      When MAYBE_NEVER is 0, all insns will be executed at least once
619      so that is not a problem.  */
620
621   p = scan_start;
622   while (1)
623     {
624       p = NEXT_INSN (p);
625       /* At end of a straight-in loop, we are done.
626          At end of a loop entered at the bottom, scan the top.  */
627       if (p == scan_start)
628         break;
629       if (p == end)
630         {
631           if (loop_top != 0)
632             p = loop_top;
633           else
634             break;
635           if (p == scan_start)
636             break;
637         }
638
639       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
640           && find_reg_note (p, REG_LIBCALL, NULL_RTX))
641         in_libcall = 1;
642       else if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
643                && find_reg_note (p, REG_RETVAL, NULL_RTX))
644         in_libcall = 0;
645
646       if (GET_CODE (p) == INSN
647           && (set = single_set (p))
648           && GET_CODE (SET_DEST (set)) == REG
649           && ! may_not_optimize[REGNO (SET_DEST (set))])
650         {
651           int tem1 = 0;
652           int tem2 = 0;
653           int move_insn = 0;
654           rtx src = SET_SRC (set);
655           rtx dependencies = 0;
656
657           /* Figure out what to use as a source of this insn.  If a REG_EQUIV
658              note is given or if a REG_EQUAL note with a constant operand is
659              specified, use it as the source and mark that we should move
660              this insn by calling emit_move_insn rather that duplicating the
661              insn.
662
663              Otherwise, only use the REG_EQUAL contents if a REG_RETVAL note
664              is present.  */
665           temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
666           if (temp)
667             src = XEXP (temp, 0), move_insn = 1;
668           else 
669             {
670               temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
671               if (temp && CONSTANT_P (XEXP (temp, 0)))
672                 src = XEXP (temp, 0), move_insn = 1;
673               if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
674                 {
675                   src = XEXP (temp, 0);
676                   /* A libcall block can use regs that don't appear in
677                      the equivalent expression.  To move the libcall,
678                      we must move those regs too.  */
679                   dependencies = libcall_other_reg (p, src);
680                 }
681             }
682
683           /* Don't try to optimize a register that was made
684              by loop-optimization for an inner loop.
685              We don't know its life-span, so we can't compute the benefit.  */
686           if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
687             ;
688           /* In order to move a register, we need to have one of three cases:
689              (1) it is used only in the same basic block as the set
690              (2) it is not a user variable and it is not used in the
691                  exit test (this can cause the variable to be used
692                  before it is set just like a user-variable).
693              (3) the set is guaranteed to be executed once the loop starts,
694                  and the reg is not used until after that.  */
695           else if (! ((! maybe_never
696                        && ! loop_reg_used_before_p (set, p, loop_start,
697                                                     scan_start, end))
698                       || (! REG_USERVAR_P (SET_DEST (set))
699                           && ! REG_LOOP_TEST_P (SET_DEST (set)))
700                       || reg_in_basic_block_p (p, SET_DEST (set))))
701             ;
702           else if ((tem = invariant_p (src))
703                    && (dependencies == 0
704                        || (tem2 = invariant_p (dependencies)) != 0)
705                    && (n_times_set[REGNO (SET_DEST (set))] == 1
706                        || (tem1
707                            = consec_sets_invariant_p (SET_DEST (set),
708                                                       n_times_set[REGNO (SET_DEST (set))],
709                                                       p)))
710                    /* If the insn can cause a trap (such as divide by zero),
711                       can't move it unless it's guaranteed to be executed
712                       once loop is entered.  Even a function call might
713                       prevent the trap insn from being reached
714                       (since it might exit!)  */
715                    && ! ((maybe_never || call_passed)
716                          && may_trap_p (src)))
717             {
718               register struct movable *m;
719               register int regno = REGNO (SET_DEST (set));
720
721               /* A potential lossage is where we have a case where two insns
722                  can be combined as long as they are both in the loop, but
723                  we move one of them outside the loop.  For large loops,
724                  this can lose.  The most common case of this is the address
725                  of a function being called.  
726
727                  Therefore, if this register is marked as being used exactly
728                  once if we are in a loop with calls (a "large loop"), see if
729                  we can replace the usage of this register with the source
730                  of this SET.  If we can, delete this insn. 
731
732                  Don't do this if P has a REG_RETVAL note or if we have
733                  SMALL_REGISTER_CLASSES and SET_SRC is a hard register.  */
734
735               if (reg_single_usage && reg_single_usage[regno] != 0
736                   && reg_single_usage[regno] != const0_rtx
737                   && regno_first_uid[regno] == INSN_UID (p)
738                   && (regno_last_uid[regno]
739                       == INSN_UID (reg_single_usage[regno]))
740                   && n_times_set[REGNO (SET_DEST (set))] == 1
741                   && ! side_effects_p (SET_SRC (set))
742                   && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
743 #ifdef SMALL_REGISTER_CLASSES
744                   && ! (GET_CODE (SET_SRC (set)) == REG
745                         && REGNO (SET_SRC (set)) < FIRST_PSEUDO_REGISTER)
746 #endif
747                   /* This test is not redundant; SET_SRC (set) might be
748                      a call-clobbered register and the life of REGNO
749                      might span a call.  */
750                   && ! modified_between_p (SET_SRC (set), p,
751                                            reg_single_usage[regno])
752                   && no_labels_between_p (p, reg_single_usage[regno])
753                   && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
754                                            reg_single_usage[regno]))
755                 {
756                   /* Replace any usage in a REG_EQUAL note.  Must copy the
757                      new source, so that we don't get rtx sharing between the
758                      SET_SOURCE and REG_NOTES of insn p.  */
759                   REG_NOTES (reg_single_usage[regno])
760                     = replace_rtx (REG_NOTES (reg_single_usage[regno]),
761                                    SET_DEST (set), copy_rtx (SET_SRC (set)));
762                                    
763                   PUT_CODE (p, NOTE);
764                   NOTE_LINE_NUMBER (p) = NOTE_INSN_DELETED;
765                   NOTE_SOURCE_FILE (p) = 0;
766                   n_times_set[regno] = 0;
767                   continue;
768                 }
769
770               m = (struct movable *) alloca (sizeof (struct movable));
771               m->next = 0;
772               m->insn = p;
773               m->set_src = src;
774               m->dependencies = dependencies;
775               m->set_dest = SET_DEST (set);
776               m->force = 0;
777               m->consec = n_times_set[REGNO (SET_DEST (set))] - 1;
778               m->done = 0;
779               m->forces = 0;
780               m->partial = 0;
781               m->move_insn = move_insn;
782               m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
783               m->savemode = VOIDmode;
784               m->regno = regno;
785               /* Set M->cond if either invariant_p or consec_sets_invariant_p
786                  returned 2 (only conditionally invariant).  */
787               m->cond = ((tem | tem1 | tem2) > 1);
788               m->global = (uid_luid[regno_last_uid[regno]] > INSN_LUID (end)
789                            || uid_luid[regno_first_uid[regno]] < INSN_LUID (loop_start));
790               m->match = 0;
791               m->lifetime = (uid_luid[regno_last_uid[regno]]
792                              - uid_luid[regno_first_uid[regno]]);
793               m->savings = n_times_used[regno];
794               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
795                 m->savings += libcall_benefit (p);
796               n_times_set[regno] = move_insn ? -2 : -1;
797               /* Add M to the end of the chain MOVABLES.  */
798               if (movables == 0)
799                 movables = m;
800               else
801                 last_movable->next = m;
802               last_movable = m;
803
804               if (m->consec > 0)
805                 {
806                   /* Skip this insn, not checking REG_LIBCALL notes.  */
807                   p = next_nonnote_insn (p);
808                   /* Skip the consecutive insns, if there are any.  */
809                   p = skip_consec_insns (p, m->consec);
810                   /* Back up to the last insn of the consecutive group.  */
811                   p = prev_nonnote_insn (p);
812
813                   /* We must now reset m->move_insn, m->is_equiv, and possibly
814                      m->set_src to correspond to the effects of all the
815                      insns.  */
816                   temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
817                   if (temp)
818                     m->set_src = XEXP (temp, 0), m->move_insn = 1;
819                   else
820                     {
821                       temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
822                       if (temp && CONSTANT_P (XEXP (temp, 0)))
823                         m->set_src = XEXP (temp, 0), m->move_insn = 1;
824                       else
825                         m->move_insn = 0;
826
827                     }
828                   m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
829                 }
830             }
831           /* If this register is always set within a STRICT_LOW_PART
832              or set to zero, then its high bytes are constant.
833              So clear them outside the loop and within the loop
834              just load the low bytes.
835              We must check that the machine has an instruction to do so.
836              Also, if the value loaded into the register
837              depends on the same register, this cannot be done.  */
838           else if (SET_SRC (set) == const0_rtx
839                    && GET_CODE (NEXT_INSN (p)) == INSN
840                    && (set1 = single_set (NEXT_INSN (p)))
841                    && GET_CODE (set1) == SET
842                    && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
843                    && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
844                    && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
845                        == SET_DEST (set))
846                    && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
847             {
848               register int regno = REGNO (SET_DEST (set));
849               if (n_times_set[regno] == 2)
850                 {
851                   register struct movable *m;
852                   m = (struct movable *) alloca (sizeof (struct movable));
853                   m->next = 0;
854                   m->insn = p;
855                   m->set_dest = SET_DEST (set);
856                   m->dependencies = 0;
857                   m->force = 0;
858                   m->consec = 0;
859                   m->done = 0;
860                   m->forces = 0;
861                   m->move_insn = 0;
862                   m->partial = 1;
863                   /* If the insn may not be executed on some cycles,
864                      we can't clear the whole reg; clear just high part.
865                      Not even if the reg is used only within this loop.
866                      Consider this:
867                      while (1)
868                        while (s != t) {
869                          if (foo ()) x = *s;
870                          use (x);
871                        }
872                      Clearing x before the inner loop could clobber a value
873                      being saved from the last time around the outer loop.
874                      However, if the reg is not used outside this loop
875                      and all uses of the register are in the same
876                      basic block as the store, there is no problem.
877
878                      If this insn was made by loop, we don't know its
879                      INSN_LUID and hence must make a conservative
880                      assumption. */
881                   m->global = (INSN_UID (p) >= max_uid_for_loop
882                                || (uid_luid[regno_last_uid[regno]]
883                                    > INSN_LUID (end))
884                                || (uid_luid[regno_first_uid[regno]]
885                                    < INSN_LUID (p))
886                                || (labels_in_range_p
887                                    (p, uid_luid[regno_first_uid[regno]])));
888                   if (maybe_never && m->global)
889                     m->savemode = GET_MODE (SET_SRC (set1));
890                   else
891                     m->savemode = VOIDmode;
892                   m->regno = regno;
893                   m->cond = 0;
894                   m->match = 0;
895                   m->lifetime = (uid_luid[regno_last_uid[regno]]
896                                  - uid_luid[regno_first_uid[regno]]);
897                   m->savings = 1;
898                   n_times_set[regno] = -1;
899                   /* Add M to the end of the chain MOVABLES.  */
900                   if (movables == 0)
901                     movables = m;
902                   else
903                     last_movable->next = m;
904                   last_movable = m;
905                 }
906             }
907         }
908       /* Past a call insn, we get to insns which might not be executed
909          because the call might exit.  This matters for insns that trap.
910          Call insns inside a REG_LIBCALL/REG_RETVAL block always return,
911          so they don't count.  */
912       else if (GET_CODE (p) == CALL_INSN && ! in_libcall)
913         call_passed = 1;
914       /* Past a label or a jump, we get to insns for which we
915          can't count on whether or how many times they will be
916          executed during each iteration.  Therefore, we can
917          only move out sets of trivial variables
918          (those not used after the loop).  */
919       /* Similar code appears twice in strength_reduce.  */
920       else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
921                /* If we enter the loop in the middle, and scan around to the
922                   beginning, don't set maybe_never for that.  This must be an
923                   unconditional jump, otherwise the code at the top of the
924                   loop might never be executed.  Unconditional jumps are
925                   followed a by barrier then loop end.  */
926                && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop_top
927                      && NEXT_INSN (NEXT_INSN (p)) == end
928                      && simplejump_p (p)))
929         maybe_never = 1;
930       else if (GET_CODE (p) == NOTE)
931         {
932           /* At the virtual top of a converted loop, insns are again known to
933              be executed: logically, the loop begins here even though the exit
934              code has been duplicated.  */
935           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
936             maybe_never = call_passed = 0;
937           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
938             loop_depth++;
939           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
940             loop_depth--;
941         }
942     }
943
944   /* If one movable subsumes another, ignore that other.  */
945
946   ignore_some_movables (movables);
947
948   /* For each movable insn, see if the reg that it loads
949      leads when it dies right into another conditionally movable insn.
950      If so, record that the second insn "forces" the first one,
951      since the second can be moved only if the first is.  */
952
953   force_movables (movables);
954
955   /* See if there are multiple movable insns that load the same value.
956      If there are, make all but the first point at the first one
957      through the `match' field, and add the priorities of them
958      all together as the priority of the first.  */
959
960   combine_movables (movables, nregs);
961         
962   /* Now consider each movable insn to decide whether it is worth moving.
963      Store 0 in n_times_set for each reg that is moved.  */
964
965   move_movables (movables, threshold,
966                  insn_count, loop_start, end, nregs);
967
968   /* Now candidates that still are negative are those not moved.
969      Change n_times_set to indicate that those are not actually invariant.  */
970   for (i = 0; i < nregs; i++)
971     if (n_times_set[i] < 0)
972       n_times_set[i] = n_times_used[i];
973
974   if (flag_strength_reduce)
975     strength_reduce (scan_start, end, loop_top,
976                      insn_count, loop_start, end);
977 }
978 \f
979 /* Add elements to *OUTPUT to record all the pseudo-regs
980    mentioned in IN_THIS but not mentioned in NOT_IN_THIS.  */
981
982 void
983 record_excess_regs (in_this, not_in_this, output)
984      rtx in_this, not_in_this;
985      rtx *output;
986 {
987   enum rtx_code code;
988   char *fmt;
989   int i;
990
991   code = GET_CODE (in_this);
992
993   switch (code)
994     {
995     case PC:
996     case CC0:
997     case CONST_INT:
998     case CONST_DOUBLE:
999     case CONST:
1000     case SYMBOL_REF:
1001     case LABEL_REF:
1002       return;
1003
1004     case REG:
1005       if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1006           && ! reg_mentioned_p (in_this, not_in_this))
1007         *output = gen_rtx (EXPR_LIST, VOIDmode, in_this, *output);
1008       return;
1009     }
1010
1011   fmt = GET_RTX_FORMAT (code);
1012   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1013     {
1014       int j;
1015
1016       switch (fmt[i])
1017         {
1018         case 'E':
1019           for (j = 0; j < XVECLEN (in_this, i); j++)
1020             record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1021           break;
1022
1023         case 'e':
1024           record_excess_regs (XEXP (in_this, i), not_in_this, output);
1025           break;
1026         }
1027     }
1028 }
1029 \f
1030 /* Check what regs are referred to in the libcall block ending with INSN,
1031    aside from those mentioned in the equivalent value.
1032    If there are none, return 0.
1033    If there are one or more, return an EXPR_LIST containing all of them.  */
1034
1035 static rtx
1036 libcall_other_reg (insn, equiv)
1037      rtx insn, equiv;
1038 {
1039   rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1040   rtx p = XEXP (note, 0);
1041   rtx output = 0;
1042
1043   /* First, find all the regs used in the libcall block
1044      that are not mentioned as inputs to the result.  */
1045
1046   while (p != insn)
1047     {
1048       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1049           || GET_CODE (p) == CALL_INSN)
1050         record_excess_regs (PATTERN (p), equiv, &output);
1051       p = NEXT_INSN (p);
1052     }
1053
1054   return output;
1055 }
1056 \f
1057 /* Return 1 if all uses of REG
1058    are between INSN and the end of the basic block.  */
1059
1060 static int 
1061 reg_in_basic_block_p (insn, reg)
1062      rtx insn, reg;
1063 {
1064   int regno = REGNO (reg);
1065   rtx p;
1066
1067   if (regno_first_uid[regno] != INSN_UID (insn))
1068     return 0;
1069
1070   /* Search this basic block for the already recorded last use of the reg.  */
1071   for (p = insn; p; p = NEXT_INSN (p))
1072     {
1073       switch (GET_CODE (p))
1074         {
1075         case NOTE:
1076           break;
1077
1078         case INSN:
1079         case CALL_INSN:
1080           /* Ordinary insn: if this is the last use, we win.  */
1081           if (regno_last_uid[regno] == INSN_UID (p))
1082             return 1;
1083           break;
1084
1085         case JUMP_INSN:
1086           /* Jump insn: if this is the last use, we win.  */
1087           if (regno_last_uid[regno] == INSN_UID (p))
1088             return 1;
1089           /* Otherwise, it's the end of the basic block, so we lose.  */
1090           return 0;
1091
1092         case CODE_LABEL:
1093         case BARRIER:
1094           /* It's the end of the basic block, so we lose.  */
1095           return 0;
1096         }
1097     }
1098
1099   /* The "last use" doesn't follow the "first use"??  */
1100   abort ();
1101 }
1102 \f
1103 /* Compute the benefit of eliminating the insns in the block whose
1104    last insn is LAST.  This may be a group of insns used to compute a
1105    value directly or can contain a library call.  */
1106
1107 static int
1108 libcall_benefit (last)
1109      rtx last;
1110 {
1111   rtx insn;
1112   int benefit = 0;
1113
1114   for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1115        insn != last; insn = NEXT_INSN (insn))
1116     {
1117       if (GET_CODE (insn) == CALL_INSN)
1118         benefit += 10;          /* Assume at least this many insns in a library
1119                                    routine. */
1120       else if (GET_CODE (insn) == INSN
1121                && GET_CODE (PATTERN (insn)) != USE
1122                && GET_CODE (PATTERN (insn)) != CLOBBER)
1123         benefit++;
1124     }
1125
1126   return benefit;
1127 }
1128 \f
1129 /* Skip COUNT insns from INSN, counting library calls as 1 insn.  */
1130
1131 static rtx
1132 skip_consec_insns (insn, count)
1133      rtx insn;
1134      int count;
1135 {
1136   for (; count > 0; count--)
1137     {
1138       rtx temp;
1139
1140       /* If first insn of libcall sequence, skip to end.  */
1141       /* Do this at start of loop, since INSN is guaranteed to 
1142          be an insn here.  */
1143       if (GET_CODE (insn) != NOTE
1144           && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1145         insn = XEXP (temp, 0);
1146
1147       do insn = NEXT_INSN (insn);
1148       while (GET_CODE (insn) == NOTE);
1149     }
1150
1151   return insn;
1152 }
1153
1154 /* Ignore any movable whose insn falls within a libcall
1155    which is part of another movable.
1156    We make use of the fact that the movable for the libcall value
1157    was made later and so appears later on the chain.  */
1158
1159 static void
1160 ignore_some_movables (movables)
1161      struct movable *movables;
1162 {
1163   register struct movable *m, *m1;
1164
1165   for (m = movables; m; m = m->next)
1166     {
1167       /* Is this a movable for the value of a libcall?  */
1168       rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1169       if (note)
1170         {
1171           rtx insn;
1172           /* Check for earlier movables inside that range,
1173              and mark them invalid.  We cannot use LUIDs here because
1174              insns created by loop.c for prior loops don't have LUIDs.
1175              Rather than reject all such insns from movables, we just
1176              explicitly check each insn in the libcall (since invariant
1177              libcalls aren't that common).  */
1178           for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1179             for (m1 = movables; m1 != m; m1 = m1->next)
1180               if (m1->insn == insn)
1181                 m1->done = 1;
1182         }
1183     }
1184 }         
1185
1186 /* For each movable insn, see if the reg that it loads
1187    leads when it dies right into another conditionally movable insn.
1188    If so, record that the second insn "forces" the first one,
1189    since the second can be moved only if the first is.  */
1190
1191 static void
1192 force_movables (movables)
1193      struct movable *movables;
1194 {
1195   register struct movable *m, *m1;
1196   for (m1 = movables; m1; m1 = m1->next)
1197     /* Omit this if moving just the (SET (REG) 0) of a zero-extend.  */
1198     if (!m1->partial && !m1->done)
1199       {
1200         int regno = m1->regno;
1201         for (m = m1->next; m; m = m->next)
1202           /* ??? Could this be a bug?  What if CSE caused the
1203              register of M1 to be used after this insn?
1204              Since CSE does not update regno_last_uid,
1205              this insn M->insn might not be where it dies.
1206              But very likely this doesn't matter; what matters is
1207              that M's reg is computed from M1's reg.  */
1208           if (INSN_UID (m->insn) == regno_last_uid[regno]
1209               && !m->done)
1210             break;
1211         if (m != 0 && m->set_src == m1->set_dest
1212             /* If m->consec, m->set_src isn't valid.  */
1213             && m->consec == 0)
1214           m = 0;
1215
1216         /* Increase the priority of the moving the first insn
1217            since it permits the second to be moved as well.  */
1218         if (m != 0)
1219           {
1220             m->forces = m1;
1221             m1->lifetime += m->lifetime;
1222             m1->savings += m1->savings;
1223           }
1224       }
1225 }
1226 \f
1227 /* Find invariant expressions that are equal and can be combined into
1228    one register.  */
1229
1230 static void
1231 combine_movables (movables, nregs)
1232      struct movable *movables;
1233      int nregs;
1234 {
1235   register struct movable *m;
1236   char *matched_regs = (char *) alloca (nregs);
1237   enum machine_mode mode;
1238
1239   /* Regs that are set more than once are not allowed to match
1240      or be matched.  I'm no longer sure why not.  */
1241   /* Perhaps testing m->consec_sets would be more appropriate here?  */
1242
1243   for (m = movables; m; m = m->next)
1244     if (m->match == 0 && n_times_used[m->regno] == 1 && !m->partial)
1245       {
1246         register struct movable *m1;
1247         int regno = m->regno;
1248
1249         bzero (matched_regs, nregs);
1250         matched_regs[regno] = 1;
1251
1252         for (m1 = movables; m1; m1 = m1->next)
1253           if (m != m1 && m1->match == 0 && n_times_used[m1->regno] == 1
1254               /* A reg used outside the loop mustn't be eliminated.  */
1255               && !m1->global
1256               /* A reg used for zero-extending mustn't be eliminated.  */
1257               && !m1->partial
1258               && (matched_regs[m1->regno]
1259                   ||
1260                   (
1261                    /* Can combine regs with different modes loaded from the
1262                       same constant only if the modes are the same or
1263                       if both are integer modes with M wider or the same
1264                       width as M1.  The check for integer is redundant, but
1265                       safe, since the only case of differing destination
1266                       modes with equal sources is when both sources are
1267                       VOIDmode, i.e., CONST_INT.  */
1268                    (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1269                     || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1270                         && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1271                         && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1272                             >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1273                    /* See if the source of M1 says it matches M.  */
1274                    && ((GET_CODE (m1->set_src) == REG
1275                         && matched_regs[REGNO (m1->set_src)])
1276                        || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1277                                                 movables))))
1278               && ((m->dependencies == m1->dependencies)
1279                   || rtx_equal_p (m->dependencies, m1->dependencies)))
1280             {
1281               m->lifetime += m1->lifetime;
1282               m->savings += m1->savings;
1283               m1->done = 1;
1284               m1->match = m;
1285               matched_regs[m1->regno] = 1;
1286             }
1287       }
1288
1289   /* Now combine the regs used for zero-extension.
1290      This can be done for those not marked `global'
1291      provided their lives don't overlap.  */
1292
1293   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1294        mode = GET_MODE_WIDER_MODE (mode))
1295     {
1296       register struct movable *m0 = 0;
1297
1298       /* Combine all the registers for extension from mode MODE.
1299          Don't combine any that are used outside this loop.  */
1300       for (m = movables; m; m = m->next)
1301         if (m->partial && ! m->global
1302             && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1303           {
1304             register struct movable *m1;
1305             int first = uid_luid[regno_first_uid[m->regno]];
1306             int last = uid_luid[regno_last_uid[m->regno]];
1307
1308             if (m0 == 0)
1309               {
1310                 /* First one: don't check for overlap, just record it.  */
1311                 m0 = m;
1312                   continue;
1313               }
1314
1315             /* Make sure they extend to the same mode.
1316                (Almost always true.)  */
1317             if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1318                 continue;
1319
1320             /* We already have one: check for overlap with those
1321                already combined together.  */
1322             for (m1 = movables; m1 != m; m1 = m1->next)
1323               if (m1 == m0 || (m1->partial && m1->match == m0))
1324                 if (! (uid_luid[regno_first_uid[m1->regno]] > last
1325                        || uid_luid[regno_last_uid[m1->regno]] < first))
1326                   goto overlap;
1327
1328             /* No overlap: we can combine this with the others.  */
1329             m0->lifetime += m->lifetime;
1330             m0->savings += m->savings;
1331             m->done = 1;
1332             m->match = m0;
1333
1334           overlap: ;
1335           }
1336     }
1337 }
1338 \f
1339 /* Return 1 if regs X and Y will become the same if moved.  */
1340
1341 static int
1342 regs_match_p (x, y, movables)
1343      rtx x, y;
1344      struct movable *movables;
1345 {
1346   int xn = REGNO (x);
1347   int yn = REGNO (y);
1348   struct movable *mx, *my;
1349
1350   for (mx = movables; mx; mx = mx->next)
1351     if (mx->regno == xn)
1352       break;
1353
1354   for (my = movables; my; my = my->next)
1355     if (my->regno == yn)
1356       break;
1357
1358   return (mx && my
1359           && ((mx->match == my->match && mx->match != 0)
1360               || mx->match == my
1361               || mx == my->match));
1362 }
1363
1364 /* Return 1 if X and Y are identical-looking rtx's.
1365    This is the Lisp function EQUAL for rtx arguments.
1366
1367    If two registers are matching movables or a movable register and an
1368    equivalent constant, consider them equal.  */
1369
1370 static int
1371 rtx_equal_for_loop_p (x, y, movables)
1372      rtx x, y;
1373      struct movable *movables;
1374 {
1375   register int i;
1376   register int j;
1377   register struct movable *m;
1378   register enum rtx_code code;
1379   register char *fmt;
1380
1381   if (x == y)
1382     return 1;
1383   if (x == 0 || y == 0)
1384     return 0;
1385
1386   code = GET_CODE (x);
1387
1388   /* If we have a register and a constant, they may sometimes be
1389      equal.  */
1390   if (GET_CODE (x) == REG && n_times_set[REGNO (x)] == -2
1391       && CONSTANT_P (y))
1392     for (m = movables; m; m = m->next)
1393       if (m->move_insn && m->regno == REGNO (x)
1394           && rtx_equal_p (m->set_src, y))
1395         return 1;
1396
1397   else if (GET_CODE (y) == REG && n_times_set[REGNO (y)] == -2
1398            && CONSTANT_P (x))
1399     for (m = movables; m; m = m->next)
1400       if (m->move_insn && m->regno == REGNO (y)
1401           && rtx_equal_p (m->set_src, x))
1402         return 1;
1403
1404   /* Otherwise, rtx's of different codes cannot be equal.  */
1405   if (code != GET_CODE (y))
1406     return 0;
1407
1408   /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1409      (REG:SI x) and (REG:HI x) are NOT equivalent.  */
1410
1411   if (GET_MODE (x) != GET_MODE (y))
1412     return 0;
1413
1414   /* These three types of rtx's can be compared nonrecursively.  */
1415   if (code == REG)
1416     return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1417
1418   if (code == LABEL_REF)
1419     return XEXP (x, 0) == XEXP (y, 0);
1420   if (code == SYMBOL_REF)
1421     return XSTR (x, 0) == XSTR (y, 0);
1422
1423   /* Compare the elements.  If any pair of corresponding elements
1424      fail to match, return 0 for the whole things.  */
1425
1426   fmt = GET_RTX_FORMAT (code);
1427   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1428     {
1429       switch (fmt[i])
1430         {
1431         case 'w':
1432           if (XWINT (x, i) != XWINT (y, i))
1433             return 0;
1434           break;
1435
1436         case 'i':
1437           if (XINT (x, i) != XINT (y, i))
1438             return 0;
1439           break;
1440
1441         case 'E':
1442           /* Two vectors must have the same length.  */
1443           if (XVECLEN (x, i) != XVECLEN (y, i))
1444             return 0;
1445
1446           /* And the corresponding elements must match.  */
1447           for (j = 0; j < XVECLEN (x, i); j++)
1448             if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j), movables) == 0)
1449               return 0;
1450           break;
1451
1452         case 'e':
1453           if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables) == 0)
1454             return 0;
1455           break;
1456
1457         case 's':
1458           if (strcmp (XSTR (x, i), XSTR (y, i)))
1459             return 0;
1460           break;
1461
1462         case 'u':
1463           /* These are just backpointers, so they don't matter.  */
1464           break;
1465
1466         case '0':
1467           break;
1468
1469           /* It is believed that rtx's at this level will never
1470              contain anything but integers and other rtx's,
1471              except for within LABEL_REFs and SYMBOL_REFs.  */
1472         default:
1473           abort ();
1474         }
1475     }
1476   return 1;
1477 }
1478 \f
1479 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1480   insns in INSNS which use thet reference.  */
1481
1482 static void
1483 add_label_notes (x, insns)
1484      rtx x;
1485      rtx insns;
1486 {
1487   enum rtx_code code = GET_CODE (x);
1488   int i, j;
1489   char *fmt;
1490   rtx insn;
1491
1492   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1493     {
1494       rtx next = next_real_insn (XEXP (x, 0));
1495
1496       /* Don't record labels that refer to dispatch tables.
1497          This is not necessary, since the tablejump references the same label.
1498          And if we did record them, flow.c would make worse code.  */
1499       if (next == 0
1500           || ! (GET_CODE (next) == JUMP_INSN
1501                 && (GET_CODE (PATTERN (next)) == ADDR_VEC
1502                     || GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC)))
1503         {
1504           for (insn = insns; insn; insn = NEXT_INSN (insn))
1505             if (reg_mentioned_p (XEXP (x, 0), insn))
1506               REG_NOTES (insn) = gen_rtx (EXPR_LIST, REG_LABEL, XEXP (x, 0),
1507                                           REG_NOTES (insn));
1508         }
1509       return;
1510     }
1511
1512   fmt = GET_RTX_FORMAT (code);
1513   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1514     {
1515       if (fmt[i] == 'e')
1516         add_label_notes (XEXP (x, i), insns);
1517       else if (fmt[i] == 'E')
1518         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1519           add_label_notes (XVECEXP (x, i, j), insns);
1520     }
1521 }
1522 \f
1523 /* Scan MOVABLES, and move the insns that deserve to be moved.
1524    If two matching movables are combined, replace one reg with the
1525    other throughout.  */
1526
1527 static void
1528 move_movables (movables, threshold, insn_count, loop_start, end, nregs)
1529      struct movable *movables;
1530      int threshold;
1531      int insn_count;
1532      rtx loop_start;
1533      rtx end;
1534      int nregs;
1535 {
1536   rtx new_start = 0;
1537   register struct movable *m;
1538   register rtx p;
1539   /* Map of pseudo-register replacements to handle combining
1540      when we move several insns that load the same value
1541      into different pseudo-registers.  */
1542   rtx *reg_map = (rtx *) alloca (nregs * sizeof (rtx));
1543   char *already_moved = (char *) alloca (nregs);
1544
1545   bzero (already_moved, nregs);
1546   bzero ((char *) reg_map, nregs * sizeof (rtx));
1547
1548   num_movables = 0;
1549
1550   for (m = movables; m; m = m->next)
1551     {
1552       /* Describe this movable insn.  */
1553
1554       if (loop_dump_stream)
1555         {
1556           fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1557                    INSN_UID (m->insn), m->regno, m->lifetime);
1558           if (m->consec > 0)
1559             fprintf (loop_dump_stream, "consec %d, ", m->consec);
1560           if (m->cond)
1561             fprintf (loop_dump_stream, "cond ");
1562           if (m->force)
1563             fprintf (loop_dump_stream, "force ");
1564           if (m->global)
1565             fprintf (loop_dump_stream, "global ");
1566           if (m->done)
1567             fprintf (loop_dump_stream, "done ");
1568           if (m->move_insn)
1569             fprintf (loop_dump_stream, "move-insn ");
1570           if (m->match)
1571             fprintf (loop_dump_stream, "matches %d ",
1572                      INSN_UID (m->match->insn));
1573           if (m->forces)
1574             fprintf (loop_dump_stream, "forces %d ",
1575                      INSN_UID (m->forces->insn));
1576         }
1577
1578       /* Count movables.  Value used in heuristics in strength_reduce.  */
1579       num_movables++;
1580
1581       /* Ignore the insn if it's already done (it matched something else).
1582          Otherwise, see if it is now safe to move.  */
1583
1584       if (!m->done
1585           && (! m->cond
1586               || (1 == invariant_p (m->set_src)
1587                   && (m->dependencies == 0
1588                       || 1 == invariant_p (m->dependencies))
1589                   && (m->consec == 0
1590                       || 1 == consec_sets_invariant_p (m->set_dest,
1591                                                        m->consec + 1,
1592                                                        m->insn))))
1593           && (! m->forces || m->forces->done))
1594         {
1595           register int regno;
1596           register rtx p;
1597           int savings = m->savings;
1598
1599           /* We have an insn that is safe to move.
1600              Compute its desirability.  */
1601
1602           p = m->insn;
1603           regno = m->regno;
1604
1605           if (loop_dump_stream)
1606             fprintf (loop_dump_stream, "savings %d ", savings);
1607
1608           if (moved_once[regno])
1609             {
1610               insn_count *= 2;
1611
1612               if (loop_dump_stream)
1613                 fprintf (loop_dump_stream, "halved since already moved ");
1614             }
1615
1616           /* An insn MUST be moved if we already moved something else
1617              which is safe only if this one is moved too: that is,
1618              if already_moved[REGNO] is nonzero.  */
1619
1620           /* An insn is desirable to move if the new lifetime of the
1621              register is no more than THRESHOLD times the old lifetime.
1622              If it's not desirable, it means the loop is so big
1623              that moving won't speed things up much,
1624              and it is liable to make register usage worse.  */
1625
1626           /* It is also desirable to move if it can be moved at no
1627              extra cost because something else was already moved.  */
1628
1629           if (already_moved[regno]
1630               || (threshold * savings * m->lifetime) >= insn_count
1631               || (m->forces && m->forces->done
1632                   && n_times_used[m->forces->regno] == 1))
1633             {
1634               int count;
1635               register struct movable *m1;
1636               rtx first;
1637
1638               /* Now move the insns that set the reg.  */
1639
1640               if (m->partial && m->match)
1641                 {
1642                   rtx newpat, i1;
1643                   rtx r1, r2;
1644                   /* Find the end of this chain of matching regs.
1645                      Thus, we load each reg in the chain from that one reg.
1646                      And that reg is loaded with 0 directly,
1647                      since it has ->match == 0.  */
1648                   for (m1 = m; m1->match; m1 = m1->match);
1649                   newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1650                                           SET_DEST (PATTERN (m1->insn)));
1651                   i1 = emit_insn_before (newpat, loop_start);
1652
1653                   /* Mark the moved, invariant reg as being allowed to
1654                      share a hard reg with the other matching invariant.  */
1655                   REG_NOTES (i1) = REG_NOTES (m->insn);
1656                   r1 = SET_DEST (PATTERN (m->insn));
1657                   r2 = SET_DEST (PATTERN (m1->insn));
1658                   regs_may_share = gen_rtx (EXPR_LIST, VOIDmode, r1,
1659                                             gen_rtx (EXPR_LIST, VOIDmode, r2,
1660                                                      regs_may_share));
1661                   delete_insn (m->insn);
1662
1663                   if (new_start == 0)
1664                     new_start = i1;
1665
1666                   if (loop_dump_stream)
1667                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1668                 }
1669               /* If we are to re-generate the item being moved with a
1670                  new move insn, first delete what we have and then emit
1671                  the move insn before the loop.  */
1672               else if (m->move_insn)
1673                 {
1674                   rtx i1, temp;
1675
1676                   for (count = m->consec; count >= 0; count--)
1677                     {
1678                       /* If this is the first insn of a library call sequence,
1679                          skip to the end.  */
1680                       if (GET_CODE (p) != NOTE
1681                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1682                         p = XEXP (temp, 0);
1683
1684                       /* If this is the last insn of a libcall sequence, then
1685                          delete every insn in the sequence except the last.
1686                          The last insn is handled in the normal manner.  */
1687                       if (GET_CODE (p) != NOTE
1688                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1689                         {
1690                           temp = XEXP (temp, 0);
1691                           while (temp != p)
1692                             temp = delete_insn (temp);
1693                         }
1694
1695                       p = delete_insn (p);
1696                       while (p && GET_CODE (p) == NOTE)
1697                         p = NEXT_INSN (p);
1698                     }
1699
1700                   start_sequence ();
1701                   emit_move_insn (m->set_dest, m->set_src);
1702                   temp = get_insns ();
1703                   end_sequence ();
1704
1705                   add_label_notes (m->set_src, temp);
1706
1707                   i1 = emit_insns_before (temp, loop_start);
1708                   if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1709                     REG_NOTES (i1)
1710                       = gen_rtx (EXPR_LIST,
1711                                  m->is_equiv ? REG_EQUIV : REG_EQUAL,
1712                                  m->set_src, REG_NOTES (i1));
1713
1714                   if (loop_dump_stream)
1715                     fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1716
1717                   /* The more regs we move, the less we like moving them.  */
1718                   threshold -= 3;
1719                 }
1720               else
1721                 {
1722                   for (count = m->consec; count >= 0; count--)
1723                     {
1724                       rtx i1, temp;
1725
1726                       /* If first insn of libcall sequence, skip to end. */
1727                       /* Do this at start of loop, since p is guaranteed to 
1728                          be an insn here.  */
1729                       if (GET_CODE (p) != NOTE
1730                           && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1731                         p = XEXP (temp, 0);
1732
1733                       /* If last insn of libcall sequence, move all
1734                          insns except the last before the loop.  The last
1735                          insn is handled in the normal manner.  */
1736                       if (GET_CODE (p) != NOTE
1737                           && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1738                         {
1739                           rtx fn_address = 0;
1740                           rtx fn_reg = 0;
1741                           rtx fn_address_insn = 0;
1742
1743                           first = 0;
1744                           for (temp = XEXP (temp, 0); temp != p;
1745                                temp = NEXT_INSN (temp))
1746                             {
1747                               rtx body;
1748                               rtx n;
1749                               rtx next;
1750
1751                               if (GET_CODE (temp) == NOTE)
1752                                 continue;
1753
1754                               body = PATTERN (temp);
1755
1756                               /* Find the next insn after TEMP,
1757                                  not counting USE or NOTE insns.  */
1758                               for (next = NEXT_INSN (temp); next != p;
1759                                    next = NEXT_INSN (next))
1760                                 if (! (GET_CODE (next) == INSN
1761                                        && GET_CODE (PATTERN (next)) == USE)
1762                                     && GET_CODE (next) != NOTE)
1763                                   break;
1764                               
1765                               /* If that is the call, this may be the insn
1766                                  that loads the function address.
1767
1768                                  Extract the function address from the insn
1769                                  that loads it into a register.
1770                                  If this insn was cse'd, we get incorrect code.
1771
1772                                  So emit a new move insn that copies the
1773                                  function address into the register that the
1774                                  call insn will use.  flow.c will delete any
1775                                  redundant stores that we have created.  */
1776                               if (GET_CODE (next) == CALL_INSN
1777                                   && GET_CODE (body) == SET
1778                                   && GET_CODE (SET_DEST (body)) == REG
1779                                   && (n = find_reg_note (temp, REG_EQUAL,
1780                                                          NULL_RTX)))
1781                                 {
1782                                   fn_reg = SET_SRC (body);
1783                                   if (GET_CODE (fn_reg) != REG)
1784                                     fn_reg = SET_DEST (body);
1785                                   fn_address = XEXP (n, 0);
1786                                   fn_address_insn = temp;
1787                                 }
1788                               /* We have the call insn.
1789                                  If it uses the register we suspect it might,
1790                                  load it with the correct address directly.  */
1791                               if (GET_CODE (temp) == CALL_INSN
1792                                   && fn_address != 0
1793                                   && reg_referenced_p (fn_reg, body))
1794                                 emit_insn_after (gen_move_insn (fn_reg,
1795                                                                 fn_address),
1796                                                  fn_address_insn);
1797
1798                               if (GET_CODE (temp) == CALL_INSN)
1799                                 {
1800                                   i1 = emit_call_insn_before (body, loop_start);
1801                                   /* Because the USAGE information potentially
1802                                      contains objects other than hard registers
1803                                      we need to copy it.  */
1804                                   if (CALL_INSN_FUNCTION_USAGE (temp))
1805                                     CALL_INSN_FUNCTION_USAGE (i1) =
1806                                       copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
1807                                 }
1808                               else
1809                                 i1 = emit_insn_before (body, loop_start);
1810                               if (first == 0)
1811                                 first = i1;
1812                               if (temp == fn_address_insn)
1813                                 fn_address_insn = i1;
1814                               REG_NOTES (i1) = REG_NOTES (temp);
1815                               delete_insn (temp);
1816                             }
1817                         }
1818                       if (m->savemode != VOIDmode)
1819                         {
1820                           /* P sets REG to zero; but we should clear only
1821                              the bits that are not covered by the mode
1822                              m->savemode.  */
1823                           rtx reg = m->set_dest;
1824                           rtx sequence;
1825                           rtx tem;
1826                       
1827                           start_sequence ();
1828                           tem = expand_binop
1829                             (GET_MODE (reg), and_optab, reg,
1830                              GEN_INT ((((HOST_WIDE_INT) 1
1831                                         << GET_MODE_BITSIZE (m->savemode)))
1832                                       - 1),
1833                              reg, 1, OPTAB_LIB_WIDEN);
1834                           if (tem == 0)
1835                             abort ();
1836                           if (tem != reg)
1837                             emit_move_insn (reg, tem);
1838                           sequence = gen_sequence ();
1839                           end_sequence ();
1840                           i1 = emit_insn_before (sequence, loop_start);
1841                         }
1842                       else if (GET_CODE (p) == CALL_INSN)
1843                         {
1844                           i1 = emit_call_insn_before (PATTERN (p), loop_start);
1845                           /* Because the USAGE information potentially
1846                              contains objects other than hard registers
1847                              we need to copy it.  */
1848                           if (CALL_INSN_FUNCTION_USAGE (p))
1849                             CALL_INSN_FUNCTION_USAGE (i1) =
1850                               copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
1851                         }
1852                       else
1853                         i1 = emit_insn_before (PATTERN (p), loop_start);
1854
1855                       REG_NOTES (i1) = REG_NOTES (p);
1856
1857                       /* If there is a REG_EQUAL note present whose value is
1858                          not loop invariant, then delete it, since it may
1859                          cause problems with later optimization passes.
1860                          It is possible for cse to create such notes
1861                          like this as a result of record_jump_cond.  */
1862                       
1863                       if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
1864                           && ! invariant_p (XEXP (temp, 0)))
1865                         remove_note (i1, temp);
1866
1867                       if (new_start == 0)
1868                         new_start = i1;
1869
1870                       if (loop_dump_stream)
1871                         fprintf (loop_dump_stream, " moved to %d",
1872                                  INSN_UID (i1));
1873
1874 #if 0
1875                       /* This isn't needed because REG_NOTES is copied
1876                          below and is wrong since P might be a PARALLEL.  */
1877                       if (REG_NOTES (i1) == 0
1878                           && ! m->partial /* But not if it's a zero-extend clr. */
1879                           && ! m->global /* and not if used outside the loop
1880                                             (since it might get set outside).  */
1881                           && CONSTANT_P (SET_SRC (PATTERN (p))))
1882                         REG_NOTES (i1)
1883                           = gen_rtx (EXPR_LIST, REG_EQUAL,
1884                                      SET_SRC (PATTERN (p)), REG_NOTES (i1));
1885 #endif
1886
1887                       /* If library call, now fix the REG_NOTES that contain
1888                          insn pointers, namely REG_LIBCALL on FIRST
1889                          and REG_RETVAL on I1.  */
1890                       if (temp = find_reg_note (i1, REG_RETVAL, NULL_RTX))
1891                         {
1892                           XEXP (temp, 0) = first;
1893                           temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
1894                           XEXP (temp, 0) = i1;
1895                         }
1896
1897                       delete_insn (p);
1898                       do p = NEXT_INSN (p);
1899                       while (p && GET_CODE (p) == NOTE);
1900                     }
1901
1902                   /* The more regs we move, the less we like moving them.  */
1903                   threshold -= 3;
1904                 }
1905
1906               /* Any other movable that loads the same register
1907                  MUST be moved.  */
1908               already_moved[regno] = 1;
1909
1910               /* This reg has been moved out of one loop.  */
1911               moved_once[regno] = 1;
1912
1913               /* The reg set here is now invariant.  */
1914               if (! m->partial)
1915                 n_times_set[regno] = 0;
1916
1917               m->done = 1;
1918
1919               /* Change the length-of-life info for the register
1920                  to say it lives at least the full length of this loop.
1921                  This will help guide optimizations in outer loops.  */
1922
1923               if (uid_luid[regno_first_uid[regno]] > INSN_LUID (loop_start))
1924                 /* This is the old insn before all the moved insns.
1925                    We can't use the moved insn because it is out of range
1926                    in uid_luid.  Only the old insns have luids.  */
1927                 regno_first_uid[regno] = INSN_UID (loop_start);
1928               if (uid_luid[regno_last_uid[regno]] < INSN_LUID (end))
1929                 regno_last_uid[regno] = INSN_UID (end);
1930
1931               /* Combine with this moved insn any other matching movables.  */
1932
1933               if (! m->partial)
1934                 for (m1 = movables; m1; m1 = m1->next)
1935                   if (m1->match == m)
1936                     {
1937                       rtx temp;
1938
1939                       /* Schedule the reg loaded by M1
1940                          for replacement so that shares the reg of M.
1941                          If the modes differ (only possible in restricted
1942                          circumstances, make a SUBREG.  */
1943                       if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
1944                         reg_map[m1->regno] = m->set_dest;
1945                       else
1946                         reg_map[m1->regno]
1947                           = gen_lowpart_common (GET_MODE (m1->set_dest),
1948                                                 m->set_dest);
1949                     
1950                       /* Get rid of the matching insn
1951                          and prevent further processing of it.  */
1952                       m1->done = 1;
1953
1954                       /* if library call, delete all insn except last, which
1955                          is deleted below */
1956                       if (temp = find_reg_note (m1->insn, REG_RETVAL,
1957                                                 NULL_RTX))
1958                         {
1959                           for (temp = XEXP (temp, 0); temp != m1->insn;
1960                                temp = NEXT_INSN (temp))
1961                             delete_insn (temp);
1962                         }
1963                       delete_insn (m1->insn);
1964
1965                       /* Any other movable that loads the same register
1966                          MUST be moved.  */
1967                       already_moved[m1->regno] = 1;
1968
1969                       /* The reg merged here is now invariant,
1970                          if the reg it matches is invariant.  */
1971                       if (! m->partial)
1972                         n_times_set[m1->regno] = 0;
1973                     }
1974             }
1975           else if (loop_dump_stream)
1976             fprintf (loop_dump_stream, "not desirable");
1977         }
1978       else if (loop_dump_stream && !m->match)
1979         fprintf (loop_dump_stream, "not safe");
1980
1981       if (loop_dump_stream)
1982         fprintf (loop_dump_stream, "\n");
1983     }
1984
1985   if (new_start == 0)
1986     new_start = loop_start;
1987
1988   /* Go through all the instructions in the loop, making
1989      all the register substitutions scheduled in REG_MAP.  */
1990   for (p = new_start; p != end; p = NEXT_INSN (p))
1991     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1992         || GET_CODE (p) == CALL_INSN)
1993       {
1994         replace_regs (PATTERN (p), reg_map, nregs, 0);
1995         replace_regs (REG_NOTES (p), reg_map, nregs, 0);
1996         INSN_CODE (p) = -1;
1997       }
1998 }
1999 \f
2000 #if 0
2001 /* Scan X and replace the address of any MEM in it with ADDR.
2002    REG is the address that MEM should have before the replacement.  */
2003
2004 static void
2005 replace_call_address (x, reg, addr)
2006      rtx x, reg, addr;
2007 {
2008   register enum rtx_code code;
2009   register int i;
2010   register char *fmt;
2011
2012   if (x == 0)
2013     return;
2014   code = GET_CODE (x);
2015   switch (code)
2016     {
2017     case PC:
2018     case CC0:
2019     case CONST_INT:
2020     case CONST_DOUBLE:
2021     case CONST:
2022     case SYMBOL_REF:
2023     case LABEL_REF:
2024     case REG:
2025       return;
2026
2027     case SET:
2028       /* Short cut for very common case.  */
2029       replace_call_address (XEXP (x, 1), reg, addr);
2030       return;
2031
2032     case CALL:
2033       /* Short cut for very common case.  */
2034       replace_call_address (XEXP (x, 0), reg, addr);
2035       return;
2036
2037     case MEM:
2038       /* If this MEM uses a reg other than the one we expected,
2039          something is wrong.  */
2040       if (XEXP (x, 0) != reg)
2041         abort ();
2042       XEXP (x, 0) = addr;
2043       return;
2044     }
2045
2046   fmt = GET_RTX_FORMAT (code);
2047   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2048     {
2049       if (fmt[i] == 'e')
2050         replace_call_address (XEXP (x, i), reg, addr);
2051       if (fmt[i] == 'E')
2052         {
2053           register int j;
2054           for (j = 0; j < XVECLEN (x, i); j++)
2055             replace_call_address (XVECEXP (x, i, j), reg, addr);
2056         }
2057     }
2058 }
2059 #endif
2060 \f
2061 /* Return the number of memory refs to addresses that vary
2062    in the rtx X.  */
2063
2064 static int
2065 count_nonfixed_reads (x)
2066      rtx x;
2067 {
2068   register enum rtx_code code;
2069   register int i;
2070   register char *fmt;
2071   int value;
2072
2073   if (x == 0)
2074     return 0;
2075
2076   code = GET_CODE (x);
2077   switch (code)
2078     {
2079     case PC:
2080     case CC0:
2081     case CONST_INT:
2082     case CONST_DOUBLE:
2083     case CONST:
2084     case SYMBOL_REF:
2085     case LABEL_REF:
2086     case REG:
2087       return 0;
2088
2089     case MEM:
2090       return ((invariant_p (XEXP (x, 0)) != 1)
2091               + count_nonfixed_reads (XEXP (x, 0)));
2092     }
2093
2094   value = 0;
2095   fmt = GET_RTX_FORMAT (code);
2096   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2097     {
2098       if (fmt[i] == 'e')
2099         value += count_nonfixed_reads (XEXP (x, i));
2100       if (fmt[i] == 'E')
2101         {
2102           register int j;
2103           for (j = 0; j < XVECLEN (x, i); j++)
2104             value += count_nonfixed_reads (XVECEXP (x, i, j));
2105         }
2106     }
2107   return value;
2108 }
2109
2110 \f
2111 #if 0
2112 /* P is an instruction that sets a register to the result of a ZERO_EXTEND.
2113    Replace it with an instruction to load just the low bytes
2114    if the machine supports such an instruction,
2115    and insert above LOOP_START an instruction to clear the register.  */
2116
2117 static void
2118 constant_high_bytes (p, loop_start)
2119      rtx p, loop_start;
2120 {
2121   register rtx new;
2122   register int insn_code_number;
2123
2124   /* Try to change (SET (REG ...) (ZERO_EXTEND (..:B ...)))
2125      to (SET (STRICT_LOW_PART (SUBREG:B (REG...))) ...).  */
2126
2127   new = gen_rtx (SET, VOIDmode,
2128                  gen_rtx (STRICT_LOW_PART, VOIDmode,
2129                           gen_rtx (SUBREG, GET_MODE (XEXP (SET_SRC (PATTERN (p)), 0)),
2130                                    SET_DEST (PATTERN (p)),
2131                                    0)),
2132                  XEXP (SET_SRC (PATTERN (p)), 0));
2133   insn_code_number = recog (new, p);
2134
2135   if (insn_code_number)
2136     {
2137       register int i;
2138
2139       /* Clear destination register before the loop.  */
2140       emit_insn_before (gen_rtx (SET, VOIDmode,
2141                                  SET_DEST (PATTERN (p)),
2142                                  const0_rtx),
2143                         loop_start);
2144
2145       /* Inside the loop, just load the low part.  */
2146       PATTERN (p) = new;
2147     }
2148 }
2149 #endif
2150 \f
2151 /* Scan a loop setting the variables `unknown_address_altered',
2152    `num_mem_sets', `loop_continue', loops_enclosed', `loop_has_call',
2153    and `loop_has_volatile'.
2154    Also, fill in the array `loop_store_mems'.  */
2155
2156 static void
2157 prescan_loop (start, end)
2158      rtx start, end;
2159 {
2160   register int level = 1;
2161   register rtx insn;
2162
2163   unknown_address_altered = 0;
2164   loop_has_call = 0;
2165   loop_has_volatile = 0;
2166   loop_store_mems_idx = 0;
2167
2168   num_mem_sets = 0;
2169   loops_enclosed = 1;
2170   loop_continue = 0;
2171
2172   for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2173        insn = NEXT_INSN (insn))
2174     {
2175       if (GET_CODE (insn) == NOTE)
2176         {
2177           if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2178             {
2179               ++level;
2180               /* Count number of loops contained in this one.  */
2181               loops_enclosed++;
2182             }
2183           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2184             {
2185               --level;
2186               if (level == 0)
2187                 {
2188                   end = insn;
2189                   break;
2190                 }
2191             }
2192           else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_CONT)
2193             {
2194               if (level == 1)
2195                 loop_continue = insn;
2196             }
2197         }
2198       else if (GET_CODE (insn) == CALL_INSN)
2199         {
2200           unknown_address_altered = 1;
2201           loop_has_call = 1;
2202         }
2203       else
2204         {
2205           if (GET_CODE (insn) == INSN || GET_CODE (insn) == JUMP_INSN)
2206             {
2207               if (volatile_refs_p (PATTERN (insn)))
2208                 loop_has_volatile = 1;
2209
2210               note_stores (PATTERN (insn), note_addr_stored);
2211             }
2212         }
2213     }
2214 }
2215 \f
2216 /* Scan the function looking for loops.  Record the start and end of each loop.
2217    Also mark as invalid loops any loops that contain a setjmp or are branched
2218    to from outside the loop.  */
2219
2220 static void
2221 find_and_verify_loops (f)
2222      rtx f;
2223 {
2224   rtx insn, label;
2225   int current_loop = -1;
2226   int next_loop = -1;
2227   int loop;
2228
2229   /* If there are jumps to undefined labels,
2230      treat them as jumps out of any/all loops.
2231      This also avoids writing past end of tables when there are no loops.  */
2232   uid_loop_num[0] = -1;
2233
2234   /* Find boundaries of loops, mark which loops are contained within
2235      loops, and invalidate loops that have setjmp.  */
2236
2237   for (insn = f; insn; insn = NEXT_INSN (insn))
2238     {
2239       if (GET_CODE (insn) == NOTE)
2240         switch (NOTE_LINE_NUMBER (insn))
2241           {
2242           case NOTE_INSN_LOOP_BEG:
2243             loop_number_loop_starts[++next_loop] =  insn;
2244             loop_number_loop_ends[next_loop] = 0;
2245             loop_outer_loop[next_loop] = current_loop;
2246             loop_invalid[next_loop] = 0;
2247             loop_number_exit_labels[next_loop] = 0;
2248             loop_number_exit_count[next_loop] = 0;
2249             current_loop = next_loop;
2250             break;
2251
2252           case NOTE_INSN_SETJMP:
2253             /* In this case, we must invalidate our current loop and any
2254                enclosing loop.  */
2255             for (loop = current_loop; loop != -1; loop = loop_outer_loop[loop])
2256               {
2257                 loop_invalid[loop] = 1;
2258                 if (loop_dump_stream)
2259                   fprintf (loop_dump_stream,
2260                            "\nLoop at %d ignored due to setjmp.\n",
2261                            INSN_UID (loop_number_loop_starts[loop]));
2262               }
2263             break;
2264
2265           case NOTE_INSN_LOOP_END:
2266             if (current_loop == -1)
2267               abort ();
2268
2269             loop_number_loop_ends[current_loop] = insn;
2270             current_loop = loop_outer_loop[current_loop];
2271             break;
2272
2273           }
2274
2275       /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2276          enclosing loop, but this doesn't matter.  */
2277       uid_loop_num[INSN_UID (insn)] = current_loop;
2278     }
2279
2280   /* Any loop containing a label used in an initializer must be invalidated,
2281      because it can be jumped into from anywhere.  */
2282
2283   for (label = forced_labels; label; label = XEXP (label, 1))
2284     {
2285       int loop_num;
2286
2287       for (loop_num = uid_loop_num[INSN_UID (XEXP (label, 0))];
2288            loop_num != -1;
2289            loop_num = loop_outer_loop[loop_num])
2290         loop_invalid[loop_num] = 1;
2291     }
2292
2293   /* Now scan all insn's in the function.  If any JUMP_INSN branches into a
2294      loop that it is not contained within, that loop is marked invalid.
2295      If any INSN or CALL_INSN uses a label's address, then the loop containing
2296      that label is marked invalid, because it could be jumped into from
2297      anywhere.
2298
2299      Also look for blocks of code ending in an unconditional branch that
2300      exits the loop.  If such a block is surrounded by a conditional 
2301      branch around the block, move the block elsewhere (see below) and
2302      invert the jump to point to the code block.  This may eliminate a
2303      label in our loop and will simplify processing by both us and a
2304      possible second cse pass.  */
2305
2306   for (insn = f; insn; insn = NEXT_INSN (insn))
2307     if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
2308       {
2309         int this_loop_num = uid_loop_num[INSN_UID (insn)];
2310
2311         if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2312           {
2313             rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2314             if (note)
2315               {
2316                 int loop_num;
2317
2318                 for (loop_num = uid_loop_num[INSN_UID (XEXP (note, 0))];
2319                      loop_num != -1;
2320                      loop_num = loop_outer_loop[loop_num])
2321                   loop_invalid[loop_num] = 1;
2322               }
2323           }
2324
2325         if (GET_CODE (insn) != JUMP_INSN)
2326           continue;
2327
2328         mark_loop_jump (PATTERN (insn), this_loop_num);
2329
2330         /* See if this is an unconditional branch outside the loop.  */
2331         if (this_loop_num != -1
2332             && (GET_CODE (PATTERN (insn)) == RETURN
2333                 || (simplejump_p (insn)
2334                     && (uid_loop_num[INSN_UID (JUMP_LABEL (insn))]
2335                         != this_loop_num)))
2336             && get_max_uid () < max_uid_for_loop)
2337           {
2338             rtx p;
2339             rtx our_next = next_real_insn (insn);
2340             int dest_loop;
2341             int outer_loop = -1;
2342
2343             /* Go backwards until we reach the start of the loop, a label,
2344                or a JUMP_INSN.  */
2345             for (p = PREV_INSN (insn);
2346                  GET_CODE (p) != CODE_LABEL
2347                  && ! (GET_CODE (p) == NOTE
2348                        && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2349                  && GET_CODE (p) != JUMP_INSN;
2350                  p = PREV_INSN (p))
2351               ;
2352
2353             /* Check for the case where we have a jump to an inner nested
2354                loop, and do not perform the optimization in that case.  */
2355
2356             if (JUMP_LABEL (insn))
2357               {
2358                 dest_loop = uid_loop_num[INSN_UID (JUMP_LABEL (insn))];
2359                 if (dest_loop != -1)
2360                   {
2361                     for (outer_loop = dest_loop; outer_loop != -1;
2362                          outer_loop = loop_outer_loop[outer_loop])
2363                       if (outer_loop == this_loop_num)
2364                         break;
2365                   }
2366               }
2367
2368             /* Make sure that the target of P is within the current loop.  */
2369
2370             if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2371                 && uid_loop_num[INSN_UID (JUMP_LABEL (p))] != this_loop_num)
2372               outer_loop = this_loop_num;
2373
2374             /* If we stopped on a JUMP_INSN to the next insn after INSN,
2375                we have a block of code to try to move.
2376
2377                We look backward and then forward from the target of INSN
2378                to find a BARRIER at the same loop depth as the target.
2379                If we find such a BARRIER, we make a new label for the start
2380                of the block, invert the jump in P and point it to that label,
2381                and move the block of code to the spot we found.  */
2382
2383             if (outer_loop == -1
2384                 && GET_CODE (p) == JUMP_INSN
2385                 && JUMP_LABEL (p) != 0
2386                 /* Just ignore jumps to labels that were never emitted.
2387                    These always indicate compilation errors.  */
2388                 && INSN_UID (JUMP_LABEL (p)) != 0
2389                 && condjump_p (p)
2390                 && ! simplejump_p (p)
2391                 && next_real_insn (JUMP_LABEL (p)) == our_next)
2392               {
2393                 rtx target
2394                   = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2395                 int target_loop_num = uid_loop_num[INSN_UID (target)];
2396                 rtx loc;
2397
2398                 for (loc = target; loc; loc = PREV_INSN (loc))
2399                   if (GET_CODE (loc) == BARRIER
2400                       && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2401                     break;
2402
2403                 if (loc == 0)
2404                   for (loc = target; loc; loc = NEXT_INSN (loc))
2405                     if (GET_CODE (loc) == BARRIER
2406                         && uid_loop_num[INSN_UID (loc)] == target_loop_num)
2407                       break;
2408
2409                 if (loc)
2410                   {
2411                     rtx cond_label = JUMP_LABEL (p);
2412                     rtx new_label = get_label_after (p);
2413
2414                     /* Ensure our label doesn't go away.  */
2415                     LABEL_NUSES (cond_label)++;
2416
2417                     /* Verify that uid_loop_num is large enough and that
2418                        we can invert P. */
2419                    if (invert_jump (p, new_label))
2420                      {
2421                        rtx q, r;
2422
2423                        /* Include the BARRIER after INSN and copy the
2424                           block after LOC.  */
2425                        new_label = squeeze_notes (new_label, NEXT_INSN (insn));
2426                        reorder_insns (new_label, NEXT_INSN (insn), loc);
2427
2428                        /* All those insns are now in TARGET_LOOP_NUM.  */
2429                        for (q = new_label; q != NEXT_INSN (NEXT_INSN (insn));
2430                             q = NEXT_INSN (q))
2431                          uid_loop_num[INSN_UID (q)] = target_loop_num;
2432
2433                        /* The label jumped to by INSN is no longer a loop exit.
2434                           Unless INSN does not have a label (e.g., it is a
2435                           RETURN insn), search loop_number_exit_labels to find
2436                           its label_ref, and remove it.  Also turn off
2437                           LABEL_OUTSIDE_LOOP_P bit.  */
2438                        if (JUMP_LABEL (insn))
2439                          {
2440                            int loop_num;
2441
2442                            for (q = 0,
2443                                 r = loop_number_exit_labels[this_loop_num];
2444                                 r; q = r, r = LABEL_NEXTREF (r))
2445                              if (XEXP (r, 0) == JUMP_LABEL (insn))
2446                                {
2447                                  LABEL_OUTSIDE_LOOP_P (r) = 0;
2448                                  if (q)
2449                                    LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2450                                  else
2451                                    loop_number_exit_labels[this_loop_num]
2452                                      = LABEL_NEXTREF (r);
2453                                  break;
2454                                }
2455
2456                            for (loop_num = this_loop_num;
2457                                 loop_num != -1 && loop_num != target_loop_num;
2458                                 loop_num = loop_outer_loop[loop_num])
2459                              loop_number_exit_count[loop_num]--;
2460
2461                            /* If we didn't find it, then something is wrong. */
2462                            if (! r)
2463                              abort ();
2464                          }
2465
2466                        /* P is now a jump outside the loop, so it must be put
2467                           in loop_number_exit_labels, and marked as such.
2468                           The easiest way to do this is to just call
2469                           mark_loop_jump again for P.  */
2470                        mark_loop_jump (PATTERN (p), this_loop_num);
2471
2472                        /* If INSN now jumps to the insn after it,
2473                           delete INSN.  */
2474                        if (JUMP_LABEL (insn) != 0
2475                            && (next_real_insn (JUMP_LABEL (insn))
2476                                == next_real_insn (insn)))
2477                          delete_insn (insn);
2478                      }
2479
2480                     /* Continue the loop after where the conditional
2481                        branch used to jump, since the only branch insn
2482                        in the block (if it still remains) is an inter-loop
2483                        branch and hence needs no processing.  */
2484                     insn = NEXT_INSN (cond_label);
2485
2486                     if (--LABEL_NUSES (cond_label) == 0)
2487                       delete_insn (cond_label);
2488
2489                     /* This loop will be continued with NEXT_INSN (insn).  */
2490                     insn = PREV_INSN (insn);
2491                   }
2492               }
2493           }
2494       }
2495 }
2496
2497 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
2498    loops it is contained in, mark the target loop invalid.
2499
2500    For speed, we assume that X is part of a pattern of a JUMP_INSN.  */
2501
2502 static void
2503 mark_loop_jump (x, loop_num)
2504      rtx x;
2505      int loop_num;
2506 {
2507   int dest_loop;
2508   int outer_loop;
2509   int i;
2510
2511   switch (GET_CODE (x))
2512     {
2513     case PC:
2514     case USE:
2515     case CLOBBER:
2516     case REG:
2517     case MEM:
2518     case CONST_INT:
2519     case CONST_DOUBLE:
2520     case RETURN:
2521       return;
2522
2523     case CONST:
2524       /* There could be a label reference in here.  */
2525       mark_loop_jump (XEXP (x, 0), loop_num);
2526       return;
2527
2528     case PLUS:
2529     case MINUS:
2530     case MULT:
2531       mark_loop_jump (XEXP (x, 0), loop_num);
2532       mark_loop_jump (XEXP (x, 1), loop_num);
2533       return;
2534
2535     case SIGN_EXTEND:
2536     case ZERO_EXTEND:
2537       mark_loop_jump (XEXP (x, 0), loop_num);
2538       return;
2539
2540     case LABEL_REF:
2541       dest_loop = uid_loop_num[INSN_UID (XEXP (x, 0))];
2542
2543       /* Link together all labels that branch outside the loop.  This
2544          is used by final_[bg]iv_value and the loop unrolling code.  Also
2545          mark this LABEL_REF so we know that this branch should predict
2546          false.  */
2547
2548       /* A check to make sure the label is not in an inner nested loop,
2549          since this does not count as a loop exit.  */
2550       if (dest_loop != -1)
2551         {
2552           for (outer_loop = dest_loop; outer_loop != -1;
2553                outer_loop = loop_outer_loop[outer_loop])
2554             if (outer_loop == loop_num)
2555               break;
2556         }
2557       else
2558         outer_loop = -1;
2559
2560       if (loop_num != -1 && outer_loop == -1)
2561         {
2562           LABEL_OUTSIDE_LOOP_P (x) = 1;
2563           LABEL_NEXTREF (x) = loop_number_exit_labels[loop_num];
2564           loop_number_exit_labels[loop_num] = x;
2565
2566           for (outer_loop = loop_num;
2567                outer_loop != -1 && outer_loop != dest_loop;
2568                outer_loop = loop_outer_loop[outer_loop])
2569             loop_number_exit_count[outer_loop]++;
2570         }
2571
2572       /* If this is inside a loop, but not in the current loop or one enclosed
2573          by it, it invalidates at least one loop.  */
2574
2575       if (dest_loop == -1)
2576         return;
2577
2578       /* We must invalidate every nested loop containing the target of this
2579          label, except those that also contain the jump insn.  */
2580
2581       for (; dest_loop != -1; dest_loop = loop_outer_loop[dest_loop])
2582         {
2583           /* Stop when we reach a loop that also contains the jump insn.  */
2584           for (outer_loop = loop_num; outer_loop != -1;
2585                outer_loop = loop_outer_loop[outer_loop])
2586             if (dest_loop == outer_loop)
2587               return;
2588
2589           /* If we get here, we know we need to invalidate a loop.  */
2590           if (loop_dump_stream && ! loop_invalid[dest_loop])
2591             fprintf (loop_dump_stream,
2592                      "\nLoop at %d ignored due to multiple entry points.\n",
2593                      INSN_UID (loop_number_loop_starts[dest_loop]));
2594           
2595           loop_invalid[dest_loop] = 1;
2596         }
2597       return;
2598
2599     case SET:
2600       /* If this is not setting pc, ignore.  */
2601       if (SET_DEST (x) == pc_rtx)
2602         mark_loop_jump (SET_SRC (x), loop_num);
2603       return;
2604
2605     case IF_THEN_ELSE:
2606       mark_loop_jump (XEXP (x, 1), loop_num);
2607       mark_loop_jump (XEXP (x, 2), loop_num);
2608       return;
2609
2610     case PARALLEL:
2611     case ADDR_VEC:
2612       for (i = 0; i < XVECLEN (x, 0); i++)
2613         mark_loop_jump (XVECEXP (x, 0, i), loop_num);
2614       return;
2615
2616     case ADDR_DIFF_VEC:
2617       for (i = 0; i < XVECLEN (x, 1); i++)
2618         mark_loop_jump (XVECEXP (x, 1, i), loop_num);
2619       return;
2620
2621     default:
2622       /* Treat anything else (such as a symbol_ref)
2623          as a branch out of this loop, but not into any loop.  */
2624
2625       if (loop_num != -1)
2626         {
2627           loop_number_exit_labels[loop_num] = x;
2628
2629           for (outer_loop = loop_num; outer_loop != -1;
2630                outer_loop = loop_outer_loop[outer_loop])
2631             loop_number_exit_count[outer_loop]++;
2632         }
2633       return;
2634     }
2635 }
2636 \f
2637 /* Return nonzero if there is a label in the range from
2638    insn INSN to and including the insn whose luid is END
2639    INSN must have an assigned luid (i.e., it must not have
2640    been previously created by loop.c).  */
2641
2642 static int
2643 labels_in_range_p (insn, end)
2644      rtx insn;
2645      int end;
2646 {
2647   while (insn && INSN_LUID (insn) <= end)
2648     {
2649       if (GET_CODE (insn) == CODE_LABEL)
2650         return 1;
2651       insn = NEXT_INSN (insn);
2652     }
2653
2654   return 0;
2655 }
2656
2657 /* Record that a memory reference X is being set.  */
2658
2659 static void
2660 note_addr_stored (x)
2661      rtx x;
2662 {
2663   register int i;
2664
2665   if (x == 0 || GET_CODE (x) != MEM)
2666     return;
2667
2668   /* Count number of memory writes.
2669      This affects heuristics in strength_reduce.  */
2670   num_mem_sets++;
2671
2672   /* BLKmode MEM means all memory is clobbered.  */
2673   if (GET_MODE (x) == BLKmode)
2674     unknown_address_altered = 1;
2675
2676   if (unknown_address_altered)
2677     return;
2678
2679   for (i = 0; i < loop_store_mems_idx; i++)
2680     if (rtx_equal_p (XEXP (loop_store_mems[i], 0), XEXP (x, 0))
2681         && MEM_IN_STRUCT_P (x) == MEM_IN_STRUCT_P (loop_store_mems[i]))
2682       {
2683         /* We are storing at the same address as previously noted.  Save the
2684            wider reference.  */
2685         if (GET_MODE_SIZE (GET_MODE (x))
2686             > GET_MODE_SIZE (GET_MODE (loop_store_mems[i])))
2687           loop_store_mems[i] = x;
2688         break;
2689       }
2690
2691   if (i == NUM_STORES)
2692     unknown_address_altered = 1;
2693
2694   else if (i == loop_store_mems_idx)
2695     loop_store_mems[loop_store_mems_idx++] = x;
2696 }
2697 \f
2698 /* Return nonzero if the rtx X is invariant over the current loop.
2699
2700    The value is 2 if we refer to something only conditionally invariant.
2701
2702    If `unknown_address_altered' is nonzero, no memory ref is invariant.
2703    Otherwise, a memory ref is invariant if it does not conflict with
2704    anything stored in `loop_store_mems'.  */
2705
2706 int
2707 invariant_p (x)
2708      register rtx x;
2709 {
2710   register int i;
2711   register enum rtx_code code;
2712   register char *fmt;
2713   int conditional = 0;
2714
2715   if (x == 0)
2716     return 1;
2717   code = GET_CODE (x);
2718   switch (code)
2719     {
2720     case CONST_INT:
2721     case CONST_DOUBLE:
2722     case SYMBOL_REF:
2723     case CONST:
2724       return 1;
2725
2726     case LABEL_REF:
2727       /* A LABEL_REF is normally invariant, however, if we are unrolling
2728          loops, and this label is inside the loop, then it isn't invariant.
2729          This is because each unrolled copy of the loop body will have
2730          a copy of this label.  If this was invariant, then an insn loading
2731          the address of this label into a register might get moved outside
2732          the loop, and then each loop body would end up using the same label.
2733
2734          We don't know the loop bounds here though, so just fail for all
2735          labels.  */
2736       if (flag_unroll_loops)
2737         return 0;
2738       else
2739         return 1;
2740
2741     case PC:
2742     case CC0:
2743     case UNSPEC_VOLATILE:
2744       return 0;
2745
2746     case REG:
2747       /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
2748          since the reg might be set by initialization within the loop.  */
2749       if (x == frame_pointer_rtx || x == hard_frame_pointer_rtx
2750           || x == arg_pointer_rtx)
2751         return 1;
2752       if (loop_has_call
2753           && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
2754         return 0;
2755       if (n_times_set[REGNO (x)] < 0)
2756         return 2;
2757       return n_times_set[REGNO (x)] == 0;
2758
2759     case MEM:
2760       /* Volatile memory references must be rejected.  Do this before
2761          checking for read-only items, so that volatile read-only items
2762          will be rejected also.  */
2763       if (MEM_VOLATILE_P (x))
2764         return 0;
2765
2766       /* Read-only items (such as constants in a constant pool) are
2767          invariant if their address is.  */
2768       if (RTX_UNCHANGING_P (x))
2769         break;
2770
2771       /* If we filled the table (or had a subroutine call), any location
2772          in memory could have been clobbered.  */
2773       if (unknown_address_altered)
2774         return 0;
2775
2776       /* See if there is any dependence between a store and this load.  */
2777       for (i = loop_store_mems_idx - 1; i >= 0; i--)
2778         if (true_dependence (loop_store_mems[i], x))
2779           return 0;
2780
2781       /* It's not invalidated by a store in memory
2782          but we must still verify the address is invariant.  */
2783       break;
2784
2785     case ASM_OPERANDS:
2786       /* Don't mess with insns declared volatile.  */
2787       if (MEM_VOLATILE_P (x))
2788         return 0;
2789     }
2790
2791   fmt = GET_RTX_FORMAT (code);
2792   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2793     {
2794       if (fmt[i] == 'e')
2795         {
2796           int tem = invariant_p (XEXP (x, i));
2797           if (tem == 0)
2798             return 0;
2799           if (tem == 2)
2800             conditional = 1;
2801         }
2802       else if (fmt[i] == 'E')
2803         {
2804           register int j;
2805           for (j = 0; j < XVECLEN (x, i); j++)
2806             {
2807               int tem = invariant_p (XVECEXP (x, i, j));
2808               if (tem == 0)
2809                 return 0;
2810               if (tem == 2)
2811                 conditional = 1;
2812             }
2813
2814         }
2815     }
2816
2817   return 1 + conditional;
2818 }
2819
2820 \f
2821 /* Return nonzero if all the insns in the loop that set REG
2822    are INSN and the immediately following insns,
2823    and if each of those insns sets REG in an invariant way
2824    (not counting uses of REG in them).
2825
2826    The value is 2 if some of these insns are only conditionally invariant.
2827
2828    We assume that INSN itself is the first set of REG
2829    and that its source is invariant.  */
2830
2831 static int
2832 consec_sets_invariant_p (reg, n_sets, insn)
2833      int n_sets;
2834      rtx reg, insn;
2835 {
2836   register rtx p = insn;
2837   register int regno = REGNO (reg);
2838   rtx temp;
2839   /* Number of sets we have to insist on finding after INSN.  */
2840   int count = n_sets - 1;
2841   int old = n_times_set[regno];
2842   int value = 0;
2843   int this;
2844
2845   /* If N_SETS hit the limit, we can't rely on its value.  */
2846   if (n_sets == 127)
2847     return 0;
2848
2849   n_times_set[regno] = 0;
2850
2851   while (count > 0)
2852     {
2853       register enum rtx_code code;
2854       rtx set;
2855
2856       p = NEXT_INSN (p);
2857       code = GET_CODE (p);
2858
2859       /* If library call, skip to end of of it.  */
2860       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2861         p = XEXP (temp, 0);
2862
2863       this = 0;
2864       if (code == INSN
2865           && (set = single_set (p))
2866           && GET_CODE (SET_DEST (set)) == REG
2867           && REGNO (SET_DEST (set)) == regno)
2868         {
2869           this = invariant_p (SET_SRC (set));
2870           if (this != 0)
2871             value |= this;
2872           else if (temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
2873             {
2874               /* If this is a libcall, then any invariant REG_EQUAL note is OK.
2875                  If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
2876                  notes are OK.  */
2877               this = (CONSTANT_P (XEXP (temp, 0))
2878                       || (find_reg_note (p, REG_RETVAL, NULL_RTX)
2879                           && invariant_p (XEXP (temp, 0))));
2880               if (this != 0)
2881                 value |= this;
2882             }
2883         }
2884       if (this != 0)
2885         count--;
2886       else if (code != NOTE)
2887         {
2888           n_times_set[regno] = old;
2889           return 0;
2890         }
2891     }
2892
2893   n_times_set[regno] = old;
2894   /* If invariant_p ever returned 2, we return 2.  */
2895   return 1 + (value & 2);
2896 }
2897
2898 #if 0
2899 /* I don't think this condition is sufficient to allow INSN
2900    to be moved, so we no longer test it.  */
2901
2902 /* Return 1 if all insns in the basic block of INSN and following INSN
2903    that set REG are invariant according to TABLE.  */
2904
2905 static int
2906 all_sets_invariant_p (reg, insn, table)
2907      rtx reg, insn;
2908      short *table;
2909 {
2910   register rtx p = insn;
2911   register int regno = REGNO (reg);
2912
2913   while (1)
2914     {
2915       register enum rtx_code code;
2916       p = NEXT_INSN (p);
2917       code = GET_CODE (p);
2918       if (code == CODE_LABEL || code == JUMP_INSN)
2919         return 1;
2920       if (code == INSN && GET_CODE (PATTERN (p)) == SET
2921           && GET_CODE (SET_DEST (PATTERN (p))) == REG
2922           && REGNO (SET_DEST (PATTERN (p))) == regno)
2923         {
2924           if (!invariant_p (SET_SRC (PATTERN (p)), table))
2925             return 0;
2926         }
2927     }
2928 }
2929 #endif /* 0 */
2930 \f
2931 /* Look at all uses (not sets) of registers in X.  For each, if it is
2932    the single use, set USAGE[REGNO] to INSN; if there was a previous use in
2933    a different insn, set USAGE[REGNO] to const0_rtx.  */
2934
2935 static void
2936 find_single_use_in_loop (insn, x, usage)
2937      rtx insn;
2938      rtx x;
2939      rtx *usage;
2940 {
2941   enum rtx_code code = GET_CODE (x);
2942   char *fmt = GET_RTX_FORMAT (code);
2943   int i, j;
2944
2945   if (code == REG)
2946     usage[REGNO (x)]
2947       = (usage[REGNO (x)] != 0 && usage[REGNO (x)] != insn)
2948         ? const0_rtx : insn;
2949
2950   else if (code == SET)
2951     {
2952       /* Don't count SET_DEST if it is a REG; otherwise count things
2953          in SET_DEST because if a register is partially modified, it won't
2954          show up as a potential movable so we don't care how USAGE is set 
2955          for it.  */
2956       if (GET_CODE (SET_DEST (x)) != REG)
2957         find_single_use_in_loop (insn, SET_DEST (x), usage);
2958       find_single_use_in_loop (insn, SET_SRC (x), usage);
2959     }
2960   else
2961     for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2962       {
2963         if (fmt[i] == 'e' && XEXP (x, i) != 0)
2964           find_single_use_in_loop (insn, XEXP (x, i), usage);
2965         else if (fmt[i] == 'E')
2966           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
2967             find_single_use_in_loop (insn, XVECEXP (x, i, j), usage);
2968       }
2969 }
2970 \f
2971 /* Increment N_TIMES_SET at the index of each register
2972    that is modified by an insn between FROM and TO.
2973    If the value of an element of N_TIMES_SET becomes 127 or more,
2974    stop incrementing it, to avoid overflow.
2975
2976    Store in SINGLE_USAGE[I] the single insn in which register I is
2977    used, if it is only used once.  Otherwise, it is set to 0 (for no
2978    uses) or const0_rtx for more than one use.  This parameter may be zero,
2979    in which case this processing is not done.
2980
2981    Store in *COUNT_PTR the number of actual instruction
2982    in the loop.  We use this to decide what is worth moving out.  */
2983
2984 /* last_set[n] is nonzero iff reg n has been set in the current basic block.
2985    In that case, it is the insn that last set reg n.  */
2986
2987 static void
2988 count_loop_regs_set (from, to, may_not_move, single_usage, count_ptr, nregs)
2989      register rtx from, to;
2990      char *may_not_move;
2991      rtx *single_usage;
2992      int *count_ptr;
2993      int nregs;
2994 {
2995   register rtx *last_set = (rtx *) alloca (nregs * sizeof (rtx));
2996   register rtx insn;
2997   register int count = 0;
2998   register rtx dest;
2999
3000   bzero ((char *) last_set, nregs * sizeof (rtx));
3001   for (insn = from; insn != to; insn = NEXT_INSN (insn))
3002     {
3003       if (GET_RTX_CLASS (GET_CODE (insn)) == 'i')
3004         {
3005           ++count;
3006
3007           /* If requested, record registers that have exactly one use.  */
3008           if (single_usage)
3009             {
3010               find_single_use_in_loop (insn, PATTERN (insn), single_usage);
3011
3012               /* Include uses in REG_EQUAL notes.  */
3013               if (REG_NOTES (insn))
3014                 find_single_use_in_loop (insn, REG_NOTES (insn), single_usage);
3015             }
3016
3017           if (GET_CODE (PATTERN (insn)) == CLOBBER
3018               && GET_CODE (XEXP (PATTERN (insn), 0)) == REG)
3019             /* Don't move a reg that has an explicit clobber.
3020                We might do so sometimes, but it's not worth the pain.  */
3021             may_not_move[REGNO (XEXP (PATTERN (insn), 0))] = 1;
3022
3023           if (GET_CODE (PATTERN (insn)) == SET
3024               || GET_CODE (PATTERN (insn)) == CLOBBER)
3025             {
3026               dest = SET_DEST (PATTERN (insn));
3027               while (GET_CODE (dest) == SUBREG
3028                      || GET_CODE (dest) == ZERO_EXTRACT
3029                      || GET_CODE (dest) == SIGN_EXTRACT
3030                      || GET_CODE (dest) == STRICT_LOW_PART)
3031                 dest = XEXP (dest, 0);
3032               if (GET_CODE (dest) == REG)
3033                 {
3034                   register int regno = REGNO (dest);
3035                   /* If this is the first setting of this reg
3036                      in current basic block, and it was set before,
3037                      it must be set in two basic blocks, so it cannot
3038                      be moved out of the loop.  */
3039                   if (n_times_set[regno] > 0 && last_set[regno] == 0)
3040                     may_not_move[regno] = 1;
3041                   /* If this is not first setting in current basic block,
3042                      see if reg was used in between previous one and this.
3043                      If so, neither one can be moved.  */
3044                   if (last_set[regno] != 0
3045                       && reg_used_between_p (dest, last_set[regno], insn))
3046                     may_not_move[regno] = 1;
3047                   if (n_times_set[regno] < 127)
3048                     ++n_times_set[regno];
3049                   last_set[regno] = insn;
3050                 }
3051             }
3052           else if (GET_CODE (PATTERN (insn)) == PARALLEL)
3053             {
3054               register int i;
3055               for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
3056                 {
3057                   register rtx x = XVECEXP (PATTERN (insn), 0, i);
3058                   if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3059                     /* Don't move a reg that has an explicit clobber.
3060                        It's not worth the pain to try to do it correctly.  */
3061                     may_not_move[REGNO (XEXP (x, 0))] = 1;
3062
3063                   if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3064                     {
3065                       dest = SET_DEST (x);
3066                       while (GET_CODE (dest) == SUBREG
3067                              || GET_CODE (dest) == ZERO_EXTRACT
3068                              || GET_CODE (dest) == SIGN_EXTRACT
3069                              || GET_CODE (dest) == STRICT_LOW_PART)
3070                         dest = XEXP (dest, 0);
3071                       if (GET_CODE (dest) == REG)
3072                         {
3073                           register int regno = REGNO (dest);
3074                           if (n_times_set[regno] > 0 && last_set[regno] == 0)
3075                             may_not_move[regno] = 1;
3076                           if (last_set[regno] != 0
3077                               && reg_used_between_p (dest, last_set[regno], insn))
3078                             may_not_move[regno] = 1;
3079                           if (n_times_set[regno] < 127)
3080                             ++n_times_set[regno];
3081                           last_set[regno] = insn;
3082                         }
3083                     }
3084                 }
3085             }
3086         }
3087
3088       if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
3089         bzero ((char *) last_set, nregs * sizeof (rtx));
3090     }
3091   *count_ptr = count;
3092 }
3093 \f
3094 /* Given a loop that is bounded by LOOP_START and LOOP_END
3095    and that is entered at SCAN_START,
3096    return 1 if the register set in SET contained in insn INSN is used by
3097    any insn that precedes INSN in cyclic order starting
3098    from the loop entry point.
3099
3100    We don't want to use INSN_LUID here because if we restrict INSN to those
3101    that have a valid INSN_LUID, it means we cannot move an invariant out
3102    from an inner loop past two loops.  */
3103
3104 static int
3105 loop_reg_used_before_p (set, insn, loop_start, scan_start, loop_end)
3106      rtx set, insn, loop_start, scan_start, loop_end;
3107 {
3108   rtx reg = SET_DEST (set);
3109   rtx p;
3110
3111   /* Scan forward checking for register usage.  If we hit INSN, we
3112      are done.  Otherwise, if we hit LOOP_END, wrap around to LOOP_START.  */
3113   for (p = scan_start; p != insn; p = NEXT_INSN (p))
3114     {
3115       if (GET_RTX_CLASS (GET_CODE (p)) == 'i'
3116           && reg_overlap_mentioned_p (reg, PATTERN (p)))
3117         return 1;
3118
3119       if (p == loop_end)
3120         p = loop_start;
3121     }
3122
3123   return 0;
3124 }
3125 \f
3126 /* A "basic induction variable" or biv is a pseudo reg that is set
3127    (within this loop) only by incrementing or decrementing it.  */
3128 /* A "general induction variable" or giv is a pseudo reg whose
3129    value is a linear function of a biv.  */
3130
3131 /* Bivs are recognized by `basic_induction_var';
3132    Givs by `general_induct_var'.  */
3133
3134 /* Indexed by register number, indicates whether or not register is an
3135    induction variable, and if so what type.  */
3136
3137 enum iv_mode *reg_iv_type;
3138
3139 /* Indexed by register number, contains pointer to `struct induction'
3140    if register is an induction variable.  This holds general info for
3141    all induction variables.  */
3142
3143 struct induction **reg_iv_info;
3144
3145 /* Indexed by register number, contains pointer to `struct iv_class'
3146    if register is a basic induction variable.  This holds info describing
3147    the class (a related group) of induction variables that the biv belongs
3148    to.  */
3149
3150 struct iv_class **reg_biv_class;
3151
3152 /* The head of a list which links together (via the next field)
3153    every iv class for the current loop.  */
3154
3155 struct iv_class *loop_iv_list;
3156
3157 /* Communication with routines called via `note_stores'.  */
3158
3159 static rtx note_insn;
3160
3161 /* Dummy register to have non-zero DEST_REG for DEST_ADDR type givs.  */
3162
3163 static rtx addr_placeholder;
3164
3165 /* ??? Unfinished optimizations, and possible future optimizations,
3166    for the strength reduction code.  */
3167
3168 /* ??? There is one more optimization you might be interested in doing: to
3169    allocate pseudo registers for frequently-accessed memory locations.
3170    If the same memory location is referenced each time around, it might
3171    be possible to copy it into a register before and out after.
3172    This is especially useful when the memory location is a variable which
3173    is in a stack slot because somewhere its address is taken.  If the
3174    loop doesn't contain a function call and the variable isn't volatile,
3175    it is safe to keep the value in a register for the duration of the
3176    loop. One tricky thing is that the copying of the value back from the
3177    register has to be done on all exits from the loop.  You need to check that
3178    all the exits from the loop go to the same place. */
3179
3180 /* ??? The interaction of biv elimination, and recognition of 'constant'
3181    bivs, may cause problems. */
3182
3183 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
3184    performance problems.
3185
3186    Perhaps don't eliminate things that can be combined with an addressing
3187    mode.  Find all givs that have the same biv, mult_val, and add_val;
3188    then for each giv, check to see if its only use dies in a following
3189    memory address.  If so, generate a new memory address and check to see
3190    if it is valid.   If it is valid, then store the modified memory address,
3191    otherwise, mark the giv as not done so that it will get its own iv.  */
3192
3193 /* ??? Could try to optimize branches when it is known that a biv is always
3194    positive.  */
3195
3196 /* ??? When replace a biv in a compare insn, we should replace with closest
3197    giv so that an optimized branch can still be recognized by the combiner,
3198    e.g. the VAX acb insn.  */
3199
3200 /* ??? Many of the checks involving uid_luid could be simplified if regscan
3201    was rerun in loop_optimize whenever a register was added or moved.
3202    Also, some of the optimizations could be a little less conservative.  */
3203 \f
3204 /* Perform strength reduction and induction variable elimination.  */
3205
3206 /* Pseudo registers created during this function will be beyond the last
3207    valid index in several tables including n_times_set and regno_last_uid.
3208    This does not cause a problem here, because the added registers cannot be
3209    givs outside of their loop, and hence will never be reconsidered.
3210    But scan_loop must check regnos to make sure they are in bounds.  */
3211
3212 static void
3213 strength_reduce (scan_start, end, loop_top, insn_count,
3214                  loop_start, loop_end)
3215      rtx scan_start;
3216      rtx end;
3217      rtx loop_top;
3218      int insn_count;
3219      rtx loop_start;
3220      rtx loop_end;
3221 {
3222   rtx p;
3223   rtx set;
3224   rtx inc_val;
3225   rtx mult_val;
3226   rtx dest_reg;
3227   /* This is 1 if current insn is not executed at least once for every loop
3228      iteration.  */
3229   int not_every_iteration = 0;
3230   /* This is 1 if current insn may be executed more than once for every
3231      loop iteration.  */
3232   int maybe_multiple = 0;
3233   /* Temporary list pointers for traversing loop_iv_list.  */
3234   struct iv_class *bl, **backbl;
3235   /* Ratio of extra register life span we can justify
3236      for saving an instruction.  More if loop doesn't call subroutines
3237      since in that case saving an insn makes more difference
3238      and more registers are available.  */
3239   /* ??? could set this to last value of threshold in move_movables */
3240   int threshold = (loop_has_call ? 1 : 2) * (3 + n_non_fixed_regs);
3241   /* Map of pseudo-register replacements.  */
3242   rtx *reg_map;
3243   int call_seen;
3244   rtx test;
3245   rtx end_insert_before;
3246   int loop_depth = 0;
3247
3248   reg_iv_type = (enum iv_mode *) alloca (max_reg_before_loop
3249                                          * sizeof (enum iv_mode *));
3250   bzero ((char *) reg_iv_type, max_reg_before_loop * sizeof (enum iv_mode *));
3251   reg_iv_info = (struct induction **)
3252     alloca (max_reg_before_loop * sizeof (struct induction *));
3253   bzero ((char *) reg_iv_info, (max_reg_before_loop
3254                                 * sizeof (struct induction *)));
3255   reg_biv_class = (struct iv_class **)
3256     alloca (max_reg_before_loop * sizeof (struct iv_class *));
3257   bzero ((char *) reg_biv_class, (max_reg_before_loop
3258                                   * sizeof (struct iv_class *)));
3259
3260   loop_iv_list = 0;
3261   addr_placeholder = gen_reg_rtx (Pmode);
3262
3263   /* Save insn immediately after the loop_end.  Insns inserted after loop_end
3264      must be put before this insn, so that they will appear in the right
3265      order (i.e. loop order). 
3266
3267      If loop_end is the end of the current function, then emit a 
3268      NOTE_INSN_DELETED after loop_end and set end_insert_before to the
3269      dummy note insn.  */
3270   if (NEXT_INSN (loop_end) != 0)
3271     end_insert_before = NEXT_INSN (loop_end);
3272   else
3273     end_insert_before = emit_note_after (NOTE_INSN_DELETED, loop_end);
3274
3275   /* Scan through loop to find all possible bivs.  */
3276
3277   p = scan_start;
3278   while (1)
3279     {
3280       p = NEXT_INSN (p);
3281       /* At end of a straight-in loop, we are done.
3282          At end of a loop entered at the bottom, scan the top.  */
3283       if (p == scan_start)
3284         break;
3285       if (p == end)
3286         {
3287           if (loop_top != 0)
3288             p = loop_top;
3289           else
3290             break;
3291           if (p == scan_start)
3292             break;
3293         }
3294
3295       if (GET_CODE (p) == INSN
3296           && (set = single_set (p))
3297           && GET_CODE (SET_DEST (set)) == REG)
3298         {
3299           dest_reg = SET_DEST (set);
3300           if (REGNO (dest_reg) < max_reg_before_loop
3301               && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
3302               && reg_iv_type[REGNO (dest_reg)] != NOT_BASIC_INDUCT)
3303             {
3304               if (basic_induction_var (SET_SRC (set), GET_MODE (SET_SRC (set)),
3305                                        dest_reg, p, &inc_val, &mult_val))
3306                 {
3307                   /* It is a possible basic induction variable.
3308                      Create and initialize an induction structure for it.  */
3309
3310                   struct induction *v
3311                     = (struct induction *) alloca (sizeof (struct induction));
3312
3313                   record_biv (v, p, dest_reg, inc_val, mult_val,
3314                               not_every_iteration, maybe_multiple);
3315                   reg_iv_type[REGNO (dest_reg)] = BASIC_INDUCT;
3316                 }
3317               else if (REGNO (dest_reg) < max_reg_before_loop)
3318                 reg_iv_type[REGNO (dest_reg)] = NOT_BASIC_INDUCT;
3319             }
3320         }
3321
3322       /* Past CODE_LABEL, we get to insns that may be executed multiple
3323          times.  The only way we can be sure that they can't is if every
3324          every jump insn between here and the end of the loop either
3325          returns, exits the loop, is a forward jump, or is a jump
3326          to the loop start.  */
3327
3328       if (GET_CODE (p) == CODE_LABEL)
3329         {
3330           rtx insn = p;
3331
3332           maybe_multiple = 0;
3333
3334           while (1)
3335             {
3336               insn = NEXT_INSN (insn);
3337               if (insn == scan_start)
3338                 break;
3339               if (insn == end)
3340                 {
3341                   if (loop_top != 0)
3342                     insn = loop_top;
3343                   else
3344                     break;
3345                   if (insn == scan_start)
3346                     break;
3347                 }
3348
3349               if (GET_CODE (insn) == JUMP_INSN
3350                   && GET_CODE (PATTERN (insn)) != RETURN
3351                   && (! condjump_p (insn)
3352                       || (JUMP_LABEL (insn) != 0
3353                           && JUMP_LABEL (insn) != scan_start
3354                           && (INSN_UID (JUMP_LABEL (insn)) >= max_uid_for_loop
3355                               || INSN_UID (insn) >= max_uid_for_loop
3356                               || (INSN_LUID (JUMP_LABEL (insn))
3357                                   < INSN_LUID (insn))))))
3358                 {
3359                   maybe_multiple = 1;
3360                   break;
3361                 }
3362             }
3363         }
3364
3365       /* Past a jump, we get to insns for which we can't count
3366          on whether they will be executed during each iteration.  */
3367       /* This code appears twice in strength_reduce.  There is also similar
3368          code in scan_loop.  */
3369       if (GET_CODE (p) == JUMP_INSN
3370           /* If we enter the loop in the middle, and scan around to the
3371              beginning, don't set not_every_iteration for that.
3372              This can be any kind of jump, since we want to know if insns
3373              will be executed if the loop is executed.  */
3374           && ! (JUMP_LABEL (p) == loop_top
3375                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3376                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3377         {
3378           rtx label = 0;
3379
3380           /* If this is a jump outside the loop, then it also doesn't
3381              matter.  Check to see if the target of this branch is on the
3382              loop_number_exits_labels list.  */
3383              
3384           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
3385                label;
3386                label = LABEL_NEXTREF (label))
3387             if (XEXP (label, 0) == JUMP_LABEL (p))
3388               break;
3389
3390           if (! label)
3391             not_every_iteration = 1;
3392         }
3393
3394       else if (GET_CODE (p) == NOTE)
3395         {
3396           /* At the virtual top of a converted loop, insns are again known to
3397              be executed each iteration: logically, the loop begins here
3398              even though the exit code has been duplicated.  */
3399           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
3400             not_every_iteration = 0;
3401           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3402             loop_depth++;
3403           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3404             loop_depth--;
3405         }
3406
3407       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3408          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3409          or not an insn is known to be executed each iteration of the
3410          loop, whether or not any iterations are known to occur.
3411
3412          Therefore, if we have just passed a label and have no more labels
3413          between here and the test insn of the loop, we know these insns
3414          will be executed each iteration.  */
3415
3416       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
3417           && no_labels_between_p (p, loop_end))
3418         not_every_iteration = 0;
3419     }
3420
3421   /* Scan loop_iv_list to remove all regs that proved not to be bivs.
3422      Make a sanity check against n_times_set.  */
3423   for (backbl = &loop_iv_list, bl = *backbl; bl; bl = bl->next)
3424     {
3425       if (reg_iv_type[bl->regno] != BASIC_INDUCT
3426           /* Above happens if register modified by subreg, etc.  */
3427           /* Make sure it is not recognized as a basic induction var: */
3428           || n_times_set[bl->regno] != bl->biv_count
3429           /* If never incremented, it is invariant that we decided not to
3430              move.  So leave it alone.  */
3431           || ! bl->incremented)
3432         {
3433           if (loop_dump_stream)
3434             fprintf (loop_dump_stream, "Reg %d: biv discarded, %s\n",
3435                      bl->regno,
3436                      (reg_iv_type[bl->regno] != BASIC_INDUCT
3437                       ? "not induction variable"
3438                       : (! bl->incremented ? "never incremented"
3439                          : "count error")));
3440           
3441           reg_iv_type[bl->regno] = NOT_BASIC_INDUCT;
3442           *backbl = bl->next;
3443         }
3444       else
3445         {
3446           backbl = &bl->next;
3447
3448           if (loop_dump_stream)
3449             fprintf (loop_dump_stream, "Reg %d: biv verified\n", bl->regno);
3450         }
3451     }
3452
3453   /* Exit if there are no bivs.  */
3454   if (! loop_iv_list)
3455     {
3456       /* Can still unroll the loop anyways, but indicate that there is no
3457          strength reduction info available.  */
3458       if (flag_unroll_loops)
3459         unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 0);
3460
3461       return;
3462     }
3463
3464   /* Find initial value for each biv by searching backwards from loop_start,
3465      halting at first label.  Also record any test condition.  */
3466
3467   call_seen = 0;
3468   for (p = loop_start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
3469     {
3470       note_insn = p;
3471
3472       if (GET_CODE (p) == CALL_INSN)
3473         call_seen = 1;
3474
3475       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3476           || GET_CODE (p) == CALL_INSN)
3477         note_stores (PATTERN (p), record_initial);
3478
3479       /* Record any test of a biv that branches around the loop if no store
3480          between it and the start of loop.  We only care about tests with
3481          constants and registers and only certain of those.  */
3482       if (GET_CODE (p) == JUMP_INSN
3483           && JUMP_LABEL (p) != 0
3484           && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop_end)
3485           && (test = get_condition_for_loop (p)) != 0
3486           && GET_CODE (XEXP (test, 0)) == REG
3487           && REGNO (XEXP (test, 0)) < max_reg_before_loop
3488           && (bl = reg_biv_class[REGNO (XEXP (test, 0))]) != 0
3489           && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop_start)
3490           && bl->init_insn == 0)
3491         {
3492           /* If an NE test, we have an initial value!  */
3493           if (GET_CODE (test) == NE)
3494             {
3495               bl->init_insn = p;
3496               bl->init_set = gen_rtx (SET, VOIDmode,
3497                                       XEXP (test, 0), XEXP (test, 1));
3498             }
3499           else
3500             bl->initial_test = test;
3501         }
3502     }
3503
3504   /* Look at the each biv and see if we can say anything better about its
3505      initial value from any initializing insns set up above.  (This is done
3506      in two passes to avoid missing SETs in a PARALLEL.)  */
3507   for (bl = loop_iv_list; bl; bl = bl->next)
3508     {
3509       rtx src;
3510
3511       if (! bl->init_insn)
3512         continue;
3513
3514       src = SET_SRC (bl->init_set);
3515
3516       if (loop_dump_stream)
3517         fprintf (loop_dump_stream,
3518                  "Biv %d initialized at insn %d: initial value ",
3519                  bl->regno, INSN_UID (bl->init_insn));
3520
3521       if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
3522            || GET_MODE (src) == VOIDmode)
3523           && valid_initial_value_p (src, bl->init_insn, call_seen, loop_start))
3524         {
3525           bl->initial_value = src;
3526
3527           if (loop_dump_stream)
3528             {
3529               if (GET_CODE (src) == CONST_INT)
3530                 fprintf (loop_dump_stream, "%d\n", INTVAL (src));
3531               else
3532                 {
3533                   print_rtl (loop_dump_stream, src);
3534                   fprintf (loop_dump_stream, "\n");
3535                 }
3536             }
3537         }
3538       else
3539         {
3540           /* Biv initial value is not simple move,
3541              so let it keep initial value of "itself".  */
3542
3543           if (loop_dump_stream)
3544             fprintf (loop_dump_stream, "is complex\n");
3545         }
3546     }
3547
3548   /* Search the loop for general induction variables.  */
3549
3550   /* A register is a giv if: it is only set once, it is a function of a
3551      biv and a constant (or invariant), and it is not a biv.  */
3552
3553   not_every_iteration = 0;
3554   loop_depth = 0;
3555   p = scan_start;
3556   while (1)
3557     {
3558       p = NEXT_INSN (p);
3559       /* At end of a straight-in loop, we are done.
3560          At end of a loop entered at the bottom, scan the top.  */
3561       if (p == scan_start)
3562         break;
3563       if (p == end)
3564         {
3565           if (loop_top != 0)
3566             p = loop_top;
3567           else
3568             break;
3569           if (p == scan_start)
3570             break;
3571         }
3572
3573       /* Look for a general induction variable in a register.  */
3574       if (GET_CODE (p) == INSN
3575           && (set = single_set (p))
3576           && GET_CODE (SET_DEST (set)) == REG
3577           && ! may_not_optimize[REGNO (SET_DEST (set))])
3578         {
3579           rtx src_reg;
3580           rtx add_val;
3581           rtx mult_val;
3582           int benefit;
3583           rtx regnote = 0;
3584
3585           dest_reg = SET_DEST (set);
3586           if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
3587             continue;
3588
3589           if (/* SET_SRC is a giv.  */
3590               ((benefit = general_induction_var (SET_SRC (set),
3591                                                  &src_reg, &add_val,
3592                                                  &mult_val))
3593                /* Equivalent expression is a giv. */
3594                || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
3595                    && (benefit = general_induction_var (XEXP (regnote, 0),
3596                                                         &src_reg,
3597                                                         &add_val, &mult_val))))
3598               /* Don't try to handle any regs made by loop optimization.
3599                  We have nothing on them in regno_first_uid, etc.  */
3600               && REGNO (dest_reg) < max_reg_before_loop
3601               /* Don't recognize a BASIC_INDUCT_VAR here.  */
3602               && dest_reg != src_reg
3603               /* This must be the only place where the register is set.  */
3604               && (n_times_set[REGNO (dest_reg)] == 1
3605                   /* or all sets must be consecutive and make a giv. */
3606                   || (benefit = consec_sets_giv (benefit, p,
3607                                                  src_reg, dest_reg,
3608                                                  &add_val, &mult_val))))
3609             {
3610               int count;
3611               struct induction *v
3612                 = (struct induction *) alloca (sizeof (struct induction));
3613               rtx temp;
3614
3615               /* If this is a library call, increase benefit.  */
3616               if (find_reg_note (p, REG_RETVAL, NULL_RTX))
3617                 benefit += libcall_benefit (p);
3618
3619               /* Skip the consecutive insns, if there are any.  */
3620               for (count = n_times_set[REGNO (dest_reg)] - 1;
3621                    count > 0; count--)
3622                 {
3623                   /* If first insn of libcall sequence, skip to end.
3624                      Do this at start of loop, since INSN is guaranteed to
3625                      be an insn here.  */
3626                   if (GET_CODE (p) != NOTE
3627                       && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3628                     p = XEXP (temp, 0);
3629
3630                   do p = NEXT_INSN (p);
3631                   while (GET_CODE (p) == NOTE);
3632                 }
3633
3634               record_giv (v, p, src_reg, dest_reg, mult_val, add_val, benefit,
3635                           DEST_REG, not_every_iteration, NULL_PTR, loop_start,
3636                           loop_end);
3637
3638             }
3639         }
3640
3641 #ifndef DONT_REDUCE_ADDR
3642       /* Look for givs which are memory addresses.  */
3643       /* This resulted in worse code on a VAX 8600.  I wonder if it
3644          still does.  */
3645       if (GET_CODE (p) == INSN)
3646         find_mem_givs (PATTERN (p), p, not_every_iteration, loop_start,
3647                        loop_end);
3648 #endif
3649
3650       /* Update the status of whether giv can derive other givs.  This can
3651          change when we pass a label or an insn that updates a biv.  */
3652       if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
3653         || GET_CODE (p) == CODE_LABEL)
3654         update_giv_derive (p);
3655
3656       /* Past a jump, we get to insns for which we can't count
3657          on whether they will be executed during each iteration.  */
3658       /* This code appears twice in strength_reduce.  There is also similar
3659          code in scan_loop.  */
3660       if (GET_CODE (p) == JUMP_INSN
3661           /* If we enter the loop in the middle, and scan around to the
3662              beginning, don't set not_every_iteration for that.
3663              This can be any kind of jump, since we want to know if insns
3664              will be executed if the loop is executed.  */
3665           && ! (JUMP_LABEL (p) == loop_top
3666                 && ((NEXT_INSN (NEXT_INSN (p)) == loop_end && simplejump_p (p))
3667                     || (NEXT_INSN (p) == loop_end && condjump_p (p)))))
3668         {
3669           rtx label = 0;
3670
3671           /* If this is a jump outside the loop, then it also doesn't
3672              matter.  Check to see if the target of this branch is on the
3673              loop_number_exits_labels list.  */
3674              
3675           for (label = loop_number_exit_labels[uid_loop_num[INSN_UID (loop_start)]];
3676                label;
3677                label = LABEL_NEXTREF (label))
3678             if (XEXP (label, 0) == JUMP_LABEL (p))
3679               break;
3680
3681           if (! label)
3682             not_every_iteration = 1;
3683         }
3684
3685       else if (GET_CODE (p) == NOTE)
3686         {
3687           /* At the virtual top of a converted loop, insns are again known to
3688              be executed each iteration: logically, the loop begins here
3689              even though the exit code has been duplicated.  */
3690           if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
3691             not_every_iteration = 0;
3692           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
3693             loop_depth++;
3694           else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
3695             loop_depth--;
3696         }
3697
3698       /* Unlike in the code motion pass where MAYBE_NEVER indicates that
3699          an insn may never be executed, NOT_EVERY_ITERATION indicates whether
3700          or not an insn is known to be executed each iteration of the
3701          loop, whether or not any iterations are known to occur.
3702
3703          Therefore, if we have just passed a label and have no more labels
3704          between here and the test insn of the loop, we know these insns
3705          will be executed each iteration.  */
3706
3707       if (not_every_iteration && GET_CODE (p) == CODE_LABEL
3708           && no_labels_between_p (p, loop_end))
3709         not_every_iteration = 0;
3710     }
3711
3712   /* Try to calculate and save the number of loop iterations.  This is
3713      set to zero if the actual number can not be calculated.  This must
3714      be called after all giv's have been identified, since otherwise it may
3715      fail if the iteration variable is a giv.  */
3716
3717   loop_n_iterations = loop_iterations (loop_start, loop_end);
3718
3719   /* Now for each giv for which we still don't know whether or not it is
3720      replaceable, check to see if it is replaceable because its final value
3721      can be calculated.  This must be done after loop_iterations is called,
3722      so that final_giv_value will work correctly.  */
3723
3724   for (bl = loop_iv_list; bl; bl = bl->next)
3725     {
3726       struct induction *v;
3727
3728       for (v = bl->giv; v; v = v->next_iv)
3729         if (! v->replaceable && ! v->not_replaceable)
3730           check_final_value (v, loop_start, loop_end);
3731     }
3732
3733   /* Try to prove that the loop counter variable (if any) is always
3734      nonnegative; if so, record that fact with a REG_NONNEG note
3735      so that "decrement and branch until zero" insn can be used.  */
3736   check_dbra_loop (loop_end, insn_count, loop_start);
3737
3738   /* Create reg_map to hold substitutions for replaceable giv regs.  */
3739   reg_map = (rtx *) alloca (max_reg_before_loop * sizeof (rtx));
3740   bzero ((char *) reg_map, max_reg_before_loop * sizeof (rtx));
3741
3742   /* Examine each iv class for feasibility of strength reduction/induction
3743      variable elimination.  */
3744
3745   for (bl = loop_iv_list; bl; bl = bl->next)
3746     {
3747       struct induction *v;
3748       int benefit;
3749       int all_reduced;
3750       rtx final_value = 0;
3751
3752       /* Test whether it will be possible to eliminate this biv
3753          provided all givs are reduced.  This is possible if either
3754          the reg is not used outside the loop, or we can compute
3755          what its final value will be.
3756
3757          For architectures with a decrement_and_branch_until_zero insn,
3758          don't do this if we put a REG_NONNEG note on the endtest for
3759          this biv.  */
3760
3761       /* Compare against bl->init_insn rather than loop_start.
3762          We aren't concerned with any uses of the biv between
3763          init_insn and loop_start since these won't be affected
3764          by the value of the biv elsewhere in the function, so
3765          long as init_insn doesn't use the biv itself.
3766          March 14, 1989 -- self@bayes.arc.nasa.gov */
3767
3768       if ((uid_luid[regno_last_uid[bl->regno]] < INSN_LUID (loop_end)
3769            && bl->init_insn
3770            && INSN_UID (bl->init_insn) < max_uid_for_loop
3771            && uid_luid[regno_first_uid[bl->regno]] >= INSN_LUID (bl->init_insn)
3772 #ifdef HAVE_decrement_and_branch_until_zero
3773            && ! bl->nonneg
3774 #endif
3775            && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
3776           || ((final_value = final_biv_value (bl, loop_start, loop_end))
3777 #ifdef HAVE_decrement_and_branch_until_zero
3778               && ! bl->nonneg
3779 #endif
3780               ))
3781         bl->eliminable = maybe_eliminate_biv (bl, loop_start, end, 0,
3782                                               threshold, insn_count);
3783       else
3784         {
3785           if (loop_dump_stream)
3786             {
3787               fprintf (loop_dump_stream,
3788                        "Cannot eliminate biv %d.\n",
3789                        bl->regno);
3790               fprintf (loop_dump_stream,
3791                        "First use: insn %d, last use: insn %d.\n",
3792                        regno_first_uid[bl->regno],
3793                        regno_last_uid[bl->regno]);
3794             }
3795         }
3796
3797       /* Combine all giv's for this iv_class.  */
3798       combine_givs (bl);
3799
3800       /* This will be true at the end, if all givs which depend on this
3801          biv have been strength reduced.
3802          We can't (currently) eliminate the biv unless this is so.  */
3803       all_reduced = 1;
3804
3805       /* Check each giv in this class to see if we will benefit by reducing
3806          it.  Skip giv's combined with others.  */
3807       for (v = bl->giv; v; v = v->next_iv)
3808         {
3809           struct induction *tv;
3810
3811           if (v->ignore || v->same)
3812             continue;
3813
3814           benefit = v->benefit;
3815
3816           /* Reduce benefit if not replaceable, since we will insert
3817              a move-insn to replace the insn that calculates this giv.
3818              Don't do this unless the giv is a user variable, since it
3819              will often be marked non-replaceable because of the duplication
3820              of the exit code outside the loop.  In such a case, the copies
3821              we insert are dead and will be deleted.  So they don't have
3822              a cost.  Similar situations exist.  */
3823           /* ??? The new final_[bg]iv_value code does a much better job
3824              of finding replaceable giv's, and hence this code may no longer
3825              be necessary.  */
3826           if (! v->replaceable && ! bl->eliminable
3827               && REG_USERVAR_P (v->dest_reg))
3828             benefit -= copy_cost;
3829
3830           /* Decrease the benefit to count the add-insns that we will
3831              insert to increment the reduced reg for the giv.  */
3832           benefit -= add_cost * bl->biv_count;
3833
3834           /* Decide whether to strength-reduce this giv or to leave the code
3835              unchanged (recompute it from the biv each time it is used).
3836              This decision can be made independently for each giv.  */
3837
3838           /* ??? Perhaps attempt to guess whether autoincrement will handle
3839              some of the new add insns; if so, can increase BENEFIT
3840              (undo the subtraction of add_cost that was done above).  */
3841
3842           /* If an insn is not to be strength reduced, then set its ignore
3843              flag, and clear all_reduced.  */
3844
3845           /* A giv that depends on a reversed biv must be reduced if it is
3846              used after the loop exit, otherwise, it would have the wrong
3847              value after the loop exit.  To make it simple, just reduce all
3848              of such giv's whether or not we know they are used after the loop
3849              exit.  */
3850
3851           if (v->lifetime * threshold * benefit < insn_count
3852               && ! bl->reversed)
3853             {
3854               if (loop_dump_stream)
3855                 fprintf (loop_dump_stream,
3856                          "giv of insn %d not worth while, %d vs %d.\n",
3857                          INSN_UID (v->insn),
3858                          v->lifetime * threshold * benefit, insn_count);
3859               v->ignore = 1;
3860               all_reduced = 0;
3861             }
3862           else
3863             {
3864               /* Check that we can increment the reduced giv without a
3865                  multiply insn.  If not, reject it.  */
3866
3867               for (tv = bl->biv; tv; tv = tv->next_iv)
3868                 if (tv->mult_val == const1_rtx
3869                     && ! product_cheap_p (tv->add_val, v->mult_val))
3870                   {
3871                     if (loop_dump_stream)
3872                       fprintf (loop_dump_stream,
3873                                "giv of insn %d: would need a multiply.\n",
3874                                INSN_UID (v->insn));
3875                     v->ignore = 1;
3876                     all_reduced = 0;
3877                     break;
3878                   }
3879             }
3880         }
3881
3882       /* Reduce each giv that we decided to reduce.  */
3883
3884       for (v = bl->giv; v; v = v->next_iv)
3885         {
3886           struct induction *tv;
3887           if (! v->ignore && v->same == 0)
3888             {
3889               int auto_inc_opt = 0;
3890
3891               v->new_reg = gen_reg_rtx (v->mode);
3892
3893 #ifdef AUTO_INC_DEC
3894               /* If the target has auto-increment addressing modes, and
3895                  this is an address giv, then try to put the increment
3896                  immediately after its use, so that flow can create an
3897                  auto-increment addressing mode.  */
3898               if (v->giv_type == DEST_ADDR && bl->biv_count == 1
3899                   && bl->biv->always_executed
3900                   && ! bl->biv->maybe_multiple
3901                   && v->always_executed && ! v->maybe_multiple)
3902                 {
3903                   /* If other giv's have been combined with this one, then
3904                      this will work only if all uses of the other giv's occur
3905                      before this giv's insn.  This is difficult to check.
3906
3907                      We simplify this by looking for the common case where
3908                      there is one DEST_REG giv, and this giv's insn is the
3909                      last use of the dest_reg of that DEST_REG giv.  If the
3910                      the increment occurs after the address giv, then we can
3911                      perform the optimization.  (Otherwise, the increment
3912                      would have to go before other_giv, and we would not be
3913                      able to combine it with the address giv to get an
3914                      auto-inc address.)  */
3915                   if (v->combined_with)
3916                     {
3917                       struct induction *other_giv = 0;
3918
3919                       for (tv = bl->giv; tv; tv = tv->next_iv)
3920                         if (tv->same == v)
3921                           {
3922                             if (other_giv)
3923                               break;
3924                             else
3925                               other_giv = tv;
3926                           }
3927                       if (! tv && other_giv
3928                           && (regno_last_uid[REGNO (other_giv->dest_reg)]
3929                               == INSN_UID (v->insn))
3930                           && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
3931                         auto_inc_opt = 1;
3932                     }
3933                   /* Check for case where increment is before the the address
3934                      giv.  */
3935                   else if (INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn))
3936                     auto_inc_opt = -1;
3937                   else
3938                     auto_inc_opt = 1;
3939
3940                   if (auto_inc_opt)
3941                     v->auto_inc_opt = 1;
3942                 }
3943 #endif
3944
3945               /* For each place where the biv is incremented, add an insn
3946                  to increment the new, reduced reg for the giv.  */
3947               for (tv = bl->biv; tv; tv = tv->next_iv)
3948                 {
3949                   rtx insert_before;
3950
3951                   if (! auto_inc_opt)
3952                     insert_before = tv->insn;
3953                   else if (auto_inc_opt == 1)
3954                     insert_before = NEXT_INSN (v->insn);
3955                   else
3956                     insert_before = v->insn;
3957
3958                   if (tv->mult_val == const1_rtx)
3959                     emit_iv_add_mult (tv->add_val, v->mult_val,
3960                                       v->new_reg, v->new_reg, insert_before);
3961                   else /* tv->mult_val == const0_rtx */
3962                     /* A multiply is acceptable here
3963                        since this is presumed to be seldom executed.  */
3964                     emit_iv_add_mult (tv->add_val, v->mult_val,
3965                                       v->add_val, v->new_reg, insert_before);
3966                 }
3967
3968               /* Add code at loop start to initialize giv's reduced reg.  */
3969
3970               emit_iv_add_mult (bl->initial_value, v->mult_val,
3971                                 v->add_val, v->new_reg, loop_start);
3972             }
3973         }
3974
3975       /* Rescan all givs.  If a giv is the same as a giv not reduced, mark it
3976          as not reduced.
3977          
3978          For each giv register that can be reduced now: if replaceable,
3979          substitute reduced reg wherever the old giv occurs;
3980          else add new move insn "giv_reg = reduced_reg".
3981
3982          Also check for givs whose first use is their definition and whose
3983          last use is the definition of another giv.  If so, it is likely
3984          dead and should not be used to eliminate a biv.  */
3985       for (v = bl->giv; v; v = v->next_iv)
3986         {
3987           if (v->same && v->same->ignore)
3988             v->ignore = 1;
3989
3990           if (v->ignore)
3991             continue;
3992
3993           if (v->giv_type == DEST_REG
3994               && regno_first_uid[REGNO (v->dest_reg)] == INSN_UID (v->insn))
3995             {
3996               struct induction *v1;
3997
3998               for (v1 = bl->giv; v1; v1 = v1->next_iv)
3999                 if (regno_last_uid[REGNO (v->dest_reg)] == INSN_UID (v1->insn))
4000                   v->maybe_dead = 1;
4001             }
4002
4003           /* Update expression if this was combined, in case other giv was
4004              replaced.  */
4005           if (v->same)
4006             v->new_reg = replace_rtx (v->new_reg,
4007                                       v->same->dest_reg, v->same->new_reg);
4008
4009           if (v->giv_type == DEST_ADDR)
4010             /* Store reduced reg as the address in the memref where we found
4011                this giv.  */
4012             validate_change (v->insn, v->location, v->new_reg, 0);
4013           else if (v->replaceable)
4014             {
4015               reg_map[REGNO (v->dest_reg)] = v->new_reg;
4016
4017 #if 0
4018               /* I can no longer duplicate the original problem.  Perhaps
4019                  this is unnecessary now?  */
4020
4021               /* Replaceable; it isn't strictly necessary to delete the old
4022                  insn and emit a new one, because v->dest_reg is now dead.
4023
4024                  However, especially when unrolling loops, the special
4025                  handling for (set REG0 REG1) in the second cse pass may
4026                  make v->dest_reg live again.  To avoid this problem, emit
4027                  an insn to set the original giv reg from the reduced giv.
4028                  We can not delete the original insn, since it may be part
4029                  of a LIBCALL, and the code in flow that eliminates dead
4030                  libcalls will fail if it is deleted.  */
4031               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4032                                v->insn);
4033 #endif
4034             }
4035           else
4036             {
4037               /* Not replaceable; emit an insn to set the original giv reg from
4038                  the reduced giv, same as above.  */
4039               emit_insn_after (gen_move_insn (v->dest_reg, v->new_reg),
4040                                v->insn);
4041             }
4042
4043           /* When a loop is reversed, givs which depend on the reversed
4044              biv, and which are live outside the loop, must be set to their
4045              correct final value.  This insn is only needed if the giv is
4046              not replaceable.  The correct final value is the same as the
4047              value that the giv starts the reversed loop with.  */
4048           if (bl->reversed && ! v->replaceable)
4049             emit_iv_add_mult (bl->initial_value, v->mult_val,
4050                               v->add_val, v->dest_reg, end_insert_before);
4051           else if (v->final_value)
4052             {
4053               rtx insert_before;
4054
4055               /* If the loop has multiple exits, emit the insn before the
4056                  loop to ensure that it will always be executed no matter
4057                  how the loop exits.  Otherwise, emit the insn after the loop,
4058                  since this is slightly more efficient.  */
4059               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
4060                 insert_before = loop_start;
4061               else
4062                 insert_before = end_insert_before;
4063               emit_insn_before (gen_move_insn (v->dest_reg, v->final_value),
4064                                 insert_before);
4065
4066 #if 0
4067               /* If the insn to set the final value of the giv was emitted
4068                  before the loop, then we must delete the insn inside the loop
4069                  that sets it.  If this is a LIBCALL, then we must delete
4070                  every insn in the libcall.  Note, however, that
4071                  final_giv_value will only succeed when there are multiple
4072                  exits if the giv is dead at each exit, hence it does not
4073                  matter that the original insn remains because it is dead
4074                  anyways.  */
4075               /* Delete the insn inside the loop that sets the giv since
4076                  the giv is now set before (or after) the loop.  */
4077               delete_insn (v->insn);
4078 #endif
4079             }
4080
4081           if (loop_dump_stream)
4082             {
4083               fprintf (loop_dump_stream, "giv at %d reduced to ",
4084                        INSN_UID (v->insn));
4085               print_rtl (loop_dump_stream, v->new_reg);
4086               fprintf (loop_dump_stream, "\n");
4087             }
4088         }
4089
4090       /* All the givs based on the biv bl have been reduced if they
4091          merit it.  */
4092
4093       /* For each giv not marked as maybe dead that has been combined with a
4094          second giv, clear any "maybe dead" mark on that second giv.
4095          v->new_reg will either be or refer to the register of the giv it
4096          combined with.
4097
4098          Doing this clearing avoids problems in biv elimination where a
4099          giv's new_reg is a complex value that can't be put in the insn but
4100          the giv combined with (with a reg as new_reg) is marked maybe_dead.
4101          Since the register will be used in either case, we'd prefer it be
4102          used from the simpler giv.  */
4103
4104       for (v = bl->giv; v; v = v->next_iv)
4105         if (! v->maybe_dead && v->same)
4106           v->same->maybe_dead = 0;
4107
4108       /* Try to eliminate the biv, if it is a candidate.
4109          This won't work if ! all_reduced,
4110          since the givs we planned to use might not have been reduced.
4111
4112          We have to be careful that we didn't initially think we could eliminate
4113          this biv because of a giv that we now think may be dead and shouldn't
4114          be used as a biv replacement.  
4115
4116          Also, there is the possibility that we may have a giv that looks
4117          like it can be used to eliminate a biv, but the resulting insn
4118          isn't valid.  This can happen, for example, on the 88k, where a 
4119          JUMP_INSN can compare a register only with zero.  Attempts to
4120          replace it with a compare with a constant will fail.
4121
4122          Note that in cases where this call fails, we may have replaced some
4123          of the occurrences of the biv with a giv, but no harm was done in
4124          doing so in the rare cases where it can occur.  */
4125
4126       if (all_reduced == 1 && bl->eliminable
4127           && maybe_eliminate_biv (bl, loop_start, end, 1,
4128                                   threshold, insn_count))
4129
4130         {
4131           /* ?? If we created a new test to bypass the loop entirely,
4132              or otherwise drop straight in, based on this test, then
4133              we might want to rewrite it also.  This way some later
4134              pass has more hope of removing the initialization of this
4135              biv entirely. */
4136
4137           /* If final_value != 0, then the biv may be used after loop end
4138              and we must emit an insn to set it just in case.
4139
4140              Reversed bivs already have an insn after the loop setting their
4141              value, so we don't need another one.  We can't calculate the
4142              proper final value for such a biv here anyways. */
4143           if (final_value != 0 && ! bl->reversed)
4144             {
4145               rtx insert_before;
4146
4147               /* If the loop has multiple exits, emit the insn before the
4148                  loop to ensure that it will always be executed no matter
4149                  how the loop exits.  Otherwise, emit the insn after the
4150                  loop, since this is slightly more efficient.  */
4151               if (loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
4152                 insert_before = loop_start;
4153               else
4154                 insert_before = end_insert_before;
4155
4156               emit_insn_before (gen_move_insn (bl->biv->dest_reg, final_value),
4157                                 end_insert_before);
4158             }
4159
4160 #if 0
4161           /* Delete all of the instructions inside the loop which set
4162              the biv, as they are all dead.  If is safe to delete them,
4163              because an insn setting a biv will never be part of a libcall.  */
4164           /* However, deleting them will invalidate the regno_last_uid info,
4165              so keeping them around is more convenient.  Final_biv_value
4166              will only succeed when there are multiple exits if the biv
4167              is dead at each exit, hence it does not matter that the original
4168              insn remains, because it is dead anyways.  */
4169           for (v = bl->biv; v; v = v->next_iv)
4170             delete_insn (v->insn);
4171 #endif
4172
4173           if (loop_dump_stream)
4174             fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
4175                      bl->regno);
4176         }
4177     }
4178
4179   /* Go through all the instructions in the loop, making all the
4180      register substitutions scheduled in REG_MAP.  */
4181
4182   for (p = loop_start; p != end; p = NEXT_INSN (p))
4183     if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4184         || GET_CODE (p) == CALL_INSN)
4185       {
4186         replace_regs (PATTERN (p), reg_map, max_reg_before_loop, 0);
4187         replace_regs (REG_NOTES (p), reg_map, max_reg_before_loop, 0);
4188         INSN_CODE (p) = -1;
4189       }
4190
4191   /* Unroll loops from within strength reduction so that we can use the
4192      induction variable information that strength_reduce has already
4193      collected.  */
4194   
4195   if (flag_unroll_loops)
4196     unroll_loop (loop_end, insn_count, loop_start, end_insert_before, 1);
4197
4198   if (loop_dump_stream)
4199     fprintf (loop_dump_stream, "\n");
4200 }
4201 \f
4202 /* Return 1 if X is a valid source for an initial value (or as value being
4203    compared against in an initial test).
4204
4205    X must be either a register or constant and must not be clobbered between
4206    the current insn and the start of the loop.
4207
4208    INSN is the insn containing X.  */
4209
4210 static int
4211 valid_initial_value_p (x, insn, call_seen, loop_start)
4212      rtx x;
4213      rtx insn;
4214      int call_seen;
4215      rtx loop_start;
4216 {
4217   if (CONSTANT_P (x))
4218     return 1;
4219
4220   /* Only consider pseudos we know about initialized in insns whose luids
4221      we know.  */
4222   if (GET_CODE (x) != REG
4223       || REGNO (x) >= max_reg_before_loop)
4224     return 0;
4225
4226   /* Don't use call-clobbered registers across a call which clobbers it.  On
4227      some machines, don't use any hard registers at all.  */
4228   if (REGNO (x) < FIRST_PSEUDO_REGISTER
4229 #ifndef SMALL_REGISTER_CLASSES
4230       && call_used_regs[REGNO (x)] && call_seen
4231 #endif
4232       )
4233     return 0;
4234
4235   /* Don't use registers that have been clobbered before the start of the
4236      loop.  */
4237   if (reg_set_between_p (x, insn, loop_start))
4238     return 0;
4239
4240   return 1;
4241 }
4242 \f
4243 /* Scan X for memory refs and check each memory address
4244    as a possible giv.  INSN is the insn whose pattern X comes from.
4245    NOT_EVERY_ITERATION is 1 if the insn might not be executed during
4246    every loop iteration.  */
4247
4248 static void
4249 find_mem_givs (x, insn, not_every_iteration, loop_start, loop_end)
4250      rtx x;
4251      rtx insn;
4252      int not_every_iteration;
4253      rtx loop_start, loop_end;
4254 {
4255   register int i, j;
4256   register enum rtx_code code;
4257   register char *fmt;
4258
4259   if (x == 0)
4260     return;
4261
4262   code = GET_CODE (x);
4263   switch (code)
4264     {
4265     case REG:
4266     case CONST_INT:
4267     case CONST:
4268     case CONST_DOUBLE:
4269     case SYMBOL_REF:
4270     case LABEL_REF:
4271     case PC:
4272     case CC0:
4273     case ADDR_VEC:
4274     case ADDR_DIFF_VEC:
4275     case USE:
4276     case CLOBBER:
4277       return;
4278
4279     case MEM:
4280       {
4281         rtx src_reg;
4282         rtx add_val;
4283         rtx mult_val;
4284         int benefit;
4285
4286         benefit = general_induction_var (XEXP (x, 0),
4287                                          &src_reg, &add_val, &mult_val);
4288
4289         /* Don't make a DEST_ADDR giv with mult_val == 1 && add_val == 0.
4290            Such a giv isn't useful.  */
4291         if (benefit > 0 && (mult_val != const1_rtx || add_val != const0_rtx))
4292           {
4293             /* Found one; record it.  */
4294             struct induction *v
4295               = (struct induction *) oballoc (sizeof (struct induction));
4296
4297             record_giv (v, insn, src_reg, addr_placeholder, mult_val,
4298                         add_val, benefit, DEST_ADDR, not_every_iteration,
4299                         &XEXP (x, 0), loop_start, loop_end);
4300
4301             v->mem_mode = GET_MODE (x);
4302           }
4303         return;
4304       }
4305     }
4306
4307   /* Recursively scan the subexpressions for other mem refs.  */
4308
4309   fmt = GET_RTX_FORMAT (code);
4310   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
4311     if (fmt[i] == 'e')
4312       find_mem_givs (XEXP (x, i), insn, not_every_iteration, loop_start,
4313                      loop_end);
4314     else if (fmt[i] == 'E')
4315       for (j = 0; j < XVECLEN (x, i); j++)
4316         find_mem_givs (XVECEXP (x, i, j), insn, not_every_iteration,
4317                        loop_start, loop_end);
4318 }
4319 \f
4320 /* Fill in the data about one biv update.
4321    V is the `struct induction' in which we record the biv.  (It is
4322    allocated by the caller, with alloca.)
4323    INSN is the insn that sets it.
4324    DEST_REG is the biv's reg.
4325
4326    MULT_VAL is const1_rtx if the biv is being incremented here, in which case
4327    INC_VAL is the increment.  Otherwise, MULT_VAL is const0_rtx and the biv is
4328    being set to INC_VAL.
4329
4330    NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
4331    executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
4332    can be executed more than once per iteration.  If MAYBE_MULTIPLE
4333    and NOT_EVERY_ITERATION are both zero, we know that the biv update is
4334    executed exactly once per iteration.  */
4335
4336 static void
4337 record_biv (v, insn, dest_reg, inc_val, mult_val,
4338             not_every_iteration, maybe_multiple)
4339      struct induction *v;
4340      rtx insn;
4341      rtx dest_reg;
4342      rtx inc_val;
4343      rtx mult_val;
4344      int not_every_iteration;
4345      int maybe_multiple;
4346 {
4347   struct iv_class *bl;
4348
4349   v->insn = insn;
4350   v->src_reg = dest_reg;
4351   v->dest_reg = dest_reg;
4352   v->mult_val = mult_val;
4353   v->add_val = inc_val;
4354   v->mode = GET_MODE (dest_reg);
4355   v->always_computable = ! not_every_iteration;
4356   v->always_executed = ! not_every_iteration;
4357   v->maybe_multiple = maybe_multiple;
4358
4359   /* Add this to the reg's iv_class, creating a class
4360      if this is the first incrementation of the reg.  */
4361
4362   bl = reg_biv_class[REGNO (dest_reg)];
4363   if (bl == 0)
4364     {
4365       /* Create and initialize new iv_class.  */
4366
4367       bl = (struct iv_class *) oballoc (sizeof (struct iv_class));
4368
4369       bl->regno = REGNO (dest_reg);
4370       bl->biv = 0;
4371       bl->giv = 0;
4372       bl->biv_count = 0;
4373       bl->giv_count = 0;
4374
4375       /* Set initial value to the reg itself.  */
4376       bl->initial_value = dest_reg;
4377       /* We haven't seen the initializing insn yet */
4378       bl->init_insn = 0;
4379       bl->init_set = 0;
4380       bl->initial_test = 0;
4381       bl->incremented = 0;
4382       bl->eliminable = 0;
4383       bl->nonneg = 0;
4384       bl->reversed = 0;
4385       bl->total_benefit = 0;
4386
4387       /* Add this class to loop_iv_list.  */
4388       bl->next = loop_iv_list;
4389       loop_iv_list = bl;
4390
4391       /* Put it in the array of biv register classes.  */
4392       reg_biv_class[REGNO (dest_reg)] = bl;
4393     }
4394
4395   /* Update IV_CLASS entry for this biv.  */
4396   v->next_iv = bl->biv;
4397   bl->biv = v;
4398   bl->biv_count++;
4399   if (mult_val == const1_rtx)
4400     bl->incremented = 1;
4401
4402   if (loop_dump_stream)
4403     {
4404       fprintf (loop_dump_stream,
4405                "Insn %d: possible biv, reg %d,",
4406                INSN_UID (insn), REGNO (dest_reg));
4407       if (GET_CODE (inc_val) == CONST_INT)
4408         fprintf (loop_dump_stream, " const = %d\n",
4409                  INTVAL (inc_val));
4410       else
4411         {
4412           fprintf (loop_dump_stream, " const = ");
4413           print_rtl (loop_dump_stream, inc_val);
4414           fprintf (loop_dump_stream, "\n");
4415         }
4416     }
4417 }
4418 \f
4419 /* Fill in the data about one giv.
4420    V is the `struct induction' in which we record the giv.  (It is
4421    allocated by the caller, with alloca.)
4422    INSN is the insn that sets it.
4423    BENEFIT estimates the savings from deleting this insn.
4424    TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
4425    into a register or is used as a memory address.
4426
4427    SRC_REG is the biv reg which the giv is computed from.
4428    DEST_REG is the giv's reg (if the giv is stored in a reg).
4429    MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
4430    LOCATION points to the place where this giv's value appears in INSN.  */
4431
4432 static void
4433 record_giv (v, insn, src_reg, dest_reg, mult_val, add_val, benefit,
4434             type, not_every_iteration, location, loop_start, loop_end)
4435      struct induction *v;
4436      rtx insn;
4437      rtx src_reg;
4438      rtx dest_reg;
4439      rtx mult_val, add_val;
4440      int benefit;
4441      enum g_types type;
4442      int not_every_iteration;
4443      rtx *location;
4444      rtx loop_start, loop_end;
4445 {
4446   struct induction *b;
4447   struct iv_class *bl;
4448   rtx set = single_set (insn);
4449   rtx p;
4450
4451   v->insn = insn;
4452   v->src_reg = src_reg;
4453   v->giv_type = type;
4454   v->dest_reg = dest_reg;
4455   v->mult_val = mult_val;
4456   v->add_val = add_val;
4457   v->benefit = benefit;
4458   v->location = location;
4459   v->cant_derive = 0;
4460   v->combined_with = 0;
4461   v->maybe_multiple = 0;
4462   v->maybe_dead = 0;
4463   v->derive_adjustment = 0;
4464   v->same = 0;
4465   v->ignore = 0;
4466   v->new_reg = 0;
4467   v->final_value = 0;
4468   v->same_insn = 0;
4469   v->auto_inc_opt = 0;
4470
4471   /* The v->always_computable field is used in update_giv_derive, to
4472      determine whether a giv can be used to derive another giv.  For a
4473      DEST_REG giv, INSN computes a new value for the giv, so its value
4474      isn't computable if INSN insn't executed every iteration.
4475      However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
4476      it does not compute a new value.  Hence the value is always computable
4477      regardless of whether INSN is executed each iteration.  */
4478
4479   if (type == DEST_ADDR)
4480     v->always_computable = 1;
4481   else
4482     v->always_computable = ! not_every_iteration;
4483
4484   v->always_executed = ! not_every_iteration;
4485
4486   if (type == DEST_ADDR)
4487     {
4488       v->mode = GET_MODE (*location);
4489       v->lifetime = 1;
4490       v->times_used = 1;
4491     }
4492   else /* type == DEST_REG */
4493     {
4494       v->mode = GET_MODE (SET_DEST (set));
4495
4496       v->lifetime = (uid_luid[regno_last_uid[REGNO (dest_reg)]]
4497                      - uid_luid[regno_first_uid[REGNO (dest_reg)]]);
4498
4499       v->times_used = n_times_used[REGNO (dest_reg)];
4500
4501       /* If the lifetime is zero, it means that this register is
4502          really a dead store.  So mark this as a giv that can be
4503          ignored.  This will not prevent the biv from being eliminated. */
4504       if (v->lifetime == 0)
4505         v->ignore = 1;
4506
4507       reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
4508       reg_iv_info[REGNO (dest_reg)] = v;
4509     }
4510
4511   /* Add the giv to the class of givs computed from one biv.  */
4512
4513   bl = reg_biv_class[REGNO (src_reg)];
4514   if (bl)
4515     {
4516       v->next_iv = bl->giv;
4517       bl->giv = v;
4518       /* Don't count DEST_ADDR.  This is supposed to count the number of
4519          insns that calculate givs.  */
4520       if (type == DEST_REG)
4521         bl->giv_count++;
4522       bl->total_benefit += benefit;
4523     }
4524   else
4525     /* Fatal error, biv missing for this giv?  */
4526     abort ();
4527
4528   if (type == DEST_ADDR)
4529     v->replaceable = 1;
4530   else
4531     {
4532       /* The giv can be replaced outright by the reduced register only if all
4533          of the following conditions are true:
4534          - the insn that sets the giv is always executed on any iteration
4535            on which the giv is used at all
4536            (there are two ways to deduce this:
4537             either the insn is executed on every iteration,
4538             or all uses follow that insn in the same basic block),
4539          - the giv is not used outside the loop
4540          - no assignments to the biv occur during the giv's lifetime.  */
4541
4542       if (regno_first_uid[REGNO (dest_reg)] == INSN_UID (insn)
4543           /* Previous line always fails if INSN was moved by loop opt.  */
4544           && uid_luid[regno_last_uid[REGNO (dest_reg)]] < INSN_LUID (loop_end)
4545           && (! not_every_iteration
4546               || last_use_this_basic_block (dest_reg, insn)))
4547         {
4548           /* Now check that there are no assignments to the biv within the
4549              giv's lifetime.  This requires two separate checks.  */
4550
4551           /* Check each biv update, and fail if any are between the first
4552              and last use of the giv.
4553              
4554              If this loop contains an inner loop that was unrolled, then
4555              the insn modifying the biv may have been emitted by the loop
4556              unrolling code, and hence does not have a valid luid.  Just
4557              mark the biv as not replaceable in this case.  It is not very
4558              useful as a biv, because it is used in two different loops.
4559              It is very unlikely that we would be able to optimize the giv
4560              using this biv anyways.  */
4561
4562           v->replaceable = 1;
4563           for (b = bl->biv; b; b = b->next_iv)
4564             {
4565               if (INSN_UID (b->insn) >= max_uid_for_loop
4566                   || ((uid_luid[INSN_UID (b->insn)]
4567                        >= uid_luid[regno_first_uid[REGNO (dest_reg)]])
4568                       && (uid_luid[INSN_UID (b->insn)]
4569                           <= uid_luid[regno_last_uid[REGNO (dest_reg)]])))
4570                 {
4571                   v->replaceable = 0;
4572                   v->not_replaceable = 1;
4573                   break;
4574                 }
4575             }
4576
4577           /* If there are any backwards branches that go from after the
4578              biv update to before it, then this giv is not replaceable.  */
4579           if (v->replaceable)
4580             for (b = bl->biv; b; b = b->next_iv)
4581               if (back_branch_in_range_p (b->insn, loop_start, loop_end))
4582                 {
4583                   v->replaceable = 0;
4584                   v->not_replaceable = 1;
4585                   break;
4586                 }
4587         }
4588       else
4589         {
4590           /* May still be replaceable, we don't have enough info here to
4591              decide.  */
4592           v->replaceable = 0;
4593           v->not_replaceable = 0;
4594         }
4595     }
4596
4597   if (loop_dump_stream)
4598     {
4599       if (type == DEST_REG)
4600         fprintf (loop_dump_stream, "Insn %d: giv reg %d",
4601                  INSN_UID (insn), REGNO (dest_reg));
4602       else
4603         fprintf (loop_dump_stream, "Insn %d: dest address",
4604                  INSN_UID (insn));
4605
4606       fprintf (loop_dump_stream, " src reg %d benefit %d",
4607                REGNO (src_reg), v->benefit);
4608       fprintf (loop_dump_stream, " used %d lifetime %d",
4609                v->times_used, v->lifetime);
4610
4611       if (v->replaceable)
4612         fprintf (loop_dump_stream, " replaceable");
4613
4614       if (GET_CODE (mult_val) == CONST_INT)
4615         fprintf (loop_dump_stream, " mult %d",
4616                  INTVAL (mult_val));
4617       else
4618         {
4619           fprintf (loop_dump_stream, " mult ");
4620           print_rtl (loop_dump_stream, mult_val);
4621         }
4622
4623       if (GET_CODE (add_val) == CONST_INT)
4624         fprintf (loop_dump_stream, " add %d",
4625                  INTVAL (add_val));
4626       else
4627         {
4628           fprintf (loop_dump_stream, " add ");
4629           print_rtl (loop_dump_stream, add_val);
4630         }
4631     }
4632
4633   if (loop_dump_stream)
4634     fprintf (loop_dump_stream, "\n");
4635
4636 }
4637
4638
4639 /* All this does is determine whether a giv can be made replaceable because
4640    its final value can be calculated.  This code can not be part of record_giv
4641    above, because final_giv_value requires that the number of loop iterations
4642    be known, and that can not be accurately calculated until after all givs
4643    have been identified.  */
4644
4645 static void
4646 check_final_value (v, loop_start, loop_end)
4647      struct induction *v;
4648      rtx loop_start, loop_end;
4649 {
4650   struct iv_class *bl;
4651   rtx final_value = 0;
4652
4653   bl = reg_biv_class[REGNO (v->src_reg)];
4654
4655   /* DEST_ADDR givs will never reach here, because they are always marked
4656      replaceable above in record_giv.  */
4657
4658   /* The giv can be replaced outright by the reduced register only if all
4659      of the following conditions are true:
4660      - the insn that sets the giv is always executed on any iteration
4661        on which the giv is used at all
4662        (there are two ways to deduce this:
4663         either the insn is executed on every iteration,
4664         or all uses follow that insn in the same basic block),
4665      - its final value can be calculated (this condition is different
4666        than the one above in record_giv)
4667      - no assignments to the biv occur during the giv's lifetime.  */
4668
4669 #if 0
4670   /* This is only called now when replaceable is known to be false.  */
4671   /* Clear replaceable, so that it won't confuse final_giv_value.  */
4672   v->replaceable = 0;
4673 #endif
4674
4675   if ((final_value = final_giv_value (v, loop_start, loop_end))
4676       && (v->always_computable || last_use_this_basic_block (v->dest_reg, v->insn)))
4677     {
4678       int biv_increment_seen = 0;
4679       rtx p = v->insn;
4680       rtx last_giv_use;
4681
4682       v->replaceable = 1;
4683
4684       /* When trying to determine whether or not a biv increment occurs
4685          during the lifetime of the giv, we can ignore uses of the variable
4686          outside the loop because final_value is true.  Hence we can not
4687          use regno_last_uid and regno_first_uid as above in record_giv.  */
4688
4689       /* Search the loop to determine whether any assignments to the
4690          biv occur during the giv's lifetime.  Start with the insn
4691          that sets the giv, and search around the loop until we come
4692          back to that insn again.
4693
4694          Also fail if there is a jump within the giv's lifetime that jumps
4695          to somewhere outside the lifetime but still within the loop.  This
4696          catches spaghetti code where the execution order is not linear, and
4697          hence the above test fails.  Here we assume that the giv lifetime
4698          does not extend from one iteration of the loop to the next, so as
4699          to make the test easier.  Since the lifetime isn't known yet,
4700          this requires two loops.  See also record_giv above.  */
4701
4702       last_giv_use = v->insn;
4703
4704       while (1)
4705         {
4706           p = NEXT_INSN (p);
4707           if (p == loop_end)
4708             p = NEXT_INSN (loop_start);
4709           if (p == v->insn)
4710             break;
4711
4712           if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
4713               || GET_CODE (p) == CALL_INSN)
4714             {
4715               if (biv_increment_seen)
4716                 {
4717                   if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
4718                     {
4719                       v->replaceable = 0;
4720                       v->not_replaceable = 1;
4721                       break;
4722                     }
4723                 }
4724               else if (GET_CODE (PATTERN (p)) == SET
4725                        && SET_DEST (PATTERN (p)) == v->src_reg)
4726                 biv_increment_seen = 1;
4727               else if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
4728                 last_giv_use = p;
4729             }
4730         }
4731       
4732       /* Now that the lifetime of the giv is known, check for branches
4733          from within the lifetime to outside the lifetime if it is still
4734          replaceable.  */
4735
4736       if (v->replaceable)
4737         {
4738           p = v->insn;
4739           while (1)
4740             {
4741               p = NEXT_INSN (p);
4742               if (p == loop_end)
4743                 p = NEXT_INSN (loop_start);
4744               if (p == last_giv_use)
4745                 break;
4746
4747               if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
4748                   && LABEL_NAME (JUMP_LABEL (p))
4749                   && ((INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (v->insn)
4750                        && INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop_start))
4751                       || (INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (last_giv_use)
4752                           && INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop_end))))
4753                 {
4754                   v->replaceable = 0;
4755                   v->not_replaceable = 1;
4756
4757                   if (loop_dump_stream)
4758                     fprintf (loop_dump_stream,
4759                              "Found branch outside giv lifetime.\n");
4760
4761                   break;
4762                 }
4763             }
4764         }
4765
4766       /* If it is replaceable, then save the final value.  */
4767       if (v->replaceable)
4768         v->final_value = final_value;
4769     }
4770
4771   if (loop_dump_stream && v->replaceable)
4772     fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
4773              INSN_UID (v->insn), REGNO (v->dest_reg));
4774 }
4775 \f
4776 /* Update the status of whether a giv can derive other givs.
4777
4778    We need to do something special if there is or may be an update to the biv
4779    between the time the giv is defined and the time it is used to derive
4780    another giv.
4781
4782    In addition, a giv that is only conditionally set is not allowed to
4783    derive another giv once a label has been passed.
4784
4785    The cases we look at are when a label or an update to a biv is passed.  */
4786
4787 static void
4788 update_giv_derive (p)
4789      rtx p;
4790 {
4791   struct iv_class *bl;
4792   struct induction *biv, *giv;
4793   rtx tem;
4794   int dummy;
4795
4796   /* Search all IV classes, then all bivs, and finally all givs.
4797
4798      There are three cases we are concerned with.  First we have the situation
4799      of a giv that is only updated conditionally.  In that case, it may not
4800      derive any givs after a label is passed.
4801
4802      The second case is when a biv update occurs, or may occur, after the
4803      definition of a giv.  For certain biv updates (see below) that are
4804      known to occur between the giv definition and use, we can adjust the
4805      giv definition.  For others, or when the biv update is conditional,
4806      we must prevent the giv from deriving any other givs.  There are two
4807      sub-cases within this case.
4808
4809      If this is a label, we are concerned with any biv update that is done
4810      conditionally, since it may be done after the giv is defined followed by
4811      a branch here (actually, we need to pass both a jump and a label, but
4812      this extra tracking doesn't seem worth it).
4813
4814      If this is a jump, we are concerned about any biv update that may be
4815      executed multiple times.  We are actually only concerned about
4816      backward jumps, but it is probably not worth performing the test
4817      on the jump again here.
4818
4819      If this is a biv update, we must adjust the giv status to show that a
4820      subsequent biv update was performed.  If this adjustment cannot be done,
4821      the giv cannot derive further givs.  */
4822
4823   for (bl = loop_iv_list; bl; bl = bl->next)
4824     for (biv = bl->biv; biv; biv = biv->next_iv)
4825       if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
4826           || biv->insn == p)
4827         {
4828           for (giv = bl->giv; giv; giv = giv->next_iv)
4829             {
4830               /* If cant_derive is already true, there is no point in
4831                  checking all of these conditions again.  */
4832               if (giv->cant_derive)
4833                 continue;
4834
4835               /* If this giv is conditionally set and we have passed a label,
4836                  it cannot derive anything.  */
4837               if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
4838                 giv->cant_derive = 1;
4839
4840               /* Skip givs that have mult_val == 0, since
4841                  they are really invariants.  Also skip those that are
4842                  replaceable, since we know their lifetime doesn't contain
4843                  any biv update.  */
4844               else if (giv->mult_val == const0_rtx || giv->replaceable)
4845                 continue;
4846
4847               /* The only way we can allow this giv to derive another
4848                  is if this is a biv increment and we can form the product
4849                  of biv->add_val and giv->mult_val.  In this case, we will
4850                  be able to compute a compensation.  */
4851               else if (biv->insn == p)
4852                 {
4853                   tem = 0;
4854
4855                   if (biv->mult_val == const1_rtx)
4856                     tem = simplify_giv_expr (gen_rtx (MULT, giv->mode,
4857                                                       biv->add_val,
4858                                                       giv->mult_val),
4859                                              &dummy);
4860
4861                   if (tem && giv->derive_adjustment)
4862                     tem = simplify_giv_expr (gen_rtx (PLUS, giv->mode, tem,
4863                                                       giv->derive_adjustment),
4864                                              &dummy);
4865                   if (tem)
4866                     giv->derive_adjustment = tem;
4867                   else
4868                     giv->cant_derive = 1;
4869                 }
4870               else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
4871                        || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
4872                 giv->cant_derive = 1;
4873             }
4874         }
4875 }
4876 \f
4877 /* Check whether an insn is an increment legitimate for a basic induction var.
4878    X is the source of insn P, or a part of it.
4879    MODE is the mode in which X should be interpreted.
4880
4881    DEST_REG is the putative biv, also the destination of the insn.
4882    We accept patterns of these forms:
4883      REG = REG + INVARIANT (includes REG = REG - CONSTANT)
4884      REG = INVARIANT + REG
4885
4886    If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
4887    and store the additive term into *INC_VAL.
4888
4889    If X is an assignment of an invariant into DEST_REG, we set
4890    *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
4891
4892    We also want to detect a BIV when it corresponds to a variable
4893    whose mode was promoted via PROMOTED_MODE.  In that case, an increment
4894    of the variable may be a PLUS that adds a SUBREG of that variable to
4895    an invariant and then sign- or zero-extends the result of the PLUS
4896    into the variable.
4897
4898    Most GIVs in such cases will be in the promoted mode, since that is the
4899    probably the natural computation mode (and almost certainly the mode
4900    used for addresses) on the machine.  So we view the pseudo-reg containing
4901    the variable as the BIV, as if it were simply incremented.
4902
4903    Note that treating the entire pseudo as a BIV will result in making
4904    simple increments to any GIVs based on it.  However, if the variable
4905    overflows in its declared mode but not its promoted mode, the result will
4906    be incorrect.  This is acceptable if the variable is signed, since 
4907    overflows in such cases are undefined, but not if it is unsigned, since
4908    those overflows are defined.  So we only check for SIGN_EXTEND and
4909    not ZERO_EXTEND.
4910
4911    If we cannot find a biv, we return 0.  */
4912
4913 static int
4914 basic_induction_var (x, mode, dest_reg, p, inc_val, mult_val)
4915      register rtx x;
4916      enum machine_mode mode;
4917      rtx p;
4918      rtx dest_reg;
4919      rtx *inc_val;
4920      rtx *mult_val;
4921 {
4922   register enum rtx_code code;
4923   rtx arg;
4924   rtx insn, set = 0;
4925
4926   code = GET_CODE (x);
4927   switch (code)
4928     {
4929     case PLUS:
4930       if (XEXP (x, 0) == dest_reg
4931           || (GET_CODE (XEXP (x, 0)) == SUBREG
4932               && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
4933               && SUBREG_REG (XEXP (x, 0)) == dest_reg))
4934         arg = XEXP (x, 1);
4935       else if (XEXP (x, 1) == dest_reg
4936                || (GET_CODE (XEXP (x, 1)) == SUBREG
4937                    && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
4938                    && SUBREG_REG (XEXP (x, 1)) == dest_reg))
4939         arg = XEXP (x, 0);
4940       else
4941         return 0;
4942
4943       if (invariant_p (arg) != 1)
4944         return 0;
4945
4946       *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
4947       *mult_val = const1_rtx;
4948       return 1;
4949
4950     case SUBREG:
4951       /* If this is a SUBREG for a promoted variable, check the inner
4952          value.  */
4953       if (SUBREG_PROMOTED_VAR_P (x))
4954         return basic_induction_var (SUBREG_REG (x), GET_MODE (SUBREG_REG (x)),
4955                                     dest_reg, p, inc_val, mult_val);
4956
4957     case REG:
4958       /* If this register is assigned in the previous insn, look at its
4959          source, but don't go outside the loop or past a label.  */
4960
4961       for (insn = PREV_INSN (p);
4962            (insn && GET_CODE (insn) == NOTE
4963             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
4964            insn = PREV_INSN (insn))
4965         ;
4966
4967       if (insn)
4968         set = single_set (insn);
4969
4970       if (set != 0
4971           && (SET_DEST (set) == x
4972               || (GET_CODE (SET_DEST (set)) == SUBREG
4973                   && (GET_MODE_SIZE (GET_MODE (SET_DEST (set)))
4974                       <= UNITS_PER_WORD)
4975                   && SUBREG_REG (SET_DEST (set)) == x)))
4976         return basic_induction_var (SET_SRC (set),
4977                                     (GET_MODE (SET_SRC (set)) == VOIDmode
4978                                      ? GET_MODE (x)
4979                                      : GET_MODE (SET_SRC (set))),
4980                                     dest_reg, insn,
4981                                     inc_val, mult_val);
4982       /* ... fall through ... */
4983
4984       /* Can accept constant setting of biv only when inside inner most loop.
4985          Otherwise, a biv of an inner loop may be incorrectly recognized
4986          as a biv of the outer loop,
4987          causing code to be moved INTO the inner loop.  */
4988     case MEM:
4989       if (invariant_p (x) != 1)
4990         return 0;
4991     case CONST_INT:
4992     case SYMBOL_REF:
4993     case CONST:
4994       if (loops_enclosed == 1)
4995         {
4996           /* Possible bug here?  Perhaps we don't know the mode of X.  */
4997           *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
4998           *mult_val = const0_rtx;
4999           return 1;
5000         }
5001       else
5002         return 0;
5003
5004     case SIGN_EXTEND:
5005       return basic_induction_var (XEXP (x, 0), GET_MODE (XEXP (x, 0)),
5006                                   dest_reg, p, inc_val, mult_val);
5007     case ASHIFTRT:
5008       /* Similar, since this can be a sign extension.  */
5009       for (insn = PREV_INSN (p);
5010            (insn && GET_CODE (insn) == NOTE
5011             && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
5012            insn = PREV_INSN (insn))
5013         ;
5014
5015       if (insn)
5016         set = single_set (insn);
5017
5018       if (set && SET_DEST (set) == XEXP (x, 0)
5019           && GET_CODE (XEXP (x, 1)) == CONST_INT
5020           && INTVAL (XEXP (x, 1)) >= 0
5021           && GET_CODE (SET_SRC (set)) == ASHIFT
5022           && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
5023         return basic_induction_var (XEXP (SET_SRC (set), 0),
5024                                     GET_MODE (XEXP (x, 0)),
5025                                     dest_reg, insn, inc_val, mult_val);
5026       return 0;
5027
5028     default:
5029       return 0;
5030     }
5031 }
5032 \f
5033 /* A general induction variable (giv) is any quantity that is a linear
5034    function   of a basic induction variable,
5035    i.e. giv = biv * mult_val + add_val.
5036    The coefficients can be any loop invariant quantity.
5037    A giv need not be computed directly from the biv;
5038    it can be computed by way of other givs.  */
5039
5040 /* Determine whether X computes a giv.
5041    If it does, return a nonzero value
5042      which is the benefit from eliminating the computation of X;
5043    set *SRC_REG to the register of the biv that it is computed from;
5044    set *ADD_VAL and *MULT_VAL to the coefficients,
5045      such that the value of X is biv * mult + add;  */
5046
5047 static int
5048 general_induction_var (x, src_reg, add_val, mult_val)
5049      rtx x;
5050      rtx *src_reg;
5051      rtx *add_val;
5052      rtx *mult_val;
5053 {
5054   rtx orig_x = x;
5055   int benefit = 0;
5056   char *storage;
5057
5058   /* If this is an invariant, forget it, it isn't a giv.  */
5059   if (invariant_p (x) == 1)
5060     return 0;
5061
5062   /* See if the expression could be a giv and get its form.
5063      Mark our place on the obstack in case we don't find a giv.  */
5064   storage = (char *) oballoc (0);
5065   x = simplify_giv_expr (x, &benefit);
5066   if (x == 0)
5067     {
5068       obfree (storage);
5069       return 0;
5070     }
5071
5072   switch (GET_CODE (x))
5073     {
5074     case USE:
5075     case CONST_INT:
5076       /* Since this is now an invariant and wasn't before, it must be a giv
5077          with MULT_VAL == 0.  It doesn't matter which BIV we associate this
5078          with.  */
5079       *src_reg = loop_iv_list->biv->dest_reg;
5080       *mult_val = const0_rtx;
5081       *add_val = x;
5082       break;
5083
5084     case REG:
5085       /* This is equivalent to a BIV.  */
5086       *src_reg = x;
5087       *mult_val = const1_rtx;
5088       *add_val = const0_rtx;
5089       break;
5090
5091     case PLUS:
5092       /* Either (plus (biv) (invar)) or
5093          (plus (mult (biv) (invar_1)) (invar_2)).  */
5094       if (GET_CODE (XEXP (x, 0)) == MULT)
5095         {
5096           *src_reg = XEXP (XEXP (x, 0), 0);
5097           *mult_val = XEXP (XEXP (x, 0), 1);
5098         }
5099       else
5100         {
5101           *src_reg = XEXP (x, 0);
5102           *mult_val = const1_rtx;
5103         }
5104       *add_val = XEXP (x, 1);
5105       break;
5106
5107     case MULT:
5108       /* ADD_VAL is zero.  */
5109       *src_reg = XEXP (x, 0);
5110       *mult_val = XEXP (x, 1);
5111       *add_val = const0_rtx;
5112       break;
5113
5114     default:
5115       abort ();
5116     }
5117
5118   /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
5119      unless they are CONST_INT).  */
5120   if (GET_CODE (*add_val) == USE)
5121     *add_val = XEXP (*add_val, 0);
5122   if (GET_CODE (*mult_val) == USE)
5123     *mult_val = XEXP (*mult_val, 0);
5124
5125   benefit += rtx_cost (orig_x, SET);
5126
5127   /* Always return some benefit if this is a giv so it will be detected
5128      as such.  This allows elimination of bivs that might otherwise
5129      not be eliminated.  */
5130   return benefit == 0 ? 1 : benefit;
5131 }
5132 \f
5133 /* Given an expression, X, try to form it as a linear function of a biv.
5134    We will canonicalize it to be of the form
5135         (plus (mult (BIV) (invar_1))
5136               (invar_2))
5137    with possible degeneracies.
5138
5139    The invariant expressions must each be of a form that can be used as a
5140    machine operand.  We surround then with a USE rtx (a hack, but localized
5141    and certainly unambiguous!) if not a CONST_INT for simplicity in this
5142    routine; it is the caller's responsibility to strip them.
5143
5144    If no such canonicalization is possible (i.e., two biv's are used or an
5145    expression that is neither invariant nor a biv or giv), this routine
5146    returns 0.
5147
5148    For a non-zero return, the result will have a code of CONST_INT, USE,
5149    REG (for a BIV), PLUS, or MULT.  No other codes will occur.  
5150
5151    *BENEFIT will be incremented by the benefit of any sub-giv encountered.  */
5152
5153 static rtx
5154 simplify_giv_expr (x, benefit)
5155      rtx x;
5156      int *benefit;
5157 {
5158   enum machine_mode mode = GET_MODE (x);
5159   rtx arg0, arg1;
5160   rtx tem;
5161
5162   /* If this is not an integer mode, or if we cannot do arithmetic in this
5163      mode, this can't be a giv.  */
5164   if (mode != VOIDmode
5165       && (GET_MODE_CLASS (mode) != MODE_INT
5166           || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
5167     return 0;
5168
5169   switch (GET_CODE (x))
5170     {
5171     case PLUS:
5172       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
5173       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
5174       if (arg0 == 0 || arg1 == 0)
5175         return 0;
5176
5177       /* Put constant last, CONST_INT last if both constant.  */
5178       if ((GET_CODE (arg0) == USE
5179            || GET_CODE (arg0) == CONST_INT)
5180           && GET_CODE (arg1) != CONST_INT)
5181         tem = arg0, arg0 = arg1, arg1 = tem;
5182
5183       /* Handle addition of zero, then addition of an invariant.  */
5184       if (arg1 == const0_rtx)
5185         return arg0;
5186       else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
5187         switch (GET_CODE (arg0))
5188           {
5189           case CONST_INT:
5190           case USE:
5191             /* Both invariant.  Only valid if sum is machine operand.
5192                First strip off possible USE on first operand.  */
5193             if (GET_CODE (arg0) == USE)
5194               arg0 = XEXP (arg0, 0);
5195
5196             tem = 0;
5197             if (CONSTANT_P (arg0) && GET_CODE (arg1) == CONST_INT)
5198               {
5199                 tem = plus_constant (arg0, INTVAL (arg1));
5200                 if (GET_CODE (tem) != CONST_INT)
5201                   tem = gen_rtx (USE, mode, tem);
5202               }
5203
5204             return tem;
5205
5206           case REG:
5207           case MULT:
5208             /* biv + invar or mult + invar.  Return sum.  */
5209             return gen_rtx (PLUS, mode, arg0, arg1);
5210
5211           case PLUS:
5212             /* (a + invar_1) + invar_2.  Associate.  */
5213             return simplify_giv_expr (gen_rtx (PLUS, mode,
5214                                                XEXP (arg0, 0),
5215                                                gen_rtx (PLUS, mode,
5216                                                         XEXP (arg0, 1), arg1)),
5217                                       benefit);
5218
5219           default:
5220             abort ();
5221           }
5222
5223       /* Each argument must be either REG, PLUS, or MULT.  Convert REG to
5224          MULT to reduce cases.  */
5225       if (GET_CODE (arg0) == REG)
5226         arg0 = gen_rtx (MULT, mode, arg0, const1_rtx);
5227       if (GET_CODE (arg1) == REG)
5228         arg1 = gen_rtx (MULT, mode, arg1, const1_rtx);
5229
5230       /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
5231          Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
5232          Recurse to associate the second PLUS.  */
5233       if (GET_CODE (arg1) == MULT)
5234         tem = arg0, arg0 = arg1, arg1 = tem;
5235
5236       if (GET_CODE (arg1) == PLUS)
5237           return simplify_giv_expr (gen_rtx (PLUS, mode,
5238                                              gen_rtx (PLUS, mode,
5239                                                       arg0, XEXP (arg1, 0)),
5240                                              XEXP (arg1, 1)),
5241                                     benefit);
5242
5243       /* Now must have MULT + MULT.  Distribute if same biv, else not giv.  */
5244       if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
5245         abort ();
5246
5247       if (XEXP (arg0, 0) != XEXP (arg1, 0))
5248         return 0;
5249
5250       return simplify_giv_expr (gen_rtx (MULT, mode,
5251                                          XEXP (arg0, 0),
5252                                          gen_rtx (PLUS, mode,
5253                                                   XEXP (arg0, 1),
5254                                                   XEXP (arg1, 1))),
5255                                 benefit);
5256
5257     case MINUS:
5258       /* Handle "a - b" as "a + b * (-1)". */
5259       return simplify_giv_expr (gen_rtx (PLUS, mode,
5260                                          XEXP (x, 0),
5261                                          gen_rtx (MULT, mode,
5262                                                   XEXP (x, 1), constm1_rtx)),
5263                                 benefit);
5264
5265     case MULT:
5266       arg0 = simplify_giv_expr (XEXP (x, 0), benefit);
5267       arg1 = simplify_giv_expr (XEXP (x, 1), benefit);
5268       if (arg0 == 0 || arg1 == 0)
5269         return 0;
5270
5271       /* Put constant last, CONST_INT last if both constant.  */
5272       if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
5273           && GET_CODE (arg1) != CONST_INT)
5274         tem = arg0, arg0 = arg1, arg1 = tem;
5275
5276       /* If second argument is not now constant, not giv.  */
5277       if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
5278         return 0;
5279
5280       /* Handle multiply by 0 or 1.  */
5281       if (arg1 == const0_rtx)
5282         return const0_rtx;
5283
5284       else if (arg1 == const1_rtx)
5285         return arg0;
5286
5287       switch (GET_CODE (arg0))
5288         {
5289         case REG:
5290           /* biv * invar.  Done.  */
5291           return gen_rtx (MULT, mode, arg0, arg1);
5292
5293         case CONST_INT:
5294           /* Product of two constants.  */
5295           return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
5296
5297         case USE:
5298           /* invar * invar.  Not giv. */
5299           return 0;
5300
5301         case MULT:
5302           /* (a * invar_1) * invar_2.  Associate.  */
5303           return simplify_giv_expr (gen_rtx (MULT, mode,
5304                                              XEXP (arg0, 0),
5305                                              gen_rtx (MULT, mode,
5306                                                       XEXP (arg0, 1), arg1)),
5307                                     benefit);
5308
5309         case PLUS:
5310           /* (a + invar_1) * invar_2.  Distribute.  */
5311           return simplify_giv_expr (gen_rtx (PLUS, mode,
5312                                              gen_rtx (MULT, mode,
5313                                                       XEXP (arg0, 0), arg1),
5314                                              gen_rtx (MULT, mode,
5315                                                       XEXP (arg0, 1), arg1)),
5316                                     benefit);
5317
5318         default:
5319           abort ();
5320         }
5321
5322     case ASHIFT:
5323       /* Shift by constant is multiply by power of two.  */
5324       if (GET_CODE (XEXP (x, 1)) != CONST_INT)
5325         return 0;
5326
5327       return simplify_giv_expr (gen_rtx (MULT, mode,
5328                                          XEXP (x, 0),
5329                                          GEN_INT ((HOST_WIDE_INT) 1
5330                                                   << INTVAL (XEXP (x, 1)))),
5331                                 benefit);
5332
5333     case NEG:
5334       /* "-a" is "a * (-1)" */
5335       return simplify_giv_expr (gen_rtx (MULT, mode, XEXP (x, 0), constm1_rtx),
5336                                 benefit);
5337
5338     case NOT:
5339       /* "~a" is "-a - 1". Silly, but easy.  */
5340       return simplify_giv_expr (gen_rtx (MINUS, mode,
5341                                          gen_rtx (NEG, mode, XEXP (x, 0)),
5342                                          const1_rtx),
5343                                 benefit);
5344
5345     case USE:
5346       /* Already in proper form for invariant.  */
5347       return x;
5348
5349     case REG:
5350       /* If this is a new register, we can't deal with it.  */
5351       if (REGNO (x) >= max_reg_before_loop)
5352         return 0;
5353
5354       /* Check for biv or giv.  */
5355       switch (reg_iv_type[REGNO (x)])
5356         {
5357         case BASIC_INDUCT:
5358           return x;
5359         case GENERAL_INDUCT:
5360           {
5361             struct induction *v = reg_iv_info[REGNO (x)];
5362
5363             /* Form expression from giv and add benefit.  Ensure this giv
5364                can derive another and subtract any needed adjustment if so.  */
5365             *benefit += v->benefit;
5366             if (v->cant_derive)
5367               return 0;
5368
5369             tem = gen_rtx (PLUS, mode, gen_rtx (MULT, mode,
5370                                                 v->src_reg, v->mult_val),
5371                            v->add_val);
5372             if (v->derive_adjustment)
5373               tem = gen_rtx (MINUS, mode, tem, v->derive_adjustment);
5374             return simplify_giv_expr (tem, benefit);
5375           }
5376         }
5377
5378       /* Fall through to general case.  */
5379     default:
5380       /* If invariant, return as USE (unless CONST_INT).
5381          Otherwise, not giv.  */
5382       if (GET_CODE (x) == USE)
5383         x = XEXP (x, 0);
5384
5385       if (invariant_p (x) == 1)
5386         {
5387           if (GET_CODE (x) == CONST_INT)
5388             return x;
5389           else
5390             return gen_rtx (USE, mode, x);
5391         }
5392       else
5393         return 0;
5394     }
5395 }
5396 \f
5397 /* Help detect a giv that is calculated by several consecutive insns;
5398    for example,
5399       giv = biv * M
5400       giv = giv + A
5401    The caller has already identified the first insn P as having a giv as dest;
5402    we check that all other insns that set the same register follow
5403    immediately after P, that they alter nothing else,
5404    and that the result of the last is still a giv.
5405
5406    The value is 0 if the reg set in P is not really a giv.
5407    Otherwise, the value is the amount gained by eliminating
5408    all the consecutive insns that compute the value.
5409
5410    FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
5411    SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
5412
5413    The coefficients of the ultimate giv value are stored in
5414    *MULT_VAL and *ADD_VAL.  */
5415
5416 static int
5417 consec_sets_giv (first_benefit, p, src_reg, dest_reg,
5418                  add_val, mult_val)
5419      int first_benefit;
5420      rtx p;
5421      rtx src_reg;
5422      rtx dest_reg;
5423      rtx *add_val;
5424      rtx *mult_val;
5425 {
5426   int count;
5427   enum rtx_code code;
5428   int benefit;
5429   rtx temp;
5430   rtx set;
5431
5432   /* Indicate that this is a giv so that we can update the value produced in
5433      each insn of the multi-insn sequence. 
5434
5435      This induction structure will be used only by the call to
5436      general_induction_var below, so we can allocate it on our stack.
5437      If this is a giv, our caller will replace the induct var entry with
5438      a new induction structure.  */
5439   struct induction *v
5440     = (struct induction *) alloca (sizeof (struct induction));
5441   v->src_reg = src_reg;
5442   v->mult_val = *mult_val;
5443   v->add_val = *add_val;
5444   v->benefit = first_benefit;
5445   v->cant_derive = 0;
5446   v->derive_adjustment = 0;
5447
5448   reg_iv_type[REGNO (dest_reg)] = GENERAL_INDUCT;
5449   reg_iv_info[REGNO (dest_reg)] = v;
5450
5451   count = n_times_set[REGNO (dest_reg)] - 1;
5452
5453   while (count > 0)
5454     {
5455       p = NEXT_INSN (p);
5456       code = GET_CODE (p);
5457
5458       /* If libcall, skip to end of call sequence.  */
5459       if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
5460         p = XEXP (temp, 0);
5461
5462       if (code == INSN
5463           && (set = single_set (p))
5464           && GET_CODE (SET_DEST (set)) == REG
5465           && SET_DEST (set) == dest_reg
5466           && ((benefit = general_induction_var (SET_SRC (set), &src_reg,
5467                                                 add_val, mult_val))
5468               /* Giv created by equivalent expression.  */
5469               || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
5470                   && (benefit = general_induction_var (XEXP (temp, 0), &src_reg,
5471                                                        add_val, mult_val))))
5472           && src_reg == v->src_reg)
5473         {
5474           if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5475             benefit += libcall_benefit (p);
5476
5477           count--;
5478           v->mult_val = *mult_val;
5479           v->add_val = *add_val;
5480           v->benefit = benefit;
5481         }
5482       else if (code != NOTE)
5483         {
5484           /* Allow insns that set something other than this giv to a
5485              constant.  Such insns are needed on machines which cannot
5486              include long constants and should not disqualify a giv.  */
5487           if (code == INSN
5488               && (set = single_set (p))
5489               && SET_DEST (set) != dest_reg
5490               && CONSTANT_P (SET_SRC (set)))
5491             continue;
5492
5493           reg_iv_type[REGNO (dest_reg)] = UNKNOWN_INDUCT;
5494           return 0;
5495         }
5496     }
5497
5498   return v->benefit;
5499 }
5500 \f
5501 /* Return an rtx, if any, that expresses giv G2 as a function of the register
5502    represented by G1.  If no such expression can be found, or it is clear that
5503    it cannot possibly be a valid address, 0 is returned. 
5504
5505    To perform the computation, we note that
5506         G1 = a * v + b          and
5507         G2 = c * v + d
5508    where `v' is the biv.
5509
5510    So G2 = (c/a) * G1 + (d - b*c/a)  */
5511
5512 #ifdef ADDRESS_COST
5513 static rtx
5514 express_from (g1, g2)
5515      struct induction *g1, *g2;
5516 {
5517   rtx mult, add;
5518
5519   /* The value that G1 will be multiplied by must be a constant integer.  Also,
5520      the only chance we have of getting a valid address is if b*c/a (see above
5521      for notation) is also an integer.  */
5522   if (GET_CODE (g1->mult_val) != CONST_INT
5523       || GET_CODE (g2->mult_val) != CONST_INT
5524       || GET_CODE (g1->add_val) != CONST_INT
5525       || g1->mult_val == const0_rtx
5526       || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
5527     return 0;
5528
5529   mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
5530   add = plus_constant (g2->add_val, - INTVAL (g1->add_val) * INTVAL (mult));
5531
5532   /* Form simplified final result.  */
5533   if (mult == const0_rtx)
5534     return add;
5535   else if (mult == const1_rtx)
5536     mult = g1->dest_reg;
5537   else
5538     mult = gen_rtx (MULT, g2->mode, g1->dest_reg, mult);
5539
5540   if (add == const0_rtx)
5541     return mult;
5542   else
5543     return gen_rtx (PLUS, g2->mode, mult, add);
5544 }
5545 #endif
5546 \f
5547 /* Return 1 if giv G2 can be combined with G1.  This means that G2 can use
5548    (either directly or via an address expression) a register used to represent
5549    G1.  Set g2->new_reg to a represtation of G1 (normally just
5550    g1->dest_reg).  */
5551
5552 static int
5553 combine_givs_p (g1, g2)
5554      struct induction *g1, *g2;
5555 {
5556   rtx tem;
5557
5558   /* If these givs are identical, they can be combined.  */
5559   if (rtx_equal_p (g1->mult_val, g2->mult_val)
5560       && rtx_equal_p (g1->add_val, g2->add_val))
5561     {
5562       g2->new_reg = g1->dest_reg;
5563       return 1;
5564     }
5565
5566 #ifdef ADDRESS_COST
5567   /* If G2 can be expressed as a function of G1 and that function is valid
5568      as an address and no more expensive than using a register for G2,
5569      the expression of G2 in terms of G1 can be used.  */
5570   if (g2->giv_type == DEST_ADDR
5571       && (tem = express_from (g1, g2)) != 0
5572       && memory_address_p (g2->mem_mode, tem)
5573       && ADDRESS_COST (tem) <= ADDRESS_COST (*g2->location))
5574     {
5575       g2->new_reg = tem;
5576       return 1;
5577     }
5578 #endif
5579
5580   return 0;
5581 }
5582 \f
5583 #ifdef GIV_SORT_CRITERION
5584 /* Compare two givs and sort the most desirable one for combinations first.
5585    This is used only in one qsort call below.  */
5586
5587 static int
5588 giv_sort (x, y)
5589      struct induction **x, **y;
5590 {
5591   GIV_SORT_CRITERION (*x, *y);
5592
5593   return 0;
5594 }
5595 #endif
5596
5597 /* Check all pairs of givs for iv_class BL and see if any can be combined with
5598    any other.  If so, point SAME to the giv combined with and set NEW_REG to
5599    be an expression (in terms of the other giv's DEST_REG) equivalent to the
5600    giv.  Also, update BENEFIT and related fields for cost/benefit analysis.  */
5601
5602 static void
5603 combine_givs (bl)
5604      struct iv_class *bl;
5605 {
5606   struct induction *g1, *g2, **giv_array, *temp_iv;
5607   int i, j, giv_count, pass;
5608
5609   /* Count givs, because bl->giv_count is incorrect here.  */
5610   giv_count = 0;
5611   for (g1 = bl->giv; g1; g1 = g1->next_iv)
5612     giv_count++;
5613
5614   giv_array
5615     = (struct induction **) alloca (giv_count * sizeof (struct induction *));
5616   i = 0;
5617   for (g1 = bl->giv; g1; g1 = g1->next_iv)
5618     giv_array[i++] = g1;
5619
5620 #ifdef GIV_SORT_CRITERION
5621   /* Sort the givs if GIV_SORT_CRITERION is defined.
5622      This is usually defined for processors which lack
5623      negative register offsets so more givs may be combined.  */
5624
5625   if (loop_dump_stream)
5626     fprintf (loop_dump_stream, "%d givs counted, sorting...\n", giv_count);
5627
5628   qsort (giv_array, giv_count, sizeof (struct induction *), giv_sort);
5629 #endif
5630
5631   for (i = 0; i < giv_count; i++)
5632     {
5633       g1 = giv_array[i];
5634       for (pass = 0; pass <= 1; pass++)
5635         for (j = 0; j < giv_count; j++)
5636           {
5637             g2 = giv_array[j];
5638             if (g1 != g2
5639                 /* First try to combine with replaceable givs, then all givs. */
5640                 && (g1->replaceable || pass == 1)
5641                 /* If either has already been combined or is to be ignored, can't
5642                    combine.  */
5643                 && ! g1->ignore && ! g2->ignore && ! g1->same && ! g2->same
5644                 /* If something has been based on G2, G2 cannot itself be based
5645                    on something else.  */
5646                 && ! g2->combined_with
5647                 && combine_givs_p (g1, g2))
5648               {
5649                 /* g2->new_reg set by `combine_givs_p'  */
5650                 g2->same = g1;
5651                 g1->combined_with = 1;
5652                 g1->benefit += g2->benefit;
5653                 /* ??? The new final_[bg]iv_value code does a much better job
5654                    of finding replaceable giv's, and hence this code may no
5655                    longer be necessary.  */
5656                 if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
5657                   g1->benefit -= copy_cost;
5658                 g1->lifetime += g2->lifetime;
5659                 g1->times_used += g2->times_used;
5660                 
5661                 if (loop_dump_stream)
5662                   fprintf (loop_dump_stream, "giv at %d combined with giv at %d\n",
5663                            INSN_UID (g2->insn), INSN_UID (g1->insn));
5664               }
5665           }
5666     }
5667 }
5668 \f
5669 /* EMIT code before INSERT_BEFORE to set REG = B * M + A.  */
5670
5671 void
5672 emit_iv_add_mult (b, m, a, reg, insert_before)
5673      rtx b;          /* initial value of basic induction variable */
5674      rtx m;          /* multiplicative constant */
5675      rtx a;          /* additive constant */
5676      rtx reg;        /* destination register */
5677      rtx insert_before;
5678 {
5679   rtx seq;
5680   rtx result;
5681
5682   /* Prevent unexpected sharing of these rtx.  */
5683   a = copy_rtx (a);
5684   b = copy_rtx (b);
5685
5686   /* Increase the lifetime of any invariants moved further in code. */
5687   update_reg_last_use (a, insert_before);
5688   update_reg_last_use (b, insert_before);
5689   update_reg_last_use (m, insert_before);
5690
5691   start_sequence ();
5692   result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 0);
5693   if (reg != result)
5694     emit_move_insn (reg, result);
5695   seq = gen_sequence ();
5696   end_sequence ();
5697
5698   emit_insn_before (seq, insert_before);
5699 }
5700 \f
5701 /* Test whether A * B can be computed without
5702    an actual multiply insn.  Value is 1 if so.  */
5703
5704 static int
5705 product_cheap_p (a, b)
5706      rtx a;
5707      rtx b;
5708 {
5709   int i;
5710   rtx tmp;
5711   struct obstack *old_rtl_obstack = rtl_obstack;
5712   char *storage = (char *) obstack_alloc (&temp_obstack, 0);
5713   int win = 1;
5714
5715   /* If only one is constant, make it B. */
5716   if (GET_CODE (a) == CONST_INT)
5717     tmp = a, a = b, b = tmp;
5718
5719   /* If first constant, both constant, so don't need multiply.  */
5720   if (GET_CODE (a) == CONST_INT)
5721     return 1;
5722
5723   /* If second not constant, neither is constant, so would need multiply.  */
5724   if (GET_CODE (b) != CONST_INT)
5725     return 0;
5726
5727   /* One operand is constant, so might not need multiply insn.  Generate the
5728      code for the multiply and see if a call or multiply, or long sequence
5729      of insns is generated.  */
5730
5731   rtl_obstack = &temp_obstack;
5732   start_sequence ();
5733   expand_mult (GET_MODE (a), a, b, NULL_RTX, 0);
5734   tmp = gen_sequence ();
5735   end_sequence ();
5736
5737   if (GET_CODE (tmp) == SEQUENCE)
5738     {
5739       if (XVEC (tmp, 0) == 0)
5740         win = 1;
5741       else if (XVECLEN (tmp, 0) > 3)
5742         win = 0;
5743       else
5744         for (i = 0; i < XVECLEN (tmp, 0); i++)
5745           {
5746             rtx insn = XVECEXP (tmp, 0, i);
5747
5748             if (GET_CODE (insn) != INSN
5749                 || (GET_CODE (PATTERN (insn)) == SET
5750                     && GET_CODE (SET_SRC (PATTERN (insn))) == MULT)
5751                 || (GET_CODE (PATTERN (insn)) == PARALLEL
5752                     && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == SET
5753                     && GET_CODE (SET_SRC (XVECEXP (PATTERN (insn), 0, 0))) == MULT))
5754               {
5755                 win = 0;
5756                 break;
5757               }
5758           }
5759     }
5760   else if (GET_CODE (tmp) == SET
5761            && GET_CODE (SET_SRC (tmp)) == MULT)
5762     win = 0;
5763   else if (GET_CODE (tmp) == PARALLEL
5764            && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
5765            && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
5766     win = 0;
5767
5768   /* Free any storage we obtained in generating this multiply and restore rtl
5769      allocation to its normal obstack.  */
5770   obstack_free (&temp_obstack, storage);
5771   rtl_obstack = old_rtl_obstack;
5772
5773   return win;
5774 }
5775 \f
5776 /* Check to see if loop can be terminated by a "decrement and branch until
5777    zero" instruction.  If so, add a REG_NONNEG note to the branch insn if so.
5778    Also try reversing an increment loop to a decrement loop
5779    to see if the optimization can be performed.
5780    Value is nonzero if optimization was performed.  */
5781
5782 /* This is useful even if the architecture doesn't have such an insn,
5783    because it might change a loops which increments from 0 to n to a loop
5784    which decrements from n to 0.  A loop that decrements to zero is usually
5785    faster than one that increments from zero.  */
5786
5787 /* ??? This could be rewritten to use some of the loop unrolling procedures,
5788    such as approx_final_value, biv_total_increment, loop_iterations, and
5789    final_[bg]iv_value.  */
5790
5791 static int
5792 check_dbra_loop (loop_end, insn_count, loop_start)
5793      rtx loop_end;
5794      int insn_count;
5795      rtx loop_start;
5796 {
5797   struct iv_class *bl;
5798   rtx reg;
5799   rtx jump_label;
5800   rtx final_value;
5801   rtx start_value;
5802   rtx new_add_val;
5803   rtx comparison;
5804   rtx before_comparison;
5805   rtx p;
5806
5807   /* If last insn is a conditional branch, and the insn before tests a
5808      register value, try to optimize it.  Otherwise, we can't do anything.  */
5809
5810   comparison = get_condition_for_loop (PREV_INSN (loop_end));
5811   if (comparison == 0)
5812     return 0;
5813
5814   /* Check all of the bivs to see if the compare uses one of them.
5815      Skip biv's set more than once because we can't guarantee that
5816      it will be zero on the last iteration.  Also skip if the biv is
5817      used between its update and the test insn.  */
5818
5819   for (bl = loop_iv_list; bl; bl = bl->next)
5820     {
5821       if (bl->biv_count == 1
5822           && bl->biv->dest_reg == XEXP (comparison, 0)
5823           && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
5824                                    PREV_INSN (PREV_INSN (loop_end))))
5825         break;
5826     }
5827
5828   if (! bl)
5829     return 0;
5830
5831   /* Look for the case where the basic induction variable is always
5832      nonnegative, and equals zero on the last iteration.
5833      In this case, add a reg_note REG_NONNEG, which allows the
5834      m68k DBRA instruction to be used.  */
5835
5836   if (((GET_CODE (comparison) == GT
5837         && GET_CODE (XEXP (comparison, 1)) == CONST_INT
5838         && INTVAL (XEXP (comparison, 1)) == -1)
5839        || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
5840       && GET_CODE (bl->biv->add_val) == CONST_INT
5841       && INTVAL (bl->biv->add_val) < 0)
5842     {
5843       /* Initial value must be greater than 0,
5844          init_val % -dec_value == 0 to ensure that it equals zero on
5845          the last iteration */
5846
5847       if (GET_CODE (bl->initial_value) == CONST_INT
5848           && INTVAL (bl->initial_value) > 0
5849           && (INTVAL (bl->initial_value) %
5850               (-INTVAL (bl->biv->add_val))) == 0)
5851         {
5852           /* register always nonnegative, add REG_NOTE to branch */
5853           REG_NOTES (PREV_INSN (loop_end))
5854             = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
5855                        REG_NOTES (PREV_INSN (loop_end)));
5856           bl->nonneg = 1;
5857
5858           return 1;
5859         }
5860
5861       /* If the decrement is 1 and the value was tested as >= 0 before
5862          the loop, then we can safely optimize.  */
5863       for (p = loop_start; p; p = PREV_INSN (p))
5864         {
5865           if (GET_CODE (p) == CODE_LABEL)
5866             break;
5867           if (GET_CODE (p) != JUMP_INSN)
5868             continue;
5869
5870           before_comparison = get_condition_for_loop (p);
5871           if (before_comparison
5872               && XEXP (before_comparison, 0) == bl->biv->dest_reg
5873               && GET_CODE (before_comparison) == LT
5874               && XEXP (before_comparison, 1) == const0_rtx
5875               && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
5876               && INTVAL (bl->biv->add_val) == -1)
5877             {
5878               REG_NOTES (PREV_INSN (loop_end))
5879                 = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
5880                            REG_NOTES (PREV_INSN (loop_end)));
5881               bl->nonneg = 1;
5882
5883               return 1;
5884             }
5885         }
5886     }
5887   else if (num_mem_sets <= 1)
5888     {
5889       /* Try to change inc to dec, so can apply above optimization.  */
5890       /* Can do this if:
5891          all registers modified are induction variables or invariant,
5892          all memory references have non-overlapping addresses
5893          (obviously true if only one write)
5894          allow 2 insns for the compare/jump at the end of the loop.  */
5895       /* Also, we must avoid any instructions which use both the reversed
5896          biv and another biv.  Such instructions will fail if the loop is
5897          reversed.  We meet this condition by requiring that either
5898          no_use_except_counting is true, or else that there is only
5899          one biv.  */
5900       int num_nonfixed_reads = 0;
5901       /* 1 if the iteration var is used only to count iterations.  */
5902       int no_use_except_counting = 0;
5903       /* 1 if the loop has no memory store, or it has a single memory store
5904          which is reversible.  */
5905       int reversible_mem_store = 1;
5906
5907       for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
5908         if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
5909           num_nonfixed_reads += count_nonfixed_reads (PATTERN (p));
5910
5911       if (bl->giv_count == 0
5912           && ! loop_number_exit_count[uid_loop_num[INSN_UID (loop_start)]])
5913         {
5914           rtx bivreg = regno_reg_rtx[bl->regno];
5915
5916           /* If there are no givs for this biv, and the only exit is the
5917              fall through at the end of the the loop, then
5918              see if perhaps there are no uses except to count.  */
5919           no_use_except_counting = 1;
5920           for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
5921             if (GET_RTX_CLASS (GET_CODE (p)) == 'i')
5922               {
5923                 rtx set = single_set (p);
5924
5925                 if (set && GET_CODE (SET_DEST (set)) == REG
5926                     && REGNO (SET_DEST (set)) == bl->regno)
5927                   /* An insn that sets the biv is okay.  */
5928                   ;
5929                 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
5930                          || p == prev_nonnote_insn (loop_end))
5931                   /* Don't bother about the end test.  */
5932                   ;
5933                 else if (reg_mentioned_p (bivreg, PATTERN (p)))
5934                   /* Any other use of the biv is no good.  */
5935                   {
5936                     no_use_except_counting = 0;
5937                     break;
5938                   }
5939               }
5940         }
5941
5942       /* If the loop has a single store, and the destination address is
5943          invariant, then we can't reverse the loop, because this address
5944          might then have the wrong value at loop exit.
5945          This would work if the source was invariant also, however, in that
5946          case, the insn should have been moved out of the loop.  */
5947
5948       if (num_mem_sets == 1)
5949         reversible_mem_store
5950           = (! unknown_address_altered
5951              && ! invariant_p (XEXP (loop_store_mems[0], 0)));
5952
5953       /* This code only acts for innermost loops.  Also it simplifies
5954          the memory address check by only reversing loops with
5955          zero or one memory access.
5956          Two memory accesses could involve parts of the same array,
5957          and that can't be reversed.  */
5958
5959       if (num_nonfixed_reads <= 1
5960           && !loop_has_call
5961           && !loop_has_volatile
5962           && reversible_mem_store
5963           && (no_use_except_counting
5964               || ((bl->giv_count + bl->biv_count + num_mem_sets
5965                    + num_movables + 2 == insn_count)
5966                   && (bl == loop_iv_list && bl->next == 0))))
5967         {
5968           rtx tem;
5969
5970           /* Loop can be reversed.  */
5971           if (loop_dump_stream)
5972             fprintf (loop_dump_stream, "Can reverse loop\n");
5973
5974           /* Now check other conditions:
5975              initial_value must be zero,
5976              final_value % add_val == 0, so that when reversed, the
5977              biv will be zero on the last iteration.
5978
5979              This test can probably be improved since +/- 1 in the constant
5980              can be obtained by changing LT to LE and vice versa; this is
5981              confusing.  */
5982
5983           if (comparison && bl->initial_value == const0_rtx
5984               && GET_CODE (XEXP (comparison, 1)) == CONST_INT
5985               /* LE gets turned into LT */
5986               && GET_CODE (comparison) == LT
5987               && (INTVAL (XEXP (comparison, 1))
5988                   % INTVAL (bl->biv->add_val)) == 0)
5989             {
5990               /* Register will always be nonnegative, with value
5991                  0 on last iteration if loop reversed */
5992
5993               /* Save some info needed to produce the new insns.  */
5994               reg = bl->biv->dest_reg;
5995               jump_label = XEXP (SET_SRC (PATTERN (PREV_INSN (loop_end))), 1);
5996               new_add_val = GEN_INT (- INTVAL (bl->biv->add_val));
5997
5998               final_value = XEXP (comparison, 1);
5999               start_value = GEN_INT (INTVAL (XEXP (comparison, 1))
6000                                      - INTVAL (bl->biv->add_val));
6001
6002               /* Initialize biv to start_value before loop start.
6003                  The old initializing insn will be deleted as a
6004                  dead store by flow.c.  */
6005               emit_insn_before (gen_move_insn (reg, start_value), loop_start);
6006
6007               /* Add insn to decrement register, and delete insn
6008                  that incremented the register.  */
6009               p = emit_insn_before (gen_add2_insn (reg, new_add_val),
6010                                     bl->biv->insn);
6011               delete_insn (bl->biv->insn);
6012                       
6013               /* Update biv info to reflect its new status.  */
6014               bl->biv->insn = p;
6015               bl->initial_value = start_value;
6016               bl->biv->add_val = new_add_val;
6017
6018               /* Inc LABEL_NUSES so that delete_insn will
6019                  not delete the label.  */
6020               LABEL_NUSES (XEXP (jump_label, 0)) ++;
6021
6022               /* Emit an insn after the end of the loop to set the biv's
6023                  proper exit value if it is used anywhere outside the loop.  */
6024               if ((regno_last_uid[bl->regno]
6025                    != INSN_UID (PREV_INSN (PREV_INSN (loop_end))))
6026                   || ! bl->init_insn
6027                   || regno_first_uid[bl->regno] != INSN_UID (bl->init_insn))
6028                 emit_insn_after (gen_move_insn (reg, final_value),
6029                                  loop_end);
6030
6031               /* Delete compare/branch at end of loop.  */
6032               delete_insn (PREV_INSN (loop_end));
6033               delete_insn (PREV_INSN (loop_end));
6034
6035               /* Add new compare/branch insn at end of loop.  */
6036               start_sequence ();
6037               emit_cmp_insn (reg, const0_rtx, GE, NULL_RTX,
6038                              GET_MODE (reg), 0, 0);
6039               emit_jump_insn (gen_bge (XEXP (jump_label, 0)));
6040               tem = gen_sequence ();
6041               end_sequence ();
6042               emit_jump_insn_before (tem, loop_end);
6043
6044               for (tem = PREV_INSN (loop_end);
6045                    tem && GET_CODE (tem) != JUMP_INSN; tem = PREV_INSN (tem))
6046                 ;
6047               if (tem)
6048                 {
6049                   JUMP_LABEL (tem) = XEXP (jump_label, 0);
6050
6051                   /* Increment of LABEL_NUSES done above. */
6052                   /* Register is now always nonnegative,
6053                      so add REG_NONNEG note to the branch.  */
6054                   REG_NOTES (tem) = gen_rtx (EXPR_LIST, REG_NONNEG, NULL_RTX,
6055                                              REG_NOTES (tem));
6056                 }
6057
6058               bl->nonneg = 1;
6059
6060               /* Mark that this biv has been reversed.  Each giv which depends
6061                  on this biv, and which is also live past the end of the loop
6062                  will have to be fixed up.  */
6063
6064               bl->reversed = 1;
6065
6066               if (loop_dump_stream)
6067                 fprintf (loop_dump_stream,
6068                          "Reversed loop and added reg_nonneg\n");
6069
6070               return 1;
6071             }
6072         }
6073     }
6074
6075   return 0;
6076 }
6077 \f
6078 /* Verify whether the biv BL appears to be eliminable,
6079    based on the insns in the loop that refer to it.
6080    LOOP_START is the first insn of the loop, and END is the end insn.
6081
6082    If ELIMINATE_P is non-zero, actually do the elimination.
6083
6084    THRESHOLD and INSN_COUNT are from loop_optimize and are used to
6085    determine whether invariant insns should be placed inside or at the
6086    start of the loop.  */
6087
6088 static int
6089 maybe_eliminate_biv (bl, loop_start, end, eliminate_p, threshold, insn_count)
6090      struct iv_class *bl;
6091      rtx loop_start;
6092      rtx end;
6093      int eliminate_p;
6094      int threshold, insn_count;
6095 {
6096   rtx reg = bl->biv->dest_reg;
6097   rtx p;
6098
6099   /* Scan all insns in the loop, stopping if we find one that uses the
6100      biv in a way that we cannot eliminate.  */
6101
6102   for (p = loop_start; p != end; p = NEXT_INSN (p))
6103     {
6104       enum rtx_code code = GET_CODE (p);
6105       rtx where = threshold >= insn_count ? loop_start : p;
6106
6107       if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
6108           && reg_mentioned_p (reg, PATTERN (p))
6109           && ! maybe_eliminate_biv_1 (PATTERN (p), p, bl, eliminate_p, where))
6110         {
6111           if (loop_dump_stream)
6112             fprintf (loop_dump_stream,
6113                      "Cannot eliminate biv %d: biv used in insn %d.\n",
6114                      bl->regno, INSN_UID (p));
6115           break;
6116         }
6117     }
6118
6119   if (p == end)
6120     {
6121       if (loop_dump_stream)
6122         fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
6123                  bl->regno, eliminate_p ? "was" : "can be");
6124       return 1;
6125     }
6126
6127   return 0;
6128 }
6129 \f
6130 /* If BL appears in X (part of the pattern of INSN), see if we can
6131    eliminate its use.  If so, return 1.  If not, return 0.
6132
6133    If BIV does not appear in X, return 1.
6134
6135    If ELIMINATE_P is non-zero, actually do the elimination.  WHERE indicates
6136    where extra insns should be added.  Depending on how many items have been
6137    moved out of the loop, it will either be before INSN or at the start of
6138    the loop.  */
6139
6140 static int
6141 maybe_eliminate_biv_1 (x, insn, bl, eliminate_p, where)
6142      rtx x, insn;
6143      struct iv_class *bl;
6144      int eliminate_p;
6145      rtx where;
6146 {
6147   enum rtx_code code = GET_CODE (x);
6148   rtx reg = bl->biv->dest_reg;
6149   enum machine_mode mode = GET_MODE (reg);
6150   struct induction *v;
6151   rtx arg, new, tem;
6152   int arg_operand;
6153   char *fmt;
6154   int i, j;
6155
6156   switch (code)
6157     {
6158     case REG:
6159       /* If we haven't already been able to do something with this BIV,
6160          we can't eliminate it.  */
6161       if (x == reg)
6162         return 0;
6163       return 1;
6164
6165     case SET:
6166       /* If this sets the BIV, it is not a problem.  */
6167       if (SET_DEST (x) == reg)
6168         return 1;
6169
6170       /* If this is an insn that defines a giv, it is also ok because
6171          it will go away when the giv is reduced.  */
6172       for (v = bl->giv; v; v = v->next_iv)
6173         if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
6174           return 1;
6175
6176 #ifdef HAVE_cc0
6177       if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
6178         {
6179           /* Can replace with any giv that was reduced and
6180              that has (MULT_VAL != 0) and (ADD_VAL == 0).
6181              Require a constant for MULT_VAL, so we know it's nonzero.
6182              ??? We disable this optimization to avoid potential
6183              overflows.  */
6184
6185           for (v = bl->giv; v; v = v->next_iv)
6186             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
6187                 && v->add_val == const0_rtx
6188                 && ! v->ignore && ! v->maybe_dead && v->always_computable
6189                 && v->mode == mode
6190                 && 0)
6191               {
6192                 /* If the giv V had the auto-inc address optimization applied
6193                    to it, and INSN occurs between the giv insn and the biv
6194                    insn, then we must adjust the value used here.
6195                    This is rare, so we don't bother to do so.  */
6196                 if (v->auto_inc_opt
6197                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6198                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6199                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
6200                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6201                   continue;
6202
6203                 if (! eliminate_p)
6204                   return 1;
6205
6206                 /* If the giv has the opposite direction of change,
6207                    then reverse the comparison.  */
6208                 if (INTVAL (v->mult_val) < 0)
6209                   new = gen_rtx (COMPARE, GET_MODE (v->new_reg),
6210                                  const0_rtx, v->new_reg);
6211                 else
6212                   new = v->new_reg;
6213
6214                 /* We can probably test that giv's reduced reg.  */
6215                 if (validate_change (insn, &SET_SRC (x), new, 0))
6216                   return 1;
6217               }
6218
6219           /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
6220              replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
6221              Require a constant for MULT_VAL, so we know it's nonzero.
6222              ??? Do this only if ADD_VAL is a pointer to avoid a potential
6223              overflow problem.  */
6224
6225           for (v = bl->giv; v; v = v->next_iv)
6226             if (CONSTANT_P (v->mult_val) && v->mult_val != const0_rtx
6227                 && ! v->ignore && ! v->maybe_dead && v->always_computable
6228                 && v->mode == mode
6229                 && (GET_CODE (v->add_val) == SYMBOL_REF
6230                     || GET_CODE (v->add_val) == LABEL_REF
6231                     || GET_CODE (v->add_val) == CONST
6232                     || (GET_CODE (v->add_val) == REG
6233                         && REGNO_POINTER_FLAG (REGNO (v->add_val)))))
6234               {
6235                 /* If the giv V had the auto-inc address optimization applied
6236                    to it, and INSN occurs between the giv insn and the biv
6237                    insn, then we must adjust the value used here.
6238                    This is rare, so we don't bother to do so.  */
6239                 if (v->auto_inc_opt
6240                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6241                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6242                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
6243                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6244                   continue;
6245
6246                 if (! eliminate_p)
6247                   return 1;
6248
6249                 /* If the giv has the opposite direction of change,
6250                    then reverse the comparison.  */
6251                 if (INTVAL (v->mult_val) < 0)
6252                   new = gen_rtx (COMPARE, VOIDmode, copy_rtx (v->add_val),
6253                                  v->new_reg);
6254                 else
6255                   new = gen_rtx (COMPARE, VOIDmode, v->new_reg,
6256                                  copy_rtx (v->add_val));
6257
6258                 /* Replace biv with the giv's reduced register.  */
6259                 update_reg_last_use (v->add_val, insn);
6260                 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
6261                   return 1;
6262
6263                 /* Insn doesn't support that constant or invariant.  Copy it
6264                    into a register (it will be a loop invariant.)  */
6265                 tem = gen_reg_rtx (GET_MODE (v->new_reg));
6266
6267                 emit_insn_before (gen_move_insn (tem, copy_rtx (v->add_val)),
6268                                   where);
6269
6270                 if (validate_change (insn, &SET_SRC (PATTERN (insn)),
6271                                      gen_rtx (COMPARE, VOIDmode,
6272                                               v->new_reg, tem), 0))
6273                   return 1;
6274               }
6275         }
6276 #endif
6277       break;
6278
6279     case COMPARE:
6280     case EQ:  case NE:
6281     case GT:  case GE:  case GTU:  case GEU:
6282     case LT:  case LE:  case LTU:  case LEU:
6283       /* See if either argument is the biv.  */
6284       if (XEXP (x, 0) == reg)
6285         arg = XEXP (x, 1), arg_operand = 1;
6286       else if (XEXP (x, 1) == reg)
6287         arg = XEXP (x, 0), arg_operand = 0;
6288       else
6289         break;
6290
6291       if (CONSTANT_P (arg))
6292         {
6293           /* First try to replace with any giv that has constant positive
6294              mult_val and constant add_val.  We might be able to support
6295              negative mult_val, but it seems complex to do it in general.  */
6296
6297           for (v = bl->giv; v; v = v->next_iv)
6298             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
6299                 && (GET_CODE (v->add_val) == SYMBOL_REF
6300                     || GET_CODE (v->add_val) == LABEL_REF
6301                     || GET_CODE (v->add_val) == CONST
6302                     || (GET_CODE (v->add_val) == REG
6303                         && REGNO_POINTER_FLAG (REGNO (v->add_val))))
6304                 && ! v->ignore && ! v->maybe_dead && v->always_computable
6305                 && v->mode == mode)
6306               {
6307                 /* If the giv V had the auto-inc address optimization applied
6308                    to it, and INSN occurs between the giv insn and the biv
6309                    insn, then we must adjust the value used here.
6310                    This is rare, so we don't bother to do so.  */
6311                 if (v->auto_inc_opt
6312                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6313                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6314                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
6315                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6316                   continue;
6317
6318                 if (! eliminate_p)
6319                   return 1;
6320
6321                 /* Replace biv with the giv's reduced reg.  */
6322                 XEXP (x, 1-arg_operand) = v->new_reg;
6323
6324                 /* If all constants are actually constant integers and
6325                    the derived constant can be directly placed in the COMPARE,
6326                    do so.  */
6327                 if (GET_CODE (arg) == CONST_INT
6328                     && GET_CODE (v->mult_val) == CONST_INT
6329                     && GET_CODE (v->add_val) == CONST_INT
6330                     && validate_change (insn, &XEXP (x, arg_operand),
6331                                         GEN_INT (INTVAL (arg)
6332                                                  * INTVAL (v->mult_val)
6333                                                  + INTVAL (v->add_val)), 0))
6334                   return 1;
6335
6336                 /* Otherwise, load it into a register.  */
6337                 tem = gen_reg_rtx (mode);
6338                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
6339                 if (validate_change (insn, &XEXP (x, arg_operand), tem, 0))
6340                   return 1;
6341
6342                 /* If that failed, put back the change we made above.  */
6343                 XEXP (x, 1-arg_operand) = reg;
6344               }
6345           
6346           /* Look for giv with positive constant mult_val and nonconst add_val.
6347              Insert insns to calculate new compare value.  
6348              ??? Turn this off due to possible overflow.  */
6349
6350           for (v = bl->giv; v; v = v->next_iv)
6351             if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
6352                 && ! v->ignore && ! v->maybe_dead && v->always_computable
6353                 && v->mode == mode
6354                 && 0)
6355               {
6356                 rtx tem;
6357
6358                 /* If the giv V had the auto-inc address optimization applied
6359                    to it, and INSN occurs between the giv insn and the biv
6360                    insn, then we must adjust the value used here.
6361                    This is rare, so we don't bother to do so.  */
6362                 if (v->auto_inc_opt
6363                     && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6364                          && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6365                         || (INSN_LUID (v->insn) > INSN_LUID (insn)
6366                             && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6367                   continue;
6368
6369                 if (! eliminate_p)
6370                   return 1;
6371
6372                 tem = gen_reg_rtx (mode);
6373
6374                 /* Replace biv with giv's reduced register.  */
6375                 validate_change (insn, &XEXP (x, 1 - arg_operand),
6376                                  v->new_reg, 1);
6377
6378                 /* Compute value to compare against.  */
6379                 emit_iv_add_mult (arg, v->mult_val, v->add_val, tem, where);
6380                 /* Use it in this insn.  */
6381                 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
6382                 if (apply_change_group ())
6383                   return 1;
6384               }
6385         }
6386       else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
6387         {
6388           if (invariant_p (arg) == 1)
6389             {
6390               /* Look for giv with constant positive mult_val and nonconst
6391                  add_val. Insert insns to compute new compare value. 
6392                  ??? Turn this off due to possible overflow.  */
6393
6394               for (v = bl->giv; v; v = v->next_iv)
6395                 if (CONSTANT_P (v->mult_val) && INTVAL (v->mult_val) > 0
6396                     && ! v->ignore && ! v->maybe_dead && v->always_computable
6397                     && v->mode == mode
6398                     && 0)
6399                   {
6400                     rtx tem;
6401
6402                     /* If the giv V had the auto-inc address optimization applied
6403                        to it, and INSN occurs between the giv insn and the biv
6404                        insn, then we must adjust the value used here.
6405                        This is rare, so we don't bother to do so.  */
6406                     if (v->auto_inc_opt
6407                         && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6408                              && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6409                             || (INSN_LUID (v->insn) > INSN_LUID (insn)
6410                                 && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6411                       continue;
6412
6413                     if (! eliminate_p)
6414                       return 1;
6415
6416                     tem = gen_reg_rtx (mode);
6417
6418                     /* Replace biv with giv's reduced register.  */
6419                     validate_change (insn, &XEXP (x, 1 - arg_operand),
6420                                      v->new_reg, 1);
6421
6422                     /* Compute value to compare against.  */
6423                     emit_iv_add_mult (arg, v->mult_val, v->add_val,
6424                                       tem, where);
6425                     validate_change (insn, &XEXP (x, arg_operand), tem, 1);
6426                     if (apply_change_group ())
6427                       return 1;
6428                   }
6429             }
6430
6431           /* This code has problems.  Basically, you can't know when
6432              seeing if we will eliminate BL, whether a particular giv
6433              of ARG will be reduced.  If it isn't going to be reduced,
6434              we can't eliminate BL.  We can try forcing it to be reduced,
6435              but that can generate poor code.
6436
6437              The problem is that the benefit of reducing TV, below should
6438              be increased if BL can actually be eliminated, but this means
6439              we might have to do a topological sort of the order in which
6440              we try to process biv.  It doesn't seem worthwhile to do
6441              this sort of thing now.  */
6442
6443 #if 0
6444           /* Otherwise the reg compared with had better be a biv.  */
6445           if (GET_CODE (arg) != REG
6446               || reg_iv_type[REGNO (arg)] != BASIC_INDUCT)
6447             return 0;
6448
6449           /* Look for a pair of givs, one for each biv,
6450              with identical coefficients.  */
6451           for (v = bl->giv; v; v = v->next_iv)
6452             {
6453               struct induction *tv;
6454
6455               if (v->ignore || v->maybe_dead || v->mode != mode)
6456                 continue;
6457
6458               for (tv = reg_biv_class[REGNO (arg)]->giv; tv; tv = tv->next_iv)
6459                 if (! tv->ignore && ! tv->maybe_dead
6460                     && rtx_equal_p (tv->mult_val, v->mult_val)
6461                     && rtx_equal_p (tv->add_val, v->add_val)
6462                     && tv->mode == mode)
6463                   {
6464                     /* If the giv V had the auto-inc address optimization applied
6465                        to it, and INSN occurs between the giv insn and the biv
6466                        insn, then we must adjust the value used here.
6467                        This is rare, so we don't bother to do so.  */
6468                     if (v->auto_inc_opt
6469                         && ((INSN_LUID (v->insn) < INSN_LUID (insn)
6470                              && INSN_LUID (insn) < INSN_LUID (bl->biv->insn))
6471                             || (INSN_LUID (v->insn) > INSN_LUID (insn)
6472                                 && INSN_LUID (insn) > INSN_LUID (bl->biv->insn))))
6473                       continue;
6474
6475                     if (! eliminate_p)
6476                       return 1;
6477
6478                     /* Replace biv with its giv's reduced reg.  */
6479                     XEXP (x, 1-arg_operand) = v->new_reg;
6480                     /* Replace other operand with the other giv's
6481                        reduced reg.  */
6482                     XEXP (x, arg_operand) = tv->new_reg;
6483                     return 1;
6484                   }
6485             }
6486 #endif
6487         }
6488
6489       /* If we get here, the biv can't be eliminated.  */
6490       return 0;
6491
6492     case MEM:
6493       /* If this address is a DEST_ADDR giv, it doesn't matter if the
6494          biv is used in it, since it will be replaced.  */
6495       for (v = bl->giv; v; v = v->next_iv)
6496         if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
6497           return 1;
6498       break;
6499     }
6500
6501   /* See if any subexpression fails elimination.  */
6502   fmt = GET_RTX_FORMAT (code);
6503   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
6504     {
6505       switch (fmt[i])
6506         {
6507         case 'e':
6508           if (! maybe_eliminate_biv_1 (XEXP (x, i), insn, bl, 
6509                                        eliminate_p, where))
6510             return 0;
6511           break;
6512
6513         case 'E':
6514           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6515             if (! maybe_eliminate_biv_1 (XVECEXP (x, i, j), insn, bl,
6516                                          eliminate_p, where))
6517               return 0;
6518           break;
6519         }
6520     }
6521
6522   return 1;
6523 }  
6524 \f
6525 /* Return nonzero if the last use of REG
6526    is in an insn following INSN in the same basic block.  */
6527
6528 static int
6529 last_use_this_basic_block (reg, insn)
6530      rtx reg;
6531      rtx insn;
6532 {
6533   rtx n;
6534   for (n = insn;
6535        n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
6536        n = NEXT_INSN (n))
6537     {
6538       if (regno_last_uid[REGNO (reg)] == INSN_UID (n))
6539         return 1;
6540     }
6541   return 0;
6542 }
6543 \f
6544 /* Called via `note_stores' to record the initial value of a biv.  Here we
6545    just record the location of the set and process it later.  */
6546
6547 static void
6548 record_initial (dest, set)
6549      rtx dest;
6550      rtx set;
6551 {
6552   struct iv_class *bl;
6553
6554   if (GET_CODE (dest) != REG
6555       || REGNO (dest) >= max_reg_before_loop
6556       || reg_iv_type[REGNO (dest)] != BASIC_INDUCT)
6557     return;
6558
6559   bl = reg_biv_class[REGNO (dest)];
6560
6561   /* If this is the first set found, record it.  */
6562   if (bl->init_insn == 0)
6563     {
6564       bl->init_insn = note_insn;
6565       bl->init_set = set;
6566     }
6567 }
6568 \f
6569 /* If any of the registers in X are "old" and currently have a last use earlier
6570    than INSN, update them to have a last use of INSN.  Their actual last use
6571    will be the previous insn but it will not have a valid uid_luid so we can't
6572    use it.  */
6573
6574 static void
6575 update_reg_last_use (x, insn)
6576      rtx x;
6577      rtx insn;
6578 {
6579   /* Check for the case where INSN does not have a valid luid.  In this case,
6580      there is no need to modify the regno_last_uid, as this can only happen
6581      when code is inserted after the loop_end to set a pseudo's final value,
6582      and hence this insn will never be the last use of x.  */
6583   if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
6584       && INSN_UID (insn) < max_uid_for_loop
6585       && uid_luid[regno_last_uid[REGNO (x)]] < uid_luid[INSN_UID (insn)])
6586     regno_last_uid[REGNO (x)] = INSN_UID (insn);
6587   else
6588     {
6589       register int i, j;
6590       register char *fmt = GET_RTX_FORMAT (GET_CODE (x));
6591       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
6592         {
6593           if (fmt[i] == 'e')
6594             update_reg_last_use (XEXP (x, i), insn);
6595           else if (fmt[i] == 'E')
6596             for (j = XVECLEN (x, i) - 1; j >= 0; j--)
6597               update_reg_last_use (XVECEXP (x, i, j), insn);
6598         }
6599     }
6600 }
6601 \f
6602 /* Given a jump insn JUMP, return the condition that will cause it to branch
6603    to its JUMP_LABEL.  If the condition cannot be understood, or is an
6604    inequality floating-point comparison which needs to be reversed, 0 will
6605    be returned.
6606
6607    If EARLIEST is non-zero, it is a pointer to a place where the earliest
6608    insn used in locating the condition was found.  If a replacement test
6609    of the condition is desired, it should be placed in front of that
6610    insn and we will be sure that the inputs are still valid.
6611
6612    The condition will be returned in a canonical form to simplify testing by
6613    callers.  Specifically:
6614
6615    (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
6616    (2) Both operands will be machine operands; (cc0) will have been replaced.
6617    (3) If an operand is a constant, it will be the second operand.
6618    (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
6619        for GE, GEU, and LEU.  */
6620
6621 rtx
6622 get_condition (jump, earliest)
6623      rtx jump;
6624      rtx *earliest;
6625 {
6626   enum rtx_code code;
6627   rtx prev = jump;
6628   rtx set;
6629   rtx tem;
6630   rtx op0, op1;
6631   int reverse_code = 0;
6632   int did_reverse_condition = 0;
6633
6634   /* If this is not a standard conditional jump, we can't parse it.  */
6635   if (GET_CODE (jump) != JUMP_INSN
6636       || ! condjump_p (jump) || simplejump_p (jump))
6637     return 0;
6638
6639   code = GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 0));
6640   op0 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 0);
6641   op1 = XEXP (XEXP (SET_SRC (PATTERN (jump)), 0), 1);
6642
6643   if (earliest)
6644     *earliest = jump;
6645
6646   /* If this branches to JUMP_LABEL when the condition is false, reverse
6647      the condition.  */
6648   if (GET_CODE (XEXP (SET_SRC (PATTERN (jump)), 2)) == LABEL_REF
6649       && XEXP (XEXP (SET_SRC (PATTERN (jump)), 2), 0) == JUMP_LABEL (jump))
6650     code = reverse_condition (code), did_reverse_condition ^= 1;
6651
6652   /* If we are comparing a register with zero, see if the register is set
6653      in the previous insn to a COMPARE or a comparison operation.  Perform
6654      the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
6655      in cse.c  */
6656
6657   while (GET_RTX_CLASS (code) == '<' && op1 == CONST0_RTX (GET_MODE (op0)))
6658     {
6659       /* Set non-zero when we find something of interest.  */
6660       rtx x = 0;
6661
6662 #ifdef HAVE_cc0
6663       /* If comparison with cc0, import actual comparison from compare
6664          insn.  */
6665       if (op0 == cc0_rtx)
6666         {
6667           if ((prev = prev_nonnote_insn (prev)) == 0
6668               || GET_CODE (prev) != INSN
6669               || (set = single_set (prev)) == 0
6670               || SET_DEST (set) != cc0_rtx)
6671             return 0;
6672
6673           op0 = SET_SRC (set);
6674           op1 = CONST0_RTX (GET_MODE (op0));
6675           if (earliest)
6676             *earliest = prev;
6677         }
6678 #endif
6679
6680       /* If this is a COMPARE, pick up the two things being compared.  */
6681       if (GET_CODE (op0) == COMPARE)
6682         {
6683           op1 = XEXP (op0, 1);
6684           op0 = XEXP (op0, 0);
6685           continue;
6686         }
6687       else if (GET_CODE (op0) != REG)
6688         break;
6689
6690       /* Go back to the previous insn.  Stop if it is not an INSN.  We also
6691          stop if it isn't a single set or if it has a REG_INC note because
6692          we don't want to bother dealing with it.  */
6693
6694       if ((prev = prev_nonnote_insn (prev)) == 0
6695           || GET_CODE (prev) != INSN
6696           || FIND_REG_INC_NOTE (prev, 0)
6697           || (set = single_set (prev)) == 0)
6698         break;
6699
6700       /* If this is setting OP0, get what it sets it to if it looks
6701          relevant.  */
6702       if (SET_DEST (set) == op0)
6703         {
6704           enum machine_mode inner_mode = GET_MODE (SET_SRC (set));
6705
6706           if ((GET_CODE (SET_SRC (set)) == COMPARE
6707                || (((code == NE
6708                      || (code == LT
6709                          && GET_MODE_CLASS (inner_mode) == MODE_INT
6710                          && (GET_MODE_BITSIZE (inner_mode)
6711                              <= HOST_BITS_PER_WIDE_INT)
6712                          && (STORE_FLAG_VALUE
6713                              & ((HOST_WIDE_INT) 1
6714                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
6715 #ifdef FLOAT_STORE_FLAG_VALUE
6716                      || (code == LT
6717                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
6718                          && FLOAT_STORE_FLAG_VALUE < 0)
6719 #endif
6720                      ))
6721                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<')))
6722             x = SET_SRC (set);
6723           else if (((code == EQ
6724                      || (code == GE
6725                          && (GET_MODE_BITSIZE (inner_mode)
6726                              <= HOST_BITS_PER_WIDE_INT)
6727                          && GET_MODE_CLASS (inner_mode) == MODE_INT
6728                          && (STORE_FLAG_VALUE
6729                              & ((HOST_WIDE_INT) 1
6730                                 << (GET_MODE_BITSIZE (inner_mode) - 1))))
6731 #ifdef FLOAT_STORE_FLAG_VALUE
6732                      || (code == GE
6733                          && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
6734                          && FLOAT_STORE_FLAG_VALUE < 0)
6735 #endif
6736                      ))
6737                    && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<')
6738             {
6739               /* We might have reversed a LT to get a GE here.  But this wasn't
6740                  actually the comparison of data, so we don't flag that we
6741                  have had to reverse the condition.  */
6742               did_reverse_condition ^= 1;
6743               reverse_code = 1;
6744               x = SET_SRC (set);
6745             }
6746           else
6747             break;
6748         }
6749
6750       else if (reg_set_p (op0, prev))
6751         /* If this sets OP0, but not directly, we have to give up.  */
6752         break;
6753
6754       if (x)
6755         {
6756           if (GET_RTX_CLASS (GET_CODE (x)) == '<')
6757             code = GET_CODE (x);
6758           if (reverse_code)
6759             {
6760               code = reverse_condition (code);
6761               did_reverse_condition ^= 1;
6762               reverse_code = 0;
6763             }
6764
6765           op0 = XEXP (x, 0), op1 = XEXP (x, 1);
6766           if (earliest)
6767             *earliest = prev;
6768         }
6769     }
6770
6771   /* If constant is first, put it last.  */
6772   if (CONSTANT_P (op0))
6773     code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
6774
6775   /* If OP0 is the result of a comparison, we weren't able to find what
6776      was really being compared, so fail.  */
6777   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
6778     return 0;
6779
6780   /* Canonicalize any ordered comparison with integers involving equality
6781      if we can do computations in the relevant mode and we do not
6782      overflow.  */
6783
6784   if (GET_CODE (op1) == CONST_INT
6785       && GET_MODE (op0) != VOIDmode
6786       && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
6787     {
6788       HOST_WIDE_INT const_val = INTVAL (op1);
6789       unsigned HOST_WIDE_INT uconst_val = const_val;
6790       unsigned HOST_WIDE_INT max_val
6791         = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
6792
6793       switch (code)
6794         {
6795         case LE:
6796           if (const_val != max_val >> 1)
6797             code = LT,  op1 = GEN_INT (const_val + 1);
6798           break;
6799
6800         case GE:
6801           if (const_val
6802               != (((HOST_WIDE_INT) 1
6803                    << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
6804             code = GT, op1 = GEN_INT (const_val - 1);
6805           break;
6806
6807         case LEU:
6808           if (uconst_val != max_val)
6809             code = LTU, op1 = GEN_INT (uconst_val + 1);
6810           break;
6811
6812         case GEU:
6813           if (uconst_val != 0)
6814             code = GTU, op1 = GEN_INT (uconst_val - 1);
6815           break;
6816         }
6817     }
6818
6819   /* If this was floating-point and we reversed anything other than an
6820      EQ or NE, return zero.  */
6821   if (TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
6822       && did_reverse_condition && code != NE && code != EQ
6823       && ! flag_fast_math
6824       && GET_MODE_CLASS (GET_MODE (op0)) == MODE_FLOAT)
6825     return 0;
6826
6827 #ifdef HAVE_cc0
6828   /* Never return CC0; return zero instead.  */
6829   if (op0 == cc0_rtx)
6830     return 0;
6831 #endif
6832
6833   return gen_rtx (code, VOIDmode, op0, op1);
6834 }
6835
6836 /* Similar to above routine, except that we also put an invariant last
6837    unless both operands are invariants.  */
6838
6839 rtx
6840 get_condition_for_loop (x)
6841      rtx x;
6842 {
6843   rtx comparison = get_condition (x, NULL_PTR);
6844
6845   if (comparison == 0
6846       || ! invariant_p (XEXP (comparison, 0))
6847       || invariant_p (XEXP (comparison, 1)))
6848     return comparison;
6849
6850   return gen_rtx (swap_condition (GET_CODE (comparison)), VOIDmode,
6851                   XEXP (comparison, 1), XEXP (comparison, 0));
6852 }