OSDN Git Service

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