add PR#
[official-gcc.git] / gcc / loop.c
blob737ec89689350990df8866f8199b9553b544a874
1 /* Perform various loop optimizations, including strength reduction.
2 Copyright (C) 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
3 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA. */
22 /* This is the loop optimization pass of the compiler.
23 It finds invariant computations within loops and moves them
24 to the beginning of the loop. Then it identifies basic and
25 general induction variables. Strength reduction is applied to the general
26 induction variables, and induction variable elimination is applied to
27 the basic induction variables.
29 It also finds cases where
30 a register is set within the loop by zero-extending a narrower value
31 and changes these to zero the entire register once before the loop
32 and merely copy the low part within the loop.
34 Most of the complexity is in heuristics to decide when it is worth
35 while to do these things. */
37 #include "config.h"
38 #include "system.h"
39 #include "coretypes.h"
40 #include "tm.h"
41 #include "rtl.h"
42 #include "tm_p.h"
43 #include "function.h"
44 #include "expr.h"
45 #include "hard-reg-set.h"
46 #include "basic-block.h"
47 #include "insn-config.h"
48 #include "regs.h"
49 #include "recog.h"
50 #include "flags.h"
51 #include "real.h"
52 #include "loop.h"
53 #include "cselib.h"
54 #include "except.h"
55 #include "toplev.h"
56 #include "predict.h"
57 #include "insn-flags.h"
58 #include "optabs.h"
59 #include "cfgloop.h"
61 /* Not really meaningful values, but at least something. */
62 #ifndef SIMULTANEOUS_PREFETCHES
63 #define SIMULTANEOUS_PREFETCHES 3
64 #endif
65 #ifndef PREFETCH_BLOCK
66 #define PREFETCH_BLOCK 32
67 #endif
68 #ifndef HAVE_prefetch
69 #define HAVE_prefetch 0
70 #define CODE_FOR_prefetch 0
71 #define gen_prefetch(a,b,c) (abort(), NULL_RTX)
72 #endif
74 /* Give up the prefetch optimizations once we exceed a given threshhold.
75 It is unlikely that we would be able to optimize something in a loop
76 with so many detected prefetches. */
77 #define MAX_PREFETCHES 100
78 /* The number of prefetch blocks that are beneficial to fetch at once before
79 a loop with a known (and low) iteration count. */
80 #define PREFETCH_BLOCKS_BEFORE_LOOP_MAX 6
81 /* For very tiny loops it is not worthwhile to prefetch even before the loop,
82 since it is likely that the data are already in the cache. */
83 #define PREFETCH_BLOCKS_BEFORE_LOOP_MIN 2
85 /* Parameterize some prefetch heuristics so they can be turned on and off
86 easily for performance testing on new architectures. These can be
87 defined in target-dependent files. */
89 /* Prefetch is worthwhile only when loads/stores are dense. */
90 #ifndef PREFETCH_ONLY_DENSE_MEM
91 #define PREFETCH_ONLY_DENSE_MEM 1
92 #endif
94 /* Define what we mean by "dense" loads and stores; This value divided by 256
95 is the minimum percentage of memory references that worth prefetching. */
96 #ifndef PREFETCH_DENSE_MEM
97 #define PREFETCH_DENSE_MEM 220
98 #endif
100 /* Do not prefetch for a loop whose iteration count is known to be low. */
101 #ifndef PREFETCH_NO_LOW_LOOPCNT
102 #define PREFETCH_NO_LOW_LOOPCNT 1
103 #endif
105 /* Define what we mean by a "low" iteration count. */
106 #ifndef PREFETCH_LOW_LOOPCNT
107 #define PREFETCH_LOW_LOOPCNT 32
108 #endif
110 /* Do not prefetch for a loop that contains a function call; such a loop is
111 probably not an internal loop. */
112 #ifndef PREFETCH_NO_CALL
113 #define PREFETCH_NO_CALL 1
114 #endif
116 /* Do not prefetch accesses with an extreme stride. */
117 #ifndef PREFETCH_NO_EXTREME_STRIDE
118 #define PREFETCH_NO_EXTREME_STRIDE 1
119 #endif
121 /* Define what we mean by an "extreme" stride. */
122 #ifndef PREFETCH_EXTREME_STRIDE
123 #define PREFETCH_EXTREME_STRIDE 4096
124 #endif
126 /* Define a limit to how far apart indices can be and still be merged
127 into a single prefetch. */
128 #ifndef PREFETCH_EXTREME_DIFFERENCE
129 #define PREFETCH_EXTREME_DIFFERENCE 4096
130 #endif
132 /* Issue prefetch instructions before the loop to fetch data to be used
133 in the first few loop iterations. */
134 #ifndef PREFETCH_BEFORE_LOOP
135 #define PREFETCH_BEFORE_LOOP 1
136 #endif
138 /* Do not handle reversed order prefetches (negative stride). */
139 #ifndef PREFETCH_NO_REVERSE_ORDER
140 #define PREFETCH_NO_REVERSE_ORDER 1
141 #endif
143 /* Prefetch even if the GIV is in conditional code. */
144 #ifndef PREFETCH_CONDITIONAL
145 #define PREFETCH_CONDITIONAL 1
146 #endif
148 #define LOOP_REG_LIFETIME(LOOP, REGNO) \
149 ((REGNO_LAST_LUID (REGNO) - REGNO_FIRST_LUID (REGNO)))
151 #define LOOP_REG_GLOBAL_P(LOOP, REGNO) \
152 ((REGNO_LAST_LUID (REGNO) > INSN_LUID ((LOOP)->end) \
153 || REGNO_FIRST_LUID (REGNO) < INSN_LUID ((LOOP)->start)))
155 #define LOOP_REGNO_NREGS(REGNO, SET_DEST) \
156 ((REGNO) < FIRST_PSEUDO_REGISTER \
157 ? (int) HARD_REGNO_NREGS ((REGNO), GET_MODE (SET_DEST)) : 1)
160 /* Vector mapping INSN_UIDs to luids.
161 The luids are like uids but increase monotonically always.
162 We use them to see whether a jump comes from outside a given loop. */
164 int *uid_luid;
166 /* Indexed by INSN_UID, contains the ordinal giving the (innermost) loop
167 number the insn is contained in. */
169 struct loop **uid_loop;
171 /* 1 + largest uid of any insn. */
173 int max_uid_for_loop;
175 /* Number of loops detected in current function. Used as index to the
176 next few tables. */
178 static int max_loop_num;
180 /* Bound on pseudo register number before loop optimization.
181 A pseudo has valid regscan info if its number is < max_reg_before_loop. */
182 unsigned int max_reg_before_loop;
184 /* The value to pass to the next call of reg_scan_update. */
185 static int loop_max_reg;
187 /* During the analysis of a loop, a chain of `struct movable's
188 is made to record all the movable insns found.
189 Then the entire chain can be scanned to decide which to move. */
191 struct movable
193 rtx insn; /* A movable insn */
194 rtx set_src; /* The expression this reg is set from. */
195 rtx set_dest; /* The destination of this SET. */
196 rtx dependencies; /* When INSN is libcall, this is an EXPR_LIST
197 of any registers used within the LIBCALL. */
198 int consec; /* Number of consecutive following insns
199 that must be moved with this one. */
200 unsigned int regno; /* The register it sets */
201 short lifetime; /* lifetime of that register;
202 may be adjusted when matching movables
203 that load the same value are found. */
204 short savings; /* Number of insns we can move for this reg,
205 including other movables that force this
206 or match this one. */
207 ENUM_BITFIELD(machine_mode) savemode : 8; /* Nonzero means it is a mode for
208 a low part that we should avoid changing when
209 clearing the rest of the reg. */
210 unsigned int cond : 1; /* 1 if only conditionally movable */
211 unsigned int force : 1; /* 1 means MUST move this insn */
212 unsigned int global : 1; /* 1 means reg is live outside this loop */
213 /* If PARTIAL is 1, GLOBAL means something different:
214 that the reg is live outside the range from where it is set
215 to the following label. */
216 unsigned int done : 1; /* 1 inhibits further processing of this */
218 unsigned int partial : 1; /* 1 means this reg is used for zero-extending.
219 In particular, moving it does not make it
220 invariant. */
221 unsigned int move_insn : 1; /* 1 means that we call emit_move_insn to
222 load SRC, rather than copying INSN. */
223 unsigned int move_insn_first:1;/* Same as above, if this is necessary for the
224 first insn of a consecutive sets group. */
225 unsigned int is_equiv : 1; /* 1 means a REG_EQUIV is present on INSN. */
226 unsigned int insert_temp : 1; /* 1 means we copy to a new pseudo and replace
227 the original insn with a copy from that
228 pseudo, rather than deleting it. */
229 struct movable *match; /* First entry for same value */
230 struct movable *forces; /* An insn that must be moved if this is */
231 struct movable *next;
235 FILE *loop_dump_stream;
237 /* Forward declarations. */
239 static void invalidate_loops_containing_label PARAMS ((rtx));
240 static void find_and_verify_loops PARAMS ((rtx, struct loops *));
241 static void mark_loop_jump PARAMS ((rtx, struct loop *));
242 static void prescan_loop PARAMS ((struct loop *));
243 static int reg_in_basic_block_p PARAMS ((rtx, rtx));
244 static int consec_sets_invariant_p PARAMS ((const struct loop *,
245 rtx, int, rtx));
246 static int labels_in_range_p PARAMS ((rtx, int));
247 static void count_one_set PARAMS ((struct loop_regs *, rtx, rtx, rtx *));
248 static void note_addr_stored PARAMS ((rtx, rtx, void *));
249 static void note_set_pseudo_multiple_uses PARAMS ((rtx, rtx, void *));
250 static int loop_reg_used_before_p PARAMS ((const struct loop *, rtx, rtx));
251 static void scan_loop PARAMS ((struct loop*, int));
252 #if 0
253 static void replace_call_address PARAMS ((rtx, rtx, rtx));
254 #endif
255 static rtx skip_consec_insns PARAMS ((rtx, int));
256 static int libcall_benefit PARAMS ((rtx));
257 static void ignore_some_movables PARAMS ((struct loop_movables *));
258 static void force_movables PARAMS ((struct loop_movables *));
259 static void combine_movables PARAMS ((struct loop_movables *,
260 struct loop_regs *));
261 static int num_unmoved_movables PARAMS ((const struct loop *));
262 static int regs_match_p PARAMS ((rtx, rtx, struct loop_movables *));
263 static int rtx_equal_for_loop_p PARAMS ((rtx, rtx, struct loop_movables *,
264 struct loop_regs *));
265 static void add_label_notes PARAMS ((rtx, rtx));
266 static void move_movables PARAMS ((struct loop *loop, struct loop_movables *,
267 int, int));
268 static void loop_movables_add PARAMS((struct loop_movables *,
269 struct movable *));
270 static void loop_movables_free PARAMS((struct loop_movables *));
271 static int count_nonfixed_reads PARAMS ((const struct loop *, rtx));
272 static void loop_bivs_find PARAMS((struct loop *));
273 static void loop_bivs_init_find PARAMS((struct loop *));
274 static void loop_bivs_check PARAMS((struct loop *));
275 static void loop_givs_find PARAMS((struct loop *));
276 static void loop_givs_check PARAMS((struct loop *));
277 static int loop_biv_eliminable_p PARAMS((struct loop *, struct iv_class *,
278 int, int));
279 static int loop_giv_reduce_benefit PARAMS((struct loop *, struct iv_class *,
280 struct induction *, rtx));
281 static void loop_givs_dead_check PARAMS((struct loop *, struct iv_class *));
282 static void loop_givs_reduce PARAMS((struct loop *, struct iv_class *));
283 static void loop_givs_rescan PARAMS((struct loop *, struct iv_class *,
284 rtx *));
285 static void loop_ivs_free PARAMS((struct loop *));
286 static void strength_reduce PARAMS ((struct loop *, int));
287 static void find_single_use_in_loop PARAMS ((struct loop_regs *, rtx, rtx));
288 static int valid_initial_value_p PARAMS ((rtx, rtx, int, rtx));
289 static void find_mem_givs PARAMS ((const struct loop *, rtx, rtx, int, int));
290 static void record_biv PARAMS ((struct loop *, struct induction *,
291 rtx, rtx, rtx, rtx, rtx *,
292 int, int));
293 static void check_final_value PARAMS ((const struct loop *,
294 struct induction *));
295 static void loop_ivs_dump PARAMS((const struct loop *, FILE *, int));
296 static void loop_iv_class_dump PARAMS((const struct iv_class *, FILE *, int));
297 static void loop_biv_dump PARAMS((const struct induction *, FILE *, int));
298 static void loop_giv_dump PARAMS((const struct induction *, FILE *, int));
299 static void record_giv PARAMS ((const struct loop *, struct induction *,
300 rtx, rtx, rtx, rtx, rtx, rtx, int,
301 enum g_types, int, int, rtx *));
302 static void update_giv_derive PARAMS ((const struct loop *, rtx));
303 static void check_ext_dependent_givs PARAMS ((struct iv_class *,
304 struct loop_info *));
305 static int basic_induction_var PARAMS ((const struct loop *, rtx,
306 enum machine_mode, rtx, rtx,
307 rtx *, rtx *, rtx **));
308 static rtx simplify_giv_expr PARAMS ((const struct loop *, rtx, rtx *, int *));
309 static int general_induction_var PARAMS ((const struct loop *loop, rtx, rtx *,
310 rtx *, rtx *, rtx *, int, int *,
311 enum machine_mode));
312 static int consec_sets_giv PARAMS ((const struct loop *, int, rtx,
313 rtx, rtx, rtx *, rtx *, rtx *, rtx *));
314 static int check_dbra_loop PARAMS ((struct loop *, int));
315 static rtx express_from_1 PARAMS ((rtx, rtx, rtx));
316 static rtx combine_givs_p PARAMS ((struct induction *, struct induction *));
317 static int cmp_combine_givs_stats PARAMS ((const PTR, const PTR));
318 static void combine_givs PARAMS ((struct loop_regs *, struct iv_class *));
319 static int product_cheap_p PARAMS ((rtx, rtx));
320 static int maybe_eliminate_biv PARAMS ((const struct loop *, struct iv_class *,
321 int, int, int));
322 static int maybe_eliminate_biv_1 PARAMS ((const struct loop *, rtx, rtx,
323 struct iv_class *, int,
324 basic_block, rtx));
325 static int last_use_this_basic_block PARAMS ((rtx, rtx));
326 static void record_initial PARAMS ((rtx, rtx, void *));
327 static void update_reg_last_use PARAMS ((rtx, rtx));
328 static rtx next_insn_in_loop PARAMS ((const struct loop *, rtx));
329 static void loop_regs_scan PARAMS ((const struct loop *, int));
330 static int count_insns_in_loop PARAMS ((const struct loop *));
331 static int find_mem_in_note_1 PARAMS ((rtx *, void *));
332 static rtx find_mem_in_note PARAMS ((rtx));
333 static void load_mems PARAMS ((const struct loop *));
334 static int insert_loop_mem PARAMS ((rtx *, void *));
335 static int replace_loop_mem PARAMS ((rtx *, void *));
336 static void replace_loop_mems PARAMS ((rtx, rtx, rtx, int));
337 static int replace_loop_reg PARAMS ((rtx *, void *));
338 static void replace_loop_regs PARAMS ((rtx insn, rtx, rtx));
339 static void note_reg_stored PARAMS ((rtx, rtx, void *));
340 static void try_copy_prop PARAMS ((const struct loop *, rtx, unsigned int));
341 static void try_swap_copy_prop PARAMS ((const struct loop *, rtx,
342 unsigned int));
343 static rtx check_insn_for_givs PARAMS((struct loop *, rtx, int, int));
344 static rtx check_insn_for_bivs PARAMS((struct loop *, rtx, int, int));
345 static rtx gen_add_mult PARAMS ((rtx, rtx, rtx, rtx));
346 static void loop_regs_update PARAMS ((const struct loop *, rtx));
347 static int iv_add_mult_cost PARAMS ((rtx, rtx, rtx, rtx));
349 static rtx loop_insn_emit_after PARAMS((const struct loop *, basic_block,
350 rtx, rtx));
351 static rtx loop_call_insn_emit_before PARAMS((const struct loop *,
352 basic_block, rtx, rtx));
353 static rtx loop_call_insn_hoist PARAMS((const struct loop *, rtx));
354 static rtx loop_insn_sink_or_swim PARAMS((const struct loop *, rtx));
356 static void loop_dump_aux PARAMS ((const struct loop *, FILE *, int));
357 static void loop_delete_insns PARAMS ((rtx, rtx));
358 static HOST_WIDE_INT remove_constant_addition PARAMS ((rtx *));
359 static rtx gen_load_of_final_value PARAMS ((rtx, rtx));
360 void debug_ivs PARAMS ((const struct loop *));
361 void debug_iv_class PARAMS ((const struct iv_class *));
362 void debug_biv PARAMS ((const struct induction *));
363 void debug_giv PARAMS ((const struct induction *));
364 void debug_loop PARAMS ((const struct loop *));
365 void debug_loops PARAMS ((const struct loops *));
367 typedef struct loop_replace_args
369 rtx match;
370 rtx replacement;
371 rtx insn;
372 } loop_replace_args;
374 /* Nonzero iff INSN is between START and END, inclusive. */
375 #define INSN_IN_RANGE_P(INSN, START, END) \
376 (INSN_UID (INSN) < max_uid_for_loop \
377 && INSN_LUID (INSN) >= INSN_LUID (START) \
378 && INSN_LUID (INSN) <= INSN_LUID (END))
380 /* Indirect_jump_in_function is computed once per function. */
381 static int indirect_jump_in_function;
382 static int indirect_jump_in_function_p PARAMS ((rtx));
384 static int compute_luids PARAMS ((rtx, rtx, int));
386 static int biv_elimination_giv_has_0_offset PARAMS ((struct induction *,
387 struct induction *,
388 rtx));
390 /* Benefit penalty, if a giv is not replaceable, i.e. must emit an insn to
391 copy the value of the strength reduced giv to its original register. */
392 static int copy_cost;
394 /* Cost of using a register, to normalize the benefits of a giv. */
395 static int reg_address_cost;
397 void
398 init_loop ()
400 rtx reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
402 reg_address_cost = address_cost (reg, SImode);
404 copy_cost = COSTS_N_INSNS (1);
407 /* Compute the mapping from uids to luids.
408 LUIDs are numbers assigned to insns, like uids,
409 except that luids increase monotonically through the code.
410 Start at insn START and stop just before END. Assign LUIDs
411 starting with PREV_LUID + 1. Return the last assigned LUID + 1. */
412 static int
413 compute_luids (start, end, prev_luid)
414 rtx start, end;
415 int prev_luid;
417 int i;
418 rtx insn;
420 for (insn = start, i = prev_luid; insn != end; insn = NEXT_INSN (insn))
422 if (INSN_UID (insn) >= max_uid_for_loop)
423 continue;
424 /* Don't assign luids to line-number NOTEs, so that the distance in
425 luids between two insns is not affected by -g. */
426 if (GET_CODE (insn) != NOTE
427 || NOTE_LINE_NUMBER (insn) <= 0)
428 uid_luid[INSN_UID (insn)] = ++i;
429 else
430 /* Give a line number note the same luid as preceding insn. */
431 uid_luid[INSN_UID (insn)] = i;
433 return i + 1;
436 /* Entry point of this file. Perform loop optimization
437 on the current function. F is the first insn of the function
438 and DUMPFILE is a stream for output of a trace of actions taken
439 (or 0 if none should be output). */
441 void
442 loop_optimize (f, dumpfile, flags)
443 /* f is the first instruction of a chain of insns for one function */
444 rtx f;
445 FILE *dumpfile;
446 int flags;
448 rtx insn;
449 int i;
450 struct loops loops_data;
451 struct loops *loops = &loops_data;
452 struct loop_info *loops_info;
454 loop_dump_stream = dumpfile;
456 init_recog_no_volatile ();
458 max_reg_before_loop = max_reg_num ();
459 loop_max_reg = max_reg_before_loop;
461 regs_may_share = 0;
463 /* Count the number of loops. */
465 max_loop_num = 0;
466 for (insn = f; insn; insn = NEXT_INSN (insn))
468 if (GET_CODE (insn) == NOTE
469 && NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
470 max_loop_num++;
473 /* Don't waste time if no loops. */
474 if (max_loop_num == 0)
475 return;
477 loops->num = max_loop_num;
479 /* Get size to use for tables indexed by uids.
480 Leave some space for labels allocated by find_and_verify_loops. */
481 max_uid_for_loop = get_max_uid () + 1 + max_loop_num * 32;
483 uid_luid = (int *) xcalloc (max_uid_for_loop, sizeof (int));
484 uid_loop = (struct loop **) xcalloc (max_uid_for_loop,
485 sizeof (struct loop *));
487 /* Allocate storage for array of loops. */
488 loops->array = (struct loop *)
489 xcalloc (loops->num, sizeof (struct loop));
491 /* Find and process each loop.
492 First, find them, and record them in order of their beginnings. */
493 find_and_verify_loops (f, loops);
495 /* Allocate and initialize auxiliary loop information. */
496 loops_info = xcalloc (loops->num, sizeof (struct loop_info));
497 for (i = 0; i < (int) loops->num; i++)
498 loops->array[i].aux = loops_info + i;
500 /* Now find all register lifetimes. This must be done after
501 find_and_verify_loops, because it might reorder the insns in the
502 function. */
503 reg_scan (f, max_reg_before_loop, 1);
505 /* This must occur after reg_scan so that registers created by gcse
506 will have entries in the register tables.
508 We could have added a call to reg_scan after gcse_main in toplev.c,
509 but moving this call to init_alias_analysis is more efficient. */
510 init_alias_analysis ();
512 /* See if we went too far. Note that get_max_uid already returns
513 one more that the maximum uid of all insn. */
514 if (get_max_uid () > max_uid_for_loop)
515 abort ();
516 /* Now reset it to the actual size we need. See above. */
517 max_uid_for_loop = get_max_uid ();
519 /* find_and_verify_loops has already called compute_luids, but it
520 might have rearranged code afterwards, so we need to recompute
521 the luids now. */
522 compute_luids (f, NULL_RTX, 0);
524 /* Don't leave gaps in uid_luid for insns that have been
525 deleted. It is possible that the first or last insn
526 using some register has been deleted by cross-jumping.
527 Make sure that uid_luid for that former insn's uid
528 points to the general area where that insn used to be. */
529 for (i = 0; i < max_uid_for_loop; i++)
531 uid_luid[0] = uid_luid[i];
532 if (uid_luid[0] != 0)
533 break;
535 for (i = 0; i < max_uid_for_loop; i++)
536 if (uid_luid[i] == 0)
537 uid_luid[i] = uid_luid[i - 1];
539 /* Determine if the function has indirect jump. On some systems
540 this prevents low overhead loop instructions from being used. */
541 indirect_jump_in_function = indirect_jump_in_function_p (f);
543 /* Now scan the loops, last ones first, since this means inner ones are done
544 before outer ones. */
545 for (i = max_loop_num - 1; i >= 0; i--)
547 struct loop *loop = &loops->array[i];
549 if (! loop->invalid && loop->end)
550 scan_loop (loop, flags);
553 end_alias_analysis ();
555 /* Clean up. */
556 free (uid_luid);
557 free (uid_loop);
558 free (loops_info);
559 free (loops->array);
562 /* Returns the next insn, in execution order, after INSN. START and
563 END are the NOTE_INSN_LOOP_BEG and NOTE_INSN_LOOP_END for the loop,
564 respectively. LOOP->TOP, if non-NULL, is the top of the loop in the
565 insn-stream; it is used with loops that are entered near the
566 bottom. */
568 static rtx
569 next_insn_in_loop (loop, insn)
570 const struct loop *loop;
571 rtx insn;
573 insn = NEXT_INSN (insn);
575 if (insn == loop->end)
577 if (loop->top)
578 /* Go to the top of the loop, and continue there. */
579 insn = loop->top;
580 else
581 /* We're done. */
582 insn = NULL_RTX;
585 if (insn == loop->scan_start)
586 /* We're done. */
587 insn = NULL_RTX;
589 return insn;
592 /* Optimize one loop described by LOOP. */
594 /* ??? Could also move memory writes out of loops if the destination address
595 is invariant, the source is invariant, the memory write is not volatile,
596 and if we can prove that no read inside the loop can read this address
597 before the write occurs. If there is a read of this address after the
598 write, then we can also mark the memory read as invariant. */
600 static void
601 scan_loop (loop, flags)
602 struct loop *loop;
603 int flags;
605 struct loop_info *loop_info = LOOP_INFO (loop);
606 struct loop_regs *regs = LOOP_REGS (loop);
607 int i;
608 rtx loop_start = loop->start;
609 rtx loop_end = loop->end;
610 rtx p;
611 /* 1 if we are scanning insns that could be executed zero times. */
612 int maybe_never = 0;
613 /* 1 if we are scanning insns that might never be executed
614 due to a subroutine call which might exit before they are reached. */
615 int call_passed = 0;
616 /* Number of insns in the loop. */
617 int insn_count;
618 int tem;
619 rtx temp, update_start, update_end;
620 /* The SET from an insn, if it is the only SET in the insn. */
621 rtx set, set1;
622 /* Chain describing insns movable in current loop. */
623 struct loop_movables *movables = LOOP_MOVABLES (loop);
624 /* Ratio of extra register life span we can justify
625 for saving an instruction. More if loop doesn't call subroutines
626 since in that case saving an insn makes more difference
627 and more registers are available. */
628 int threshold;
629 /* Nonzero if we are scanning instructions in a sub-loop. */
630 int loop_depth = 0;
631 int in_libcall;
633 loop->top = 0;
635 movables->head = 0;
636 movables->last = 0;
638 /* Determine whether this loop starts with a jump down to a test at
639 the end. This will occur for a small number of loops with a test
640 that is too complex to duplicate in front of the loop.
642 We search for the first insn or label in the loop, skipping NOTEs.
643 However, we must be careful not to skip past a NOTE_INSN_LOOP_BEG
644 (because we might have a loop executed only once that contains a
645 loop which starts with a jump to its exit test) or a NOTE_INSN_LOOP_END
646 (in case we have a degenerate loop).
648 Note that if we mistakenly think that a loop is entered at the top
649 when, in fact, it is entered at the exit test, the only effect will be
650 slightly poorer optimization. Making the opposite error can generate
651 incorrect code. Since very few loops now start with a jump to the
652 exit test, the code here to detect that case is very conservative. */
654 for (p = NEXT_INSN (loop_start);
655 p != loop_end
656 && GET_CODE (p) != CODE_LABEL && ! INSN_P (p)
657 && (GET_CODE (p) != NOTE
658 || (NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_BEG
659 && NOTE_LINE_NUMBER (p) != NOTE_INSN_LOOP_END));
660 p = NEXT_INSN (p))
663 loop->scan_start = p;
665 /* If loop end is the end of the current function, then emit a
666 NOTE_INSN_DELETED after loop_end and set loop->sink to the dummy
667 note insn. This is the position we use when sinking insns out of
668 the loop. */
669 if (NEXT_INSN (loop->end) != 0)
670 loop->sink = NEXT_INSN (loop->end);
671 else
672 loop->sink = emit_note_after (NOTE_INSN_DELETED, loop->end);
674 /* Set up variables describing this loop. */
675 prescan_loop (loop);
676 threshold = (loop_info->has_call ? 1 : 2) * (1 + n_non_fixed_regs);
678 /* If loop has a jump before the first label,
679 the true entry is the target of that jump.
680 Start scan from there.
681 But record in LOOP->TOP the place where the end-test jumps
682 back to so we can scan that after the end of the loop. */
683 if (GET_CODE (p) == JUMP_INSN
684 /* Loop entry must be unconditional jump (and not a RETURN) */
685 && any_uncondjump_p (p)
686 && JUMP_LABEL (p) != 0
687 /* Check to see whether the jump actually
688 jumps out of the loop (meaning it's no loop).
689 This case can happen for things like
690 do {..} while (0). If this label was generated previously
691 by loop, we can't tell anything about it and have to reject
692 the loop. */
693 && INSN_IN_RANGE_P (JUMP_LABEL (p), loop_start, loop_end))
695 loop->top = next_label (loop->scan_start);
696 loop->scan_start = JUMP_LABEL (p);
699 /* If LOOP->SCAN_START was an insn created by loop, we don't know its luid
700 as required by loop_reg_used_before_p. So skip such loops. (This
701 test may never be true, but it's best to play it safe.)
703 Also, skip loops where we do not start scanning at a label. This
704 test also rejects loops starting with a JUMP_INSN that failed the
705 test above. */
707 if (INSN_UID (loop->scan_start) >= max_uid_for_loop
708 || GET_CODE (loop->scan_start) != CODE_LABEL)
710 if (loop_dump_stream)
711 fprintf (loop_dump_stream, "\nLoop from %d to %d is phony.\n\n",
712 INSN_UID (loop_start), INSN_UID (loop_end));
713 return;
716 /* Allocate extra space for REGs that might be created by load_mems.
717 We allocate a little extra slop as well, in the hopes that we
718 won't have to reallocate the regs array. */
719 loop_regs_scan (loop, loop_info->mems_idx + 16);
720 insn_count = count_insns_in_loop (loop);
722 if (loop_dump_stream)
724 fprintf (loop_dump_stream, "\nLoop from %d to %d: %d real insns.\n",
725 INSN_UID (loop_start), INSN_UID (loop_end), insn_count);
726 if (loop->cont)
727 fprintf (loop_dump_stream, "Continue at insn %d.\n",
728 INSN_UID (loop->cont));
731 /* Scan through the loop finding insns that are safe to move.
732 Set REGS->ARRAY[I].SET_IN_LOOP negative for the reg I being set, so that
733 this reg will be considered invariant for subsequent insns.
734 We consider whether subsequent insns use the reg
735 in deciding whether it is worth actually moving.
737 MAYBE_NEVER is nonzero if we have passed a conditional jump insn
738 and therefore it is possible that the insns we are scanning
739 would never be executed. At such times, we must make sure
740 that it is safe to execute the insn once instead of zero times.
741 When MAYBE_NEVER is 0, all insns will be executed at least once
742 so that is not a problem. */
744 for (in_libcall = 0, p = next_insn_in_loop (loop, loop->scan_start);
745 p != NULL_RTX;
746 p = next_insn_in_loop (loop, p))
748 if (in_libcall && INSN_P (p) && find_reg_note (p, REG_RETVAL, NULL_RTX))
749 in_libcall--;
750 if (GET_CODE (p) == INSN)
752 temp = find_reg_note (p, REG_LIBCALL, NULL_RTX);
753 if (temp)
754 in_libcall++;
755 if (! in_libcall
756 && (set = single_set (p))
757 && GET_CODE (SET_DEST (set)) == REG
758 #ifdef PIC_OFFSET_TABLE_REG_CALL_CLOBBERED
759 && SET_DEST (set) != pic_offset_table_rtx
760 #endif
761 && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
763 int tem1 = 0;
764 int tem2 = 0;
765 int move_insn = 0;
766 int insert_temp = 0;
767 rtx src = SET_SRC (set);
768 rtx dependencies = 0;
770 /* Figure out what to use as a source of this insn. If a
771 REG_EQUIV note is given or if a REG_EQUAL note with a
772 constant operand is specified, use it as the source and
773 mark that we should move this insn by calling
774 emit_move_insn rather that duplicating the insn.
776 Otherwise, only use the REG_EQUAL contents if a REG_RETVAL
777 note is present. */
778 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
779 if (temp)
780 src = XEXP (temp, 0), move_insn = 1;
781 else
783 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
784 if (temp && CONSTANT_P (XEXP (temp, 0)))
785 src = XEXP (temp, 0), move_insn = 1;
786 if (temp && find_reg_note (p, REG_RETVAL, NULL_RTX))
788 src = XEXP (temp, 0);
789 /* A libcall block can use regs that don't appear in
790 the equivalent expression. To move the libcall,
791 we must move those regs too. */
792 dependencies = libcall_other_reg (p, src);
796 /* For parallels, add any possible uses to the dependencies, as
797 we can't move the insn without resolving them first. */
798 if (GET_CODE (PATTERN (p)) == PARALLEL)
800 for (i = 0; i < XVECLEN (PATTERN (p), 0); i++)
802 rtx x = XVECEXP (PATTERN (p), 0, i);
803 if (GET_CODE (x) == USE)
804 dependencies
805 = gen_rtx_EXPR_LIST (VOIDmode, XEXP (x, 0),
806 dependencies);
810 if (/* The register is used in basic blocks other
811 than the one where it is set (meaning that
812 something after this point in the loop might
813 depend on its value before the set). */
814 ! reg_in_basic_block_p (p, SET_DEST (set))
815 /* And the set is not guaranteed to be executed once
816 the loop starts, or the value before the set is
817 needed before the set occurs...
819 ??? Note we have quadratic behavior here, mitigated
820 by the fact that the previous test will often fail for
821 large loops. Rather than re-scanning the entire loop
822 each time for register usage, we should build tables
823 of the register usage and use them here instead. */
824 && (maybe_never
825 || loop_reg_used_before_p (loop, set, p)))
826 /* It is unsafe to move the set. However, it may be OK to
827 move the source into a new pseudo, and substitute a
828 reg-to-reg copy for the original insn.
830 This code used to consider it OK to move a set of a variable
831 which was not created by the user and not used in an exit
832 test.
833 That behavior is incorrect and was removed. */
834 insert_temp = 1;
836 /* Don't try to optimize a MODE_CC set with a constant
837 source. It probably will be combined with a conditional
838 jump. */
839 if (GET_MODE_CLASS (GET_MODE (SET_DEST (set))) == MODE_CC
840 && CONSTANT_P (src))
842 /* Don't try to optimize a register that was made
843 by loop-optimization for an inner loop.
844 We don't know its life-span, so we can't compute
845 the benefit. */
846 else if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
848 /* Don't move the source and add a reg-to-reg copy:
849 - with -Os (this certainly increases size),
850 - if the mode doesn't support copy operations (obviously),
851 - if the source is already a reg (the motion will gain nothing),
852 - if the source is a legitimate constant (likewise). */
853 else if (insert_temp
854 && (optimize_size
855 || ! can_copy_p (GET_MODE (SET_SRC (set)))
856 || GET_CODE (SET_SRC (set)) == REG
857 || (CONSTANT_P (SET_SRC (set))
858 && LEGITIMATE_CONSTANT_P (SET_SRC (set)))))
860 else if ((tem = loop_invariant_p (loop, src))
861 && (dependencies == 0
862 || (tem2
863 = loop_invariant_p (loop, dependencies)) != 0)
864 && (regs->array[REGNO (SET_DEST (set))].set_in_loop == 1
865 || (tem1
866 = consec_sets_invariant_p
867 (loop, SET_DEST (set),
868 regs->array[REGNO (SET_DEST (set))].set_in_loop,
869 p)))
870 /* If the insn can cause a trap (such as divide by zero),
871 can't move it unless it's guaranteed to be executed
872 once loop is entered. Even a function call might
873 prevent the trap insn from being reached
874 (since it might exit!) */
875 && ! ((maybe_never || call_passed)
876 && may_trap_p (src)))
878 struct movable *m;
879 int regno = REGNO (SET_DEST (set));
881 /* A potential lossage is where we have a case where two insns
882 can be combined as long as they are both in the loop, but
883 we move one of them outside the loop. For large loops,
884 this can lose. The most common case of this is the address
885 of a function being called.
887 Therefore, if this register is marked as being used
888 exactly once if we are in a loop with calls
889 (a "large loop"), see if we can replace the usage of
890 this register with the source of this SET. If we can,
891 delete this insn.
893 Don't do this if P has a REG_RETVAL note or if we have
894 SMALL_REGISTER_CLASSES and SET_SRC is a hard register. */
896 if (loop_info->has_call
897 && regs->array[regno].single_usage != 0
898 && regs->array[regno].single_usage != const0_rtx
899 && REGNO_FIRST_UID (regno) == INSN_UID (p)
900 && (REGNO_LAST_UID (regno)
901 == INSN_UID (regs->array[regno].single_usage))
902 && regs->array[regno].set_in_loop == 1
903 && GET_CODE (SET_SRC (set)) != ASM_OPERANDS
904 && ! side_effects_p (SET_SRC (set))
905 && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
906 && (! SMALL_REGISTER_CLASSES
907 || (! (GET_CODE (SET_SRC (set)) == REG
908 && (REGNO (SET_SRC (set))
909 < FIRST_PSEUDO_REGISTER))))
910 /* This test is not redundant; SET_SRC (set) might be
911 a call-clobbered register and the life of REGNO
912 might span a call. */
913 && ! modified_between_p (SET_SRC (set), p,
914 regs->array[regno].single_usage)
915 && no_labels_between_p (p,
916 regs->array[regno].single_usage)
917 && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
918 regs->array[regno].single_usage))
920 /* Replace any usage in a REG_EQUAL note. Must copy
921 the new source, so that we don't get rtx sharing
922 between the SET_SOURCE and REG_NOTES of insn p. */
923 REG_NOTES (regs->array[regno].single_usage)
924 = (replace_rtx
925 (REG_NOTES (regs->array[regno].single_usage),
926 SET_DEST (set), copy_rtx (SET_SRC (set))));
928 delete_insn (p);
929 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
930 i++)
931 regs->array[regno+i].set_in_loop = 0;
932 continue;
935 m = (struct movable *) xmalloc (sizeof (struct movable));
936 m->next = 0;
937 m->insn = p;
938 m->set_src = src;
939 m->dependencies = dependencies;
940 m->set_dest = SET_DEST (set);
941 m->force = 0;
942 m->consec
943 = regs->array[REGNO (SET_DEST (set))].set_in_loop - 1;
944 m->done = 0;
945 m->forces = 0;
946 m->partial = 0;
947 m->move_insn = move_insn;
948 m->move_insn_first = 0;
949 m->insert_temp = insert_temp;
950 m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
951 m->savemode = VOIDmode;
952 m->regno = regno;
953 /* Set M->cond if either loop_invariant_p
954 or consec_sets_invariant_p returned 2
955 (only conditionally invariant). */
956 m->cond = ((tem | tem1 | tem2) > 1);
957 m->global = LOOP_REG_GLOBAL_P (loop, regno);
958 m->match = 0;
959 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
960 m->savings = regs->array[regno].n_times_set;
961 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
962 m->savings += libcall_benefit (p);
963 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set)); i++)
964 regs->array[regno+i].set_in_loop = move_insn ? -2 : -1;
965 /* Add M to the end of the chain MOVABLES. */
966 loop_movables_add (movables, m);
968 if (m->consec > 0)
970 /* It is possible for the first instruction to have a
971 REG_EQUAL note but a non-invariant SET_SRC, so we must
972 remember the status of the first instruction in case
973 the last instruction doesn't have a REG_EQUAL note. */
974 m->move_insn_first = m->move_insn;
976 /* Skip this insn, not checking REG_LIBCALL notes. */
977 p = next_nonnote_insn (p);
978 /* Skip the consecutive insns, if there are any. */
979 p = skip_consec_insns (p, m->consec);
980 /* Back up to the last insn of the consecutive group. */
981 p = prev_nonnote_insn (p);
983 /* We must now reset m->move_insn, m->is_equiv, and
984 possibly m->set_src to correspond to the effects of
985 all the insns. */
986 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
987 if (temp)
988 m->set_src = XEXP (temp, 0), m->move_insn = 1;
989 else
991 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
992 if (temp && CONSTANT_P (XEXP (temp, 0)))
993 m->set_src = XEXP (temp, 0), m->move_insn = 1;
994 else
995 m->move_insn = 0;
998 m->is_equiv
999 = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
1002 /* If this register is always set within a STRICT_LOW_PART
1003 or set to zero, then its high bytes are constant.
1004 So clear them outside the loop and within the loop
1005 just load the low bytes.
1006 We must check that the machine has an instruction to do so.
1007 Also, if the value loaded into the register
1008 depends on the same register, this cannot be done. */
1009 else if (SET_SRC (set) == const0_rtx
1010 && GET_CODE (NEXT_INSN (p)) == INSN
1011 && (set1 = single_set (NEXT_INSN (p)))
1012 && GET_CODE (set1) == SET
1013 && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1014 && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1015 && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1016 == SET_DEST (set))
1017 && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1019 int regno = REGNO (SET_DEST (set));
1020 if (regs->array[regno].set_in_loop == 2)
1022 struct movable *m;
1023 m = (struct movable *) xmalloc (sizeof (struct movable));
1024 m->next = 0;
1025 m->insn = p;
1026 m->set_dest = SET_DEST (set);
1027 m->dependencies = 0;
1028 m->force = 0;
1029 m->consec = 0;
1030 m->done = 0;
1031 m->forces = 0;
1032 m->move_insn = 0;
1033 m->move_insn_first = 0;
1034 m->insert_temp = insert_temp;
1035 m->partial = 1;
1036 /* If the insn may not be executed on some cycles,
1037 we can't clear the whole reg; clear just high part.
1038 Not even if the reg is used only within this loop.
1039 Consider this:
1040 while (1)
1041 while (s != t) {
1042 if (foo ()) x = *s;
1043 use (x);
1045 Clearing x before the inner loop could clobber a value
1046 being saved from the last time around the outer loop.
1047 However, if the reg is not used outside this loop
1048 and all uses of the register are in the same
1049 basic block as the store, there is no problem.
1051 If this insn was made by loop, we don't know its
1052 INSN_LUID and hence must make a conservative
1053 assumption. */
1054 m->global = (INSN_UID (p) >= max_uid_for_loop
1055 || LOOP_REG_GLOBAL_P (loop, regno)
1056 || (labels_in_range_p
1057 (p, REGNO_FIRST_LUID (regno))));
1058 if (maybe_never && m->global)
1059 m->savemode = GET_MODE (SET_SRC (set1));
1060 else
1061 m->savemode = VOIDmode;
1062 m->regno = regno;
1063 m->cond = 0;
1064 m->match = 0;
1065 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
1066 m->savings = 1;
1067 for (i = 0;
1068 i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
1069 i++)
1070 regs->array[regno+i].set_in_loop = -1;
1071 /* Add M to the end of the chain MOVABLES. */
1072 loop_movables_add (movables, m);
1077 /* Past a call insn, we get to insns which might not be executed
1078 because the call might exit. This matters for insns that trap.
1079 Constant and pure call insns always return, so they don't count. */
1080 else if (GET_CODE (p) == CALL_INSN && ! CONST_OR_PURE_CALL_P (p))
1081 call_passed = 1;
1082 /* Past a label or a jump, we get to insns for which we
1083 can't count on whether or how many times they will be
1084 executed during each iteration. Therefore, we can
1085 only move out sets of trivial variables
1086 (those not used after the loop). */
1087 /* Similar code appears twice in strength_reduce. */
1088 else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1089 /* If we enter the loop in the middle, and scan around to the
1090 beginning, don't set maybe_never for that. This must be an
1091 unconditional jump, otherwise the code at the top of the
1092 loop might never be executed. Unconditional jumps are
1093 followed by a barrier then the loop_end. */
1094 && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop->top
1095 && NEXT_INSN (NEXT_INSN (p)) == loop_end
1096 && any_uncondjump_p (p)))
1097 maybe_never = 1;
1098 else if (GET_CODE (p) == NOTE)
1100 /* At the virtual top of a converted loop, insns are again known to
1101 be executed: logically, the loop begins here even though the exit
1102 code has been duplicated. */
1103 if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1104 maybe_never = call_passed = 0;
1105 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1106 loop_depth++;
1107 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1108 loop_depth--;
1112 /* If one movable subsumes another, ignore that other. */
1114 ignore_some_movables (movables);
1116 /* For each movable insn, see if the reg that it loads
1117 leads when it dies right into another conditionally movable insn.
1118 If so, record that the second insn "forces" the first one,
1119 since the second can be moved only if the first is. */
1121 force_movables (movables);
1123 /* See if there are multiple movable insns that load the same value.
1124 If there are, make all but the first point at the first one
1125 through the `match' field, and add the priorities of them
1126 all together as the priority of the first. */
1128 combine_movables (movables, regs);
1130 /* Now consider each movable insn to decide whether it is worth moving.
1131 Store 0 in regs->array[I].set_in_loop for each reg I that is moved.
1133 For machines with few registers this increases code size, so do not
1134 move moveables when optimizing for code size on such machines.
1135 (The 18 below is the value for i386.) */
1137 if (!optimize_size
1138 || (reg_class_size[GENERAL_REGS] > 18 && !loop_info->has_call))
1140 move_movables (loop, movables, threshold, insn_count);
1142 /* Recalculate regs->array if move_movables has created new
1143 registers. */
1144 if (max_reg_num () > regs->num)
1146 loop_regs_scan (loop, 0);
1147 for (update_start = loop_start;
1148 PREV_INSN (update_start)
1149 && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1150 update_start = PREV_INSN (update_start))
1152 update_end = NEXT_INSN (loop_end);
1154 reg_scan_update (update_start, update_end, loop_max_reg);
1155 loop_max_reg = max_reg_num ();
1159 /* Now candidates that still are negative are those not moved.
1160 Change regs->array[I].set_in_loop to indicate that those are not actually
1161 invariant. */
1162 for (i = 0; i < regs->num; i++)
1163 if (regs->array[i].set_in_loop < 0)
1164 regs->array[i].set_in_loop = regs->array[i].n_times_set;
1166 /* Now that we've moved some things out of the loop, we might be able to
1167 hoist even more memory references. */
1168 load_mems (loop);
1170 /* Recalculate regs->array if load_mems has created new registers. */
1171 if (max_reg_num () > regs->num)
1172 loop_regs_scan (loop, 0);
1174 for (update_start = loop_start;
1175 PREV_INSN (update_start)
1176 && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1177 update_start = PREV_INSN (update_start))
1179 update_end = NEXT_INSN (loop_end);
1181 reg_scan_update (update_start, update_end, loop_max_reg);
1182 loop_max_reg = max_reg_num ();
1184 if (flag_strength_reduce)
1186 if (update_end && GET_CODE (update_end) == CODE_LABEL)
1187 /* Ensure our label doesn't go away. */
1188 LABEL_NUSES (update_end)++;
1190 strength_reduce (loop, flags);
1192 reg_scan_update (update_start, update_end, loop_max_reg);
1193 loop_max_reg = max_reg_num ();
1195 if (update_end && GET_CODE (update_end) == CODE_LABEL
1196 && --LABEL_NUSES (update_end) == 0)
1197 delete_related_insns (update_end);
1201 /* The movable information is required for strength reduction. */
1202 loop_movables_free (movables);
1204 free (regs->array);
1205 regs->array = 0;
1206 regs->num = 0;
1209 /* Add elements to *OUTPUT to record all the pseudo-regs
1210 mentioned in IN_THIS but not mentioned in NOT_IN_THIS. */
1212 void
1213 record_excess_regs (in_this, not_in_this, output)
1214 rtx in_this, not_in_this;
1215 rtx *output;
1217 enum rtx_code code;
1218 const char *fmt;
1219 int i;
1221 code = GET_CODE (in_this);
1223 switch (code)
1225 case PC:
1226 case CC0:
1227 case CONST_INT:
1228 case CONST_DOUBLE:
1229 case CONST:
1230 case SYMBOL_REF:
1231 case LABEL_REF:
1232 return;
1234 case REG:
1235 if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1236 && ! reg_mentioned_p (in_this, not_in_this))
1237 *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1238 return;
1240 default:
1241 break;
1244 fmt = GET_RTX_FORMAT (code);
1245 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1247 int j;
1249 switch (fmt[i])
1251 case 'E':
1252 for (j = 0; j < XVECLEN (in_this, i); j++)
1253 record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1254 break;
1256 case 'e':
1257 record_excess_regs (XEXP (in_this, i), not_in_this, output);
1258 break;
1263 /* Check what regs are referred to in the libcall block ending with INSN,
1264 aside from those mentioned in the equivalent value.
1265 If there are none, return 0.
1266 If there are one or more, return an EXPR_LIST containing all of them. */
1269 libcall_other_reg (insn, equiv)
1270 rtx insn, equiv;
1272 rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1273 rtx p = XEXP (note, 0);
1274 rtx output = 0;
1276 /* First, find all the regs used in the libcall block
1277 that are not mentioned as inputs to the result. */
1279 while (p != insn)
1281 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1282 || GET_CODE (p) == CALL_INSN)
1283 record_excess_regs (PATTERN (p), equiv, &output);
1284 p = NEXT_INSN (p);
1287 return output;
1290 /* Return 1 if all uses of REG
1291 are between INSN and the end of the basic block. */
1293 static int
1294 reg_in_basic_block_p (insn, reg)
1295 rtx insn, reg;
1297 int regno = REGNO (reg);
1298 rtx p;
1300 if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1301 return 0;
1303 /* Search this basic block for the already recorded last use of the reg. */
1304 for (p = insn; p; p = NEXT_INSN (p))
1306 switch (GET_CODE (p))
1308 case NOTE:
1309 break;
1311 case INSN:
1312 case CALL_INSN:
1313 /* Ordinary insn: if this is the last use, we win. */
1314 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1315 return 1;
1316 break;
1318 case JUMP_INSN:
1319 /* Jump insn: if this is the last use, we win. */
1320 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1321 return 1;
1322 /* Otherwise, it's the end of the basic block, so we lose. */
1323 return 0;
1325 case CODE_LABEL:
1326 case BARRIER:
1327 /* It's the end of the basic block, so we lose. */
1328 return 0;
1330 default:
1331 break;
1335 /* The "last use" that was recorded can't be found after the first
1336 use. This can happen when the last use was deleted while
1337 processing an inner loop, this inner loop was then completely
1338 unrolled, and the outer loop is always exited after the inner loop,
1339 so that everything after the first use becomes a single basic block. */
1340 return 1;
1343 /* Compute the benefit of eliminating the insns in the block whose
1344 last insn is LAST. This may be a group of insns used to compute a
1345 value directly or can contain a library call. */
1347 static int
1348 libcall_benefit (last)
1349 rtx last;
1351 rtx insn;
1352 int benefit = 0;
1354 for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1355 insn != last; insn = NEXT_INSN (insn))
1357 if (GET_CODE (insn) == CALL_INSN)
1358 benefit += 10; /* Assume at least this many insns in a library
1359 routine. */
1360 else if (GET_CODE (insn) == INSN
1361 && GET_CODE (PATTERN (insn)) != USE
1362 && GET_CODE (PATTERN (insn)) != CLOBBER)
1363 benefit++;
1366 return benefit;
1369 /* Skip COUNT insns from INSN, counting library calls as 1 insn. */
1371 static rtx
1372 skip_consec_insns (insn, count)
1373 rtx insn;
1374 int count;
1376 for (; count > 0; count--)
1378 rtx temp;
1380 /* If first insn of libcall sequence, skip to end. */
1381 /* Do this at start of loop, since INSN is guaranteed to
1382 be an insn here. */
1383 if (GET_CODE (insn) != NOTE
1384 && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1385 insn = XEXP (temp, 0);
1388 insn = NEXT_INSN (insn);
1389 while (GET_CODE (insn) == NOTE);
1392 return insn;
1395 /* Ignore any movable whose insn falls within a libcall
1396 which is part of another movable.
1397 We make use of the fact that the movable for the libcall value
1398 was made later and so appears later on the chain. */
1400 static void
1401 ignore_some_movables (movables)
1402 struct loop_movables *movables;
1404 struct movable *m, *m1;
1406 for (m = movables->head; m; m = m->next)
1408 /* Is this a movable for the value of a libcall? */
1409 rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1410 if (note)
1412 rtx insn;
1413 /* Check for earlier movables inside that range,
1414 and mark them invalid. We cannot use LUIDs here because
1415 insns created by loop.c for prior loops don't have LUIDs.
1416 Rather than reject all such insns from movables, we just
1417 explicitly check each insn in the libcall (since invariant
1418 libcalls aren't that common). */
1419 for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1420 for (m1 = movables->head; m1 != m; m1 = m1->next)
1421 if (m1->insn == insn)
1422 m1->done = 1;
1427 /* For each movable insn, see if the reg that it loads
1428 leads when it dies right into another conditionally movable insn.
1429 If so, record that the second insn "forces" the first one,
1430 since the second can be moved only if the first is. */
1432 static void
1433 force_movables (movables)
1434 struct loop_movables *movables;
1436 struct movable *m, *m1;
1438 for (m1 = movables->head; m1; m1 = m1->next)
1439 /* Omit this if moving just the (SET (REG) 0) of a zero-extend. */
1440 if (!m1->partial && !m1->done)
1442 int regno = m1->regno;
1443 for (m = m1->next; m; m = m->next)
1444 /* ??? Could this be a bug? What if CSE caused the
1445 register of M1 to be used after this insn?
1446 Since CSE does not update regno_last_uid,
1447 this insn M->insn might not be where it dies.
1448 But very likely this doesn't matter; what matters is
1449 that M's reg is computed from M1's reg. */
1450 if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1451 && !m->done)
1452 break;
1453 if (m != 0 && m->set_src == m1->set_dest
1454 /* If m->consec, m->set_src isn't valid. */
1455 && m->consec == 0)
1456 m = 0;
1458 /* Increase the priority of the moving the first insn
1459 since it permits the second to be moved as well. */
1460 if (m != 0)
1462 m->forces = m1;
1463 m1->lifetime += m->lifetime;
1464 m1->savings += m->savings;
1469 /* Find invariant expressions that are equal and can be combined into
1470 one register. */
1472 static void
1473 combine_movables (movables, regs)
1474 struct loop_movables *movables;
1475 struct loop_regs *regs;
1477 struct movable *m;
1478 char *matched_regs = (char *) xmalloc (regs->num);
1479 enum machine_mode mode;
1481 /* Regs that are set more than once are not allowed to match
1482 or be matched. I'm no longer sure why not. */
1483 /* Only pseudo registers are allowed to match or be matched,
1484 since move_movables does not validate the change. */
1485 /* Perhaps testing m->consec_sets would be more appropriate here? */
1487 for (m = movables->head; m; m = m->next)
1488 if (m->match == 0 && regs->array[m->regno].n_times_set == 1
1489 && m->regno >= FIRST_PSEUDO_REGISTER
1490 && !m->insert_temp
1491 && !m->partial)
1493 struct movable *m1;
1494 int regno = m->regno;
1496 memset (matched_regs, 0, regs->num);
1497 matched_regs[regno] = 1;
1499 /* We want later insns to match the first one. Don't make the first
1500 one match any later ones. So start this loop at m->next. */
1501 for (m1 = m->next; m1; m1 = m1->next)
1502 if (m != m1 && m1->match == 0
1503 && !m1->insert_temp
1504 && regs->array[m1->regno].n_times_set == 1
1505 && m1->regno >= FIRST_PSEUDO_REGISTER
1506 /* A reg used outside the loop mustn't be eliminated. */
1507 && !m1->global
1508 /* A reg used for zero-extending mustn't be eliminated. */
1509 && !m1->partial
1510 && (matched_regs[m1->regno]
1513 /* Can combine regs with different modes loaded from the
1514 same constant only if the modes are the same or
1515 if both are integer modes with M wider or the same
1516 width as M1. The check for integer is redundant, but
1517 safe, since the only case of differing destination
1518 modes with equal sources is when both sources are
1519 VOIDmode, i.e., CONST_INT. */
1520 (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1521 || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1522 && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1523 && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1524 >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1525 /* See if the source of M1 says it matches M. */
1526 && ((GET_CODE (m1->set_src) == REG
1527 && matched_regs[REGNO (m1->set_src)])
1528 || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1529 movables, regs))))
1530 && ((m->dependencies == m1->dependencies)
1531 || rtx_equal_p (m->dependencies, m1->dependencies)))
1533 m->lifetime += m1->lifetime;
1534 m->savings += m1->savings;
1535 m1->done = 1;
1536 m1->match = m;
1537 matched_regs[m1->regno] = 1;
1541 /* Now combine the regs used for zero-extension.
1542 This can be done for those not marked `global'
1543 provided their lives don't overlap. */
1545 for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1546 mode = GET_MODE_WIDER_MODE (mode))
1548 struct movable *m0 = 0;
1550 /* Combine all the registers for extension from mode MODE.
1551 Don't combine any that are used outside this loop. */
1552 for (m = movables->head; m; m = m->next)
1553 if (m->partial && ! m->global
1554 && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1556 struct movable *m1;
1558 int first = REGNO_FIRST_LUID (m->regno);
1559 int last = REGNO_LAST_LUID (m->regno);
1561 if (m0 == 0)
1563 /* First one: don't check for overlap, just record it. */
1564 m0 = m;
1565 continue;
1568 /* Make sure they extend to the same mode.
1569 (Almost always true.) */
1570 if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1571 continue;
1573 /* We already have one: check for overlap with those
1574 already combined together. */
1575 for (m1 = movables->head; m1 != m; m1 = m1->next)
1576 if (m1 == m0 || (m1->partial && m1->match == m0))
1577 if (! (REGNO_FIRST_LUID (m1->regno) > last
1578 || REGNO_LAST_LUID (m1->regno) < first))
1579 goto overlap;
1581 /* No overlap: we can combine this with the others. */
1582 m0->lifetime += m->lifetime;
1583 m0->savings += m->savings;
1584 m->done = 1;
1585 m->match = m0;
1587 overlap:
1592 /* Clean up. */
1593 free (matched_regs);
1596 /* Returns the number of movable instructions in LOOP that were not
1597 moved outside the loop. */
1599 static int
1600 num_unmoved_movables (loop)
1601 const struct loop *loop;
1603 int num = 0;
1604 struct movable *m;
1606 for (m = LOOP_MOVABLES (loop)->head; m; m = m->next)
1607 if (!m->done)
1608 ++num;
1610 return num;
1614 /* Return 1 if regs X and Y will become the same if moved. */
1616 static int
1617 regs_match_p (x, y, movables)
1618 rtx x, y;
1619 struct loop_movables *movables;
1621 unsigned int xn = REGNO (x);
1622 unsigned int yn = REGNO (y);
1623 struct movable *mx, *my;
1625 for (mx = movables->head; mx; mx = mx->next)
1626 if (mx->regno == xn)
1627 break;
1629 for (my = movables->head; my; my = my->next)
1630 if (my->regno == yn)
1631 break;
1633 return (mx && my
1634 && ((mx->match == my->match && mx->match != 0)
1635 || mx->match == my
1636 || mx == my->match));
1639 /* Return 1 if X and Y are identical-looking rtx's.
1640 This is the Lisp function EQUAL for rtx arguments.
1642 If two registers are matching movables or a movable register and an
1643 equivalent constant, consider them equal. */
1645 static int
1646 rtx_equal_for_loop_p (x, y, movables, regs)
1647 rtx x, y;
1648 struct loop_movables *movables;
1649 struct loop_regs *regs;
1651 int i;
1652 int j;
1653 struct movable *m;
1654 enum rtx_code code;
1655 const char *fmt;
1657 if (x == y)
1658 return 1;
1659 if (x == 0 || y == 0)
1660 return 0;
1662 code = GET_CODE (x);
1664 /* If we have a register and a constant, they may sometimes be
1665 equal. */
1666 if (GET_CODE (x) == REG && regs->array[REGNO (x)].set_in_loop == -2
1667 && CONSTANT_P (y))
1669 for (m = movables->head; m; m = m->next)
1670 if (m->move_insn && m->regno == REGNO (x)
1671 && rtx_equal_p (m->set_src, y))
1672 return 1;
1674 else if (GET_CODE (y) == REG && regs->array[REGNO (y)].set_in_loop == -2
1675 && CONSTANT_P (x))
1677 for (m = movables->head; m; m = m->next)
1678 if (m->move_insn && m->regno == REGNO (y)
1679 && rtx_equal_p (m->set_src, x))
1680 return 1;
1683 /* Otherwise, rtx's of different codes cannot be equal. */
1684 if (code != GET_CODE (y))
1685 return 0;
1687 /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1688 (REG:SI x) and (REG:HI x) are NOT equivalent. */
1690 if (GET_MODE (x) != GET_MODE (y))
1691 return 0;
1693 /* These three types of rtx's can be compared nonrecursively. */
1694 if (code == REG)
1695 return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1697 if (code == LABEL_REF)
1698 return XEXP (x, 0) == XEXP (y, 0);
1699 if (code == SYMBOL_REF)
1700 return XSTR (x, 0) == XSTR (y, 0);
1702 /* Compare the elements. If any pair of corresponding elements
1703 fail to match, return 0 for the whole things. */
1705 fmt = GET_RTX_FORMAT (code);
1706 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1708 switch (fmt[i])
1710 case 'w':
1711 if (XWINT (x, i) != XWINT (y, i))
1712 return 0;
1713 break;
1715 case 'i':
1716 if (XINT (x, i) != XINT (y, i))
1717 return 0;
1718 break;
1720 case 'E':
1721 /* Two vectors must have the same length. */
1722 if (XVECLEN (x, i) != XVECLEN (y, i))
1723 return 0;
1725 /* And the corresponding elements must match. */
1726 for (j = 0; j < XVECLEN (x, i); j++)
1727 if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j),
1728 movables, regs) == 0)
1729 return 0;
1730 break;
1732 case 'e':
1733 if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables, regs)
1734 == 0)
1735 return 0;
1736 break;
1738 case 's':
1739 if (strcmp (XSTR (x, i), XSTR (y, i)))
1740 return 0;
1741 break;
1743 case 'u':
1744 /* These are just backpointers, so they don't matter. */
1745 break;
1747 case '0':
1748 break;
1750 /* It is believed that rtx's at this level will never
1751 contain anything but integers and other rtx's,
1752 except for within LABEL_REFs and SYMBOL_REFs. */
1753 default:
1754 abort ();
1757 return 1;
1760 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1761 insns in INSNS which use the reference. LABEL_NUSES for CODE_LABEL
1762 references is incremented once for each added note. */
1764 static void
1765 add_label_notes (x, insns)
1766 rtx x;
1767 rtx insns;
1769 enum rtx_code code = GET_CODE (x);
1770 int i, j;
1771 const char *fmt;
1772 rtx insn;
1774 if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1776 /* This code used to ignore labels that referred to dispatch tables to
1777 avoid flow generating (slighly) worse code.
1779 We no longer ignore such label references (see LABEL_REF handling in
1780 mark_jump_label for additional information). */
1781 for (insn = insns; insn; insn = NEXT_INSN (insn))
1782 if (reg_mentioned_p (XEXP (x, 0), insn))
1784 REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, XEXP (x, 0),
1785 REG_NOTES (insn));
1786 if (LABEL_P (XEXP (x, 0)))
1787 LABEL_NUSES (XEXP (x, 0))++;
1791 fmt = GET_RTX_FORMAT (code);
1792 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1794 if (fmt[i] == 'e')
1795 add_label_notes (XEXP (x, i), insns);
1796 else if (fmt[i] == 'E')
1797 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1798 add_label_notes (XVECEXP (x, i, j), insns);
1802 /* Scan MOVABLES, and move the insns that deserve to be moved.
1803 If two matching movables are combined, replace one reg with the
1804 other throughout. */
1806 static void
1807 move_movables (loop, movables, threshold, insn_count)
1808 struct loop *loop;
1809 struct loop_movables *movables;
1810 int threshold;
1811 int insn_count;
1813 struct loop_regs *regs = LOOP_REGS (loop);
1814 int nregs = regs->num;
1815 rtx new_start = 0;
1816 struct movable *m;
1817 rtx p;
1818 rtx loop_start = loop->start;
1819 rtx loop_end = loop->end;
1820 /* Map of pseudo-register replacements to handle combining
1821 when we move several insns that load the same value
1822 into different pseudo-registers. */
1823 rtx *reg_map = (rtx *) xcalloc (nregs, sizeof (rtx));
1824 char *already_moved = (char *) xcalloc (nregs, sizeof (char));
1826 for (m = movables->head; m; m = m->next)
1828 /* Describe this movable insn. */
1830 if (loop_dump_stream)
1832 fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1833 INSN_UID (m->insn), m->regno, m->lifetime);
1834 if (m->consec > 0)
1835 fprintf (loop_dump_stream, "consec %d, ", m->consec);
1836 if (m->cond)
1837 fprintf (loop_dump_stream, "cond ");
1838 if (m->force)
1839 fprintf (loop_dump_stream, "force ");
1840 if (m->global)
1841 fprintf (loop_dump_stream, "global ");
1842 if (m->done)
1843 fprintf (loop_dump_stream, "done ");
1844 if (m->move_insn)
1845 fprintf (loop_dump_stream, "move-insn ");
1846 if (m->match)
1847 fprintf (loop_dump_stream, "matches %d ",
1848 INSN_UID (m->match->insn));
1849 if (m->forces)
1850 fprintf (loop_dump_stream, "forces %d ",
1851 INSN_UID (m->forces->insn));
1854 /* Ignore the insn if it's already done (it matched something else).
1855 Otherwise, see if it is now safe to move. */
1857 if (!m->done
1858 && (! m->cond
1859 || (1 == loop_invariant_p (loop, m->set_src)
1860 && (m->dependencies == 0
1861 || 1 == loop_invariant_p (loop, m->dependencies))
1862 && (m->consec == 0
1863 || 1 == consec_sets_invariant_p (loop, m->set_dest,
1864 m->consec + 1,
1865 m->insn))))
1866 && (! m->forces || m->forces->done))
1868 int regno;
1869 rtx p;
1870 int savings = m->savings;
1872 /* We have an insn that is safe to move.
1873 Compute its desirability. */
1875 p = m->insn;
1876 regno = m->regno;
1878 if (loop_dump_stream)
1879 fprintf (loop_dump_stream, "savings %d ", savings);
1881 if (regs->array[regno].moved_once && loop_dump_stream)
1882 fprintf (loop_dump_stream, "halved since already moved ");
1884 /* An insn MUST be moved if we already moved something else
1885 which is safe only if this one is moved too: that is,
1886 if already_moved[REGNO] is nonzero. */
1888 /* An insn is desirable to move if the new lifetime of the
1889 register is no more than THRESHOLD times the old lifetime.
1890 If it's not desirable, it means the loop is so big
1891 that moving won't speed things up much,
1892 and it is liable to make register usage worse. */
1894 /* It is also desirable to move if it can be moved at no
1895 extra cost because something else was already moved. */
1897 if (already_moved[regno]
1898 || flag_move_all_movables
1899 || (threshold * savings * m->lifetime) >=
1900 (regs->array[regno].moved_once ? insn_count * 2 : insn_count)
1901 || (m->forces && m->forces->done
1902 && regs->array[m->forces->regno].n_times_set == 1))
1904 int count;
1905 struct movable *m1;
1906 rtx first = NULL_RTX;
1907 rtx newreg = NULL_RTX;
1909 if (m->insert_temp)
1910 newreg = gen_reg_rtx (GET_MODE (m->set_dest));
1912 /* Now move the insns that set the reg. */
1914 if (m->partial && m->match)
1916 rtx newpat, i1;
1917 rtx r1, r2;
1918 /* Find the end of this chain of matching regs.
1919 Thus, we load each reg in the chain from that one reg.
1920 And that reg is loaded with 0 directly,
1921 since it has ->match == 0. */
1922 for (m1 = m; m1->match; m1 = m1->match);
1923 newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1924 SET_DEST (PATTERN (m1->insn)));
1925 i1 = loop_insn_hoist (loop, newpat);
1927 /* Mark the moved, invariant reg as being allowed to
1928 share a hard reg with the other matching invariant. */
1929 REG_NOTES (i1) = REG_NOTES (m->insn);
1930 r1 = SET_DEST (PATTERN (m->insn));
1931 r2 = SET_DEST (PATTERN (m1->insn));
1932 regs_may_share
1933 = gen_rtx_EXPR_LIST (VOIDmode, r1,
1934 gen_rtx_EXPR_LIST (VOIDmode, r2,
1935 regs_may_share));
1936 delete_insn (m->insn);
1938 if (new_start == 0)
1939 new_start = i1;
1941 if (loop_dump_stream)
1942 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1944 /* If we are to re-generate the item being moved with a
1945 new move insn, first delete what we have and then emit
1946 the move insn before the loop. */
1947 else if (m->move_insn)
1949 rtx i1, temp, seq;
1951 for (count = m->consec; count >= 0; count--)
1953 /* If this is the first insn of a library call sequence,
1954 something is very wrong. */
1955 if (GET_CODE (p) != NOTE
1956 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1957 abort ();
1959 /* If this is the last insn of a libcall sequence, then
1960 delete every insn in the sequence except the last.
1961 The last insn is handled in the normal manner. */
1962 if (GET_CODE (p) != NOTE
1963 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1965 temp = XEXP (temp, 0);
1966 while (temp != p)
1967 temp = delete_insn (temp);
1970 temp = p;
1971 p = delete_insn (p);
1973 /* simplify_giv_expr expects that it can walk the insns
1974 at m->insn forwards and see this old sequence we are
1975 tossing here. delete_insn does preserve the next
1976 pointers, but when we skip over a NOTE we must fix
1977 it up. Otherwise that code walks into the non-deleted
1978 insn stream. */
1979 while (p && GET_CODE (p) == NOTE)
1980 p = NEXT_INSN (temp) = NEXT_INSN (p);
1982 if (m->insert_temp)
1984 /* Replace the original insn with a move from
1985 our newly created temp. */
1986 start_sequence ();
1987 emit_move_insn (m->set_dest, newreg);
1988 seq = get_insns ();
1989 end_sequence ();
1990 emit_insn_before (seq, p);
1994 start_sequence ();
1995 emit_move_insn (m->insert_temp ? newreg : m->set_dest,
1996 m->set_src);
1997 seq = get_insns ();
1998 end_sequence ();
2000 add_label_notes (m->set_src, seq);
2002 i1 = loop_insn_hoist (loop, seq);
2003 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2004 set_unique_reg_note (i1,
2005 m->is_equiv ? REG_EQUIV : REG_EQUAL,
2006 m->set_src);
2008 if (loop_dump_stream)
2009 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
2011 /* The more regs we move, the less we like moving them. */
2012 threshold -= 3;
2014 else
2016 for (count = m->consec; count >= 0; count--)
2018 rtx i1, temp;
2020 /* If first insn of libcall sequence, skip to end. */
2021 /* Do this at start of loop, since p is guaranteed to
2022 be an insn here. */
2023 if (GET_CODE (p) != NOTE
2024 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2025 p = XEXP (temp, 0);
2027 /* If last insn of libcall sequence, move all
2028 insns except the last before the loop. The last
2029 insn is handled in the normal manner. */
2030 if (GET_CODE (p) != NOTE
2031 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
2033 rtx fn_address = 0;
2034 rtx fn_reg = 0;
2035 rtx fn_address_insn = 0;
2037 first = 0;
2038 for (temp = XEXP (temp, 0); temp != p;
2039 temp = NEXT_INSN (temp))
2041 rtx body;
2042 rtx n;
2043 rtx next;
2045 if (GET_CODE (temp) == NOTE)
2046 continue;
2048 body = PATTERN (temp);
2050 /* Find the next insn after TEMP,
2051 not counting USE or NOTE insns. */
2052 for (next = NEXT_INSN (temp); next != p;
2053 next = NEXT_INSN (next))
2054 if (! (GET_CODE (next) == INSN
2055 && GET_CODE (PATTERN (next)) == USE)
2056 && GET_CODE (next) != NOTE)
2057 break;
2059 /* If that is the call, this may be the insn
2060 that loads the function address.
2062 Extract the function address from the insn
2063 that loads it into a register.
2064 If this insn was cse'd, we get incorrect code.
2066 So emit a new move insn that copies the
2067 function address into the register that the
2068 call insn will use. flow.c will delete any
2069 redundant stores that we have created. */
2070 if (GET_CODE (next) == CALL_INSN
2071 && GET_CODE (body) == SET
2072 && GET_CODE (SET_DEST (body)) == REG
2073 && (n = find_reg_note (temp, REG_EQUAL,
2074 NULL_RTX)))
2076 fn_reg = SET_SRC (body);
2077 if (GET_CODE (fn_reg) != REG)
2078 fn_reg = SET_DEST (body);
2079 fn_address = XEXP (n, 0);
2080 fn_address_insn = temp;
2082 /* We have the call insn.
2083 If it uses the register we suspect it might,
2084 load it with the correct address directly. */
2085 if (GET_CODE (temp) == CALL_INSN
2086 && fn_address != 0
2087 && reg_referenced_p (fn_reg, body))
2088 loop_insn_emit_after (loop, 0, fn_address_insn,
2089 gen_move_insn
2090 (fn_reg, fn_address));
2092 if (GET_CODE (temp) == CALL_INSN)
2094 i1 = loop_call_insn_hoist (loop, body);
2095 /* Because the USAGE information potentially
2096 contains objects other than hard registers
2097 we need to copy it. */
2098 if (CALL_INSN_FUNCTION_USAGE (temp))
2099 CALL_INSN_FUNCTION_USAGE (i1)
2100 = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2102 else
2103 i1 = loop_insn_hoist (loop, body);
2104 if (first == 0)
2105 first = i1;
2106 if (temp == fn_address_insn)
2107 fn_address_insn = i1;
2108 REG_NOTES (i1) = REG_NOTES (temp);
2109 REG_NOTES (temp) = NULL;
2110 delete_insn (temp);
2112 if (new_start == 0)
2113 new_start = first;
2115 if (m->savemode != VOIDmode)
2117 /* P sets REG to zero; but we should clear only
2118 the bits that are not covered by the mode
2119 m->savemode. */
2120 rtx reg = m->set_dest;
2121 rtx sequence;
2122 rtx tem;
2124 start_sequence ();
2125 tem = expand_simple_binop
2126 (GET_MODE (reg), AND, reg,
2127 GEN_INT ((((HOST_WIDE_INT) 1
2128 << GET_MODE_BITSIZE (m->savemode)))
2129 - 1),
2130 reg, 1, OPTAB_LIB_WIDEN);
2131 if (tem == 0)
2132 abort ();
2133 if (tem != reg)
2134 emit_move_insn (reg, tem);
2135 sequence = get_insns ();
2136 end_sequence ();
2137 i1 = loop_insn_hoist (loop, sequence);
2139 else if (GET_CODE (p) == CALL_INSN)
2141 i1 = loop_call_insn_hoist (loop, PATTERN (p));
2142 /* Because the USAGE information potentially
2143 contains objects other than hard registers
2144 we need to copy it. */
2145 if (CALL_INSN_FUNCTION_USAGE (p))
2146 CALL_INSN_FUNCTION_USAGE (i1)
2147 = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2149 else if (count == m->consec && m->move_insn_first)
2151 rtx seq;
2152 /* The SET_SRC might not be invariant, so we must
2153 use the REG_EQUAL note. */
2154 start_sequence ();
2155 emit_move_insn (m->set_dest, m->set_src);
2156 seq = get_insns ();
2157 end_sequence ();
2159 add_label_notes (m->set_src, seq);
2161 i1 = loop_insn_hoist (loop, seq);
2162 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2163 set_unique_reg_note (i1, m->is_equiv ? REG_EQUIV
2164 : REG_EQUAL, m->set_src);
2166 else if (m->insert_temp)
2168 rtx *reg_map2 = (rtx *) xcalloc (REGNO (newreg),
2169 sizeof(rtx));
2170 reg_map2 [m->regno] = newreg;
2172 i1 = loop_insn_hoist (loop, copy_rtx (PATTERN (p)));
2173 replace_regs (i1, reg_map2, REGNO (newreg), 1);
2174 free (reg_map2);
2176 else
2177 i1 = loop_insn_hoist (loop, PATTERN (p));
2179 if (REG_NOTES (i1) == 0)
2181 REG_NOTES (i1) = REG_NOTES (p);
2182 REG_NOTES (p) = NULL;
2184 /* If there is a REG_EQUAL note present whose value
2185 is not loop invariant, then delete it, since it
2186 may cause problems with later optimization passes.
2187 It is possible for cse to create such notes
2188 like this as a result of record_jump_cond. */
2190 if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2191 && ! loop_invariant_p (loop, XEXP (temp, 0)))
2192 remove_note (i1, temp);
2195 if (new_start == 0)
2196 new_start = i1;
2198 if (loop_dump_stream)
2199 fprintf (loop_dump_stream, " moved to %d",
2200 INSN_UID (i1));
2202 /* If library call, now fix the REG_NOTES that contain
2203 insn pointers, namely REG_LIBCALL on FIRST
2204 and REG_RETVAL on I1. */
2205 if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2207 XEXP (temp, 0) = first;
2208 temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2209 XEXP (temp, 0) = i1;
2212 temp = p;
2213 delete_insn (p);
2214 p = NEXT_INSN (p);
2216 /* simplify_giv_expr expects that it can walk the insns
2217 at m->insn forwards and see this old sequence we are
2218 tossing here. delete_insn does preserve the next
2219 pointers, but when we skip over a NOTE we must fix
2220 it up. Otherwise that code walks into the non-deleted
2221 insn stream. */
2222 while (p && GET_CODE (p) == NOTE)
2223 p = NEXT_INSN (temp) = NEXT_INSN (p);
2225 if (m->insert_temp)
2227 rtx seq;
2228 /* Replace the original insn with a move from
2229 our newly created temp. */
2230 start_sequence ();
2231 emit_move_insn (m->set_dest, newreg);
2232 seq = get_insns ();
2233 end_sequence ();
2234 emit_insn_before (seq, p);
2238 /* The more regs we move, the less we like moving them. */
2239 threshold -= 3;
2242 m->done = 1;
2244 if (!m->insert_temp)
2246 /* Any other movable that loads the same register
2247 MUST be moved. */
2248 already_moved[regno] = 1;
2250 /* This reg has been moved out of one loop. */
2251 regs->array[regno].moved_once = 1;
2253 /* The reg set here is now invariant. */
2254 if (! m->partial)
2256 int i;
2257 for (i = 0; i < LOOP_REGNO_NREGS (regno, m->set_dest); i++)
2258 regs->array[regno+i].set_in_loop = 0;
2261 /* Change the length-of-life info for the register
2262 to say it lives at least the full length of this loop.
2263 This will help guide optimizations in outer loops. */
2265 if (REGNO_FIRST_LUID (regno) > INSN_LUID (loop_start))
2266 /* This is the old insn before all the moved insns.
2267 We can't use the moved insn because it is out of range
2268 in uid_luid. Only the old insns have luids. */
2269 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2270 if (REGNO_LAST_LUID (regno) < INSN_LUID (loop_end))
2271 REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2274 /* Combine with this moved insn any other matching movables. */
2276 if (! m->partial)
2277 for (m1 = movables->head; m1; m1 = m1->next)
2278 if (m1->match == m)
2280 rtx temp;
2282 /* Schedule the reg loaded by M1
2283 for replacement so that shares the reg of M.
2284 If the modes differ (only possible in restricted
2285 circumstances, make a SUBREG.
2287 Note this assumes that the target dependent files
2288 treat REG and SUBREG equally, including within
2289 GO_IF_LEGITIMATE_ADDRESS and in all the
2290 predicates since we never verify that replacing the
2291 original register with a SUBREG results in a
2292 recognizable insn. */
2293 if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2294 reg_map[m1->regno] = m->set_dest;
2295 else
2296 reg_map[m1->regno]
2297 = gen_lowpart_common (GET_MODE (m1->set_dest),
2298 m->set_dest);
2300 /* Get rid of the matching insn
2301 and prevent further processing of it. */
2302 m1->done = 1;
2304 /* if library call, delete all insns. */
2305 if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2306 NULL_RTX)))
2307 delete_insn_chain (XEXP (temp, 0), m1->insn);
2308 else
2309 delete_insn (m1->insn);
2311 /* Any other movable that loads the same register
2312 MUST be moved. */
2313 already_moved[m1->regno] = 1;
2315 /* The reg merged here is now invariant,
2316 if the reg it matches is invariant. */
2317 if (! m->partial)
2319 int i;
2320 for (i = 0;
2321 i < LOOP_REGNO_NREGS (regno, m1->set_dest);
2322 i++)
2323 regs->array[m1->regno+i].set_in_loop = 0;
2327 else if (loop_dump_stream)
2328 fprintf (loop_dump_stream, "not desirable");
2330 else if (loop_dump_stream && !m->match)
2331 fprintf (loop_dump_stream, "not safe");
2333 if (loop_dump_stream)
2334 fprintf (loop_dump_stream, "\n");
2337 if (new_start == 0)
2338 new_start = loop_start;
2340 /* Go through all the instructions in the loop, making
2341 all the register substitutions scheduled in REG_MAP. */
2342 for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2343 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2344 || GET_CODE (p) == CALL_INSN)
2346 replace_regs (PATTERN (p), reg_map, nregs, 0);
2347 replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2348 INSN_CODE (p) = -1;
2351 /* Clean up. */
2352 free (reg_map);
2353 free (already_moved);
2357 static void
2358 loop_movables_add (movables, m)
2359 struct loop_movables *movables;
2360 struct movable *m;
2362 if (movables->head == 0)
2363 movables->head = m;
2364 else
2365 movables->last->next = m;
2366 movables->last = m;
2370 static void
2371 loop_movables_free (movables)
2372 struct loop_movables *movables;
2374 struct movable *m;
2375 struct movable *m_next;
2377 for (m = movables->head; m; m = m_next)
2379 m_next = m->next;
2380 free (m);
2384 #if 0
2385 /* Scan X and replace the address of any MEM in it with ADDR.
2386 REG is the address that MEM should have before the replacement. */
2388 static void
2389 replace_call_address (x, reg, addr)
2390 rtx x, reg, addr;
2392 enum rtx_code code;
2393 int i;
2394 const char *fmt;
2396 if (x == 0)
2397 return;
2398 code = GET_CODE (x);
2399 switch (code)
2401 case PC:
2402 case CC0:
2403 case CONST_INT:
2404 case CONST_DOUBLE:
2405 case CONST:
2406 case SYMBOL_REF:
2407 case LABEL_REF:
2408 case REG:
2409 return;
2411 case SET:
2412 /* Short cut for very common case. */
2413 replace_call_address (XEXP (x, 1), reg, addr);
2414 return;
2416 case CALL:
2417 /* Short cut for very common case. */
2418 replace_call_address (XEXP (x, 0), reg, addr);
2419 return;
2421 case MEM:
2422 /* If this MEM uses a reg other than the one we expected,
2423 something is wrong. */
2424 if (XEXP (x, 0) != reg)
2425 abort ();
2426 XEXP (x, 0) = addr;
2427 return;
2429 default:
2430 break;
2433 fmt = GET_RTX_FORMAT (code);
2434 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2436 if (fmt[i] == 'e')
2437 replace_call_address (XEXP (x, i), reg, addr);
2438 else if (fmt[i] == 'E')
2440 int j;
2441 for (j = 0; j < XVECLEN (x, i); j++)
2442 replace_call_address (XVECEXP (x, i, j), reg, addr);
2446 #endif
2448 /* Return the number of memory refs to addresses that vary
2449 in the rtx X. */
2451 static int
2452 count_nonfixed_reads (loop, x)
2453 const struct loop *loop;
2454 rtx x;
2456 enum rtx_code code;
2457 int i;
2458 const char *fmt;
2459 int value;
2461 if (x == 0)
2462 return 0;
2464 code = GET_CODE (x);
2465 switch (code)
2467 case PC:
2468 case CC0:
2469 case CONST_INT:
2470 case CONST_DOUBLE:
2471 case CONST:
2472 case SYMBOL_REF:
2473 case LABEL_REF:
2474 case REG:
2475 return 0;
2477 case MEM:
2478 return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2479 + count_nonfixed_reads (loop, XEXP (x, 0)));
2481 default:
2482 break;
2485 value = 0;
2486 fmt = GET_RTX_FORMAT (code);
2487 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2489 if (fmt[i] == 'e')
2490 value += count_nonfixed_reads (loop, XEXP (x, i));
2491 if (fmt[i] == 'E')
2493 int j;
2494 for (j = 0; j < XVECLEN (x, i); j++)
2495 value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2498 return value;
2501 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2502 `has_call', `has_nonconst_call', `has_volatile', `has_tablejump',
2503 `unknown_address_altered', `unknown_constant_address_altered', and
2504 `num_mem_sets' in LOOP. Also, fill in the array `mems' and the
2505 list `store_mems' in LOOP. */
2507 static void
2508 prescan_loop (loop)
2509 struct loop *loop;
2511 int level = 1;
2512 rtx insn;
2513 struct loop_info *loop_info = LOOP_INFO (loop);
2514 rtx start = loop->start;
2515 rtx end = loop->end;
2516 /* The label after END. Jumping here is just like falling off the
2517 end of the loop. We use next_nonnote_insn instead of next_label
2518 as a hedge against the (pathological) case where some actual insn
2519 might end up between the two. */
2520 rtx exit_target = next_nonnote_insn (end);
2522 loop_info->has_indirect_jump = indirect_jump_in_function;
2523 loop_info->pre_header_has_call = 0;
2524 loop_info->has_call = 0;
2525 loop_info->has_nonconst_call = 0;
2526 loop_info->has_prefetch = 0;
2527 loop_info->has_volatile = 0;
2528 loop_info->has_tablejump = 0;
2529 loop_info->has_multiple_exit_targets = 0;
2530 loop->level = 1;
2532 loop_info->unknown_address_altered = 0;
2533 loop_info->unknown_constant_address_altered = 0;
2534 loop_info->store_mems = NULL_RTX;
2535 loop_info->first_loop_store_insn = NULL_RTX;
2536 loop_info->mems_idx = 0;
2537 loop_info->num_mem_sets = 0;
2538 /* If loop opts run twice, this was set on 1st pass for 2nd. */
2539 loop_info->preconditioned = NOTE_PRECONDITIONED (end);
2541 for (insn = start; insn && GET_CODE (insn) != CODE_LABEL;
2542 insn = PREV_INSN (insn))
2544 if (GET_CODE (insn) == CALL_INSN)
2546 loop_info->pre_header_has_call = 1;
2547 break;
2551 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2552 insn = NEXT_INSN (insn))
2554 switch (GET_CODE (insn))
2556 case NOTE:
2557 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2559 ++level;
2560 /* Count number of loops contained in this one. */
2561 loop->level++;
2563 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2564 --level;
2565 break;
2567 case CALL_INSN:
2568 if (! CONST_OR_PURE_CALL_P (insn))
2570 loop_info->unknown_address_altered = 1;
2571 loop_info->has_nonconst_call = 1;
2573 else if (pure_call_p (insn))
2574 loop_info->has_nonconst_call = 1;
2575 loop_info->has_call = 1;
2576 if (can_throw_internal (insn))
2577 loop_info->has_multiple_exit_targets = 1;
2579 /* Calls initializing constant objects have CLOBBER of MEM /u in the
2580 attached FUNCTION_USAGE expression list, not accounted for by the
2581 code above. We should note these to avoid missing dependencies in
2582 later references. */
2584 rtx fusage_entry;
2586 for (fusage_entry = CALL_INSN_FUNCTION_USAGE (insn);
2587 fusage_entry; fusage_entry = XEXP (fusage_entry, 1))
2589 rtx fusage = XEXP (fusage_entry, 0);
2591 if (GET_CODE (fusage) == CLOBBER
2592 && GET_CODE (XEXP (fusage, 0)) == MEM
2593 && RTX_UNCHANGING_P (XEXP (fusage, 0)))
2595 note_stores (fusage, note_addr_stored, loop_info);
2596 if (! loop_info->first_loop_store_insn
2597 && loop_info->store_mems)
2598 loop_info->first_loop_store_insn = insn;
2602 break;
2604 case JUMP_INSN:
2605 if (! loop_info->has_multiple_exit_targets)
2607 rtx set = pc_set (insn);
2609 if (set)
2611 rtx src = SET_SRC (set);
2612 rtx label1, label2;
2614 if (GET_CODE (src) == IF_THEN_ELSE)
2616 label1 = XEXP (src, 1);
2617 label2 = XEXP (src, 2);
2619 else
2621 label1 = src;
2622 label2 = NULL_RTX;
2627 if (label1 && label1 != pc_rtx)
2629 if (GET_CODE (label1) != LABEL_REF)
2631 /* Something tricky. */
2632 loop_info->has_multiple_exit_targets = 1;
2633 break;
2635 else if (XEXP (label1, 0) != exit_target
2636 && LABEL_OUTSIDE_LOOP_P (label1))
2638 /* A jump outside the current loop. */
2639 loop_info->has_multiple_exit_targets = 1;
2640 break;
2644 label1 = label2;
2645 label2 = NULL_RTX;
2647 while (label1);
2649 else
2651 /* A return, or something tricky. */
2652 loop_info->has_multiple_exit_targets = 1;
2655 /* FALLTHRU */
2657 case INSN:
2658 if (volatile_refs_p (PATTERN (insn)))
2659 loop_info->has_volatile = 1;
2661 if (GET_CODE (insn) == JUMP_INSN
2662 && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2663 || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2664 loop_info->has_tablejump = 1;
2666 note_stores (PATTERN (insn), note_addr_stored, loop_info);
2667 if (! loop_info->first_loop_store_insn && loop_info->store_mems)
2668 loop_info->first_loop_store_insn = insn;
2670 if (flag_non_call_exceptions && can_throw_internal (insn))
2671 loop_info->has_multiple_exit_targets = 1;
2672 break;
2674 default:
2675 break;
2679 /* Now, rescan the loop, setting up the LOOP_MEMS array. */
2680 if (/* An exception thrown by a called function might land us
2681 anywhere. */
2682 ! loop_info->has_nonconst_call
2683 /* We don't want loads for MEMs moved to a location before the
2684 one at which their stack memory becomes allocated. (Note
2685 that this is not a problem for malloc, etc., since those
2686 require actual function calls. */
2687 && ! current_function_calls_alloca
2688 /* There are ways to leave the loop other than falling off the
2689 end. */
2690 && ! loop_info->has_multiple_exit_targets)
2691 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2692 insn = NEXT_INSN (insn))
2693 for_each_rtx (&insn, insert_loop_mem, loop_info);
2695 /* BLKmode MEMs are added to LOOP_STORE_MEM as necessary so
2696 that loop_invariant_p and load_mems can use true_dependence
2697 to determine what is really clobbered. */
2698 if (loop_info->unknown_address_altered)
2700 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2702 loop_info->store_mems
2703 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2705 if (loop_info->unknown_constant_address_altered)
2707 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2709 RTX_UNCHANGING_P (mem) = 1;
2710 loop_info->store_mems
2711 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2715 /* Invalidate all loops containing LABEL. */
2717 static void
2718 invalidate_loops_containing_label (label)
2719 rtx label;
2721 struct loop *loop;
2722 for (loop = uid_loop[INSN_UID (label)]; loop; loop = loop->outer)
2723 loop->invalid = 1;
2726 /* Scan the function looking for loops. Record the start and end of each loop.
2727 Also mark as invalid loops any loops that contain a setjmp or are branched
2728 to from outside the loop. */
2730 static void
2731 find_and_verify_loops (f, loops)
2732 rtx f;
2733 struct loops *loops;
2735 rtx insn;
2736 rtx label;
2737 int num_loops;
2738 struct loop *current_loop;
2739 struct loop *next_loop;
2740 struct loop *loop;
2742 num_loops = loops->num;
2744 compute_luids (f, NULL_RTX, 0);
2746 /* If there are jumps to undefined labels,
2747 treat them as jumps out of any/all loops.
2748 This also avoids writing past end of tables when there are no loops. */
2749 uid_loop[0] = NULL;
2751 /* Find boundaries of loops, mark which loops are contained within
2752 loops, and invalidate loops that have setjmp. */
2754 num_loops = 0;
2755 current_loop = NULL;
2756 for (insn = f; insn; insn = NEXT_INSN (insn))
2758 if (GET_CODE (insn) == NOTE)
2759 switch (NOTE_LINE_NUMBER (insn))
2761 case NOTE_INSN_LOOP_BEG:
2762 next_loop = loops->array + num_loops;
2763 next_loop->num = num_loops;
2764 num_loops++;
2765 next_loop->start = insn;
2766 next_loop->outer = current_loop;
2767 current_loop = next_loop;
2768 break;
2770 case NOTE_INSN_LOOP_CONT:
2771 current_loop->cont = insn;
2772 break;
2774 case NOTE_INSN_LOOP_VTOP:
2775 current_loop->vtop = insn;
2776 break;
2778 case NOTE_INSN_LOOP_END:
2779 if (! current_loop)
2780 abort ();
2782 current_loop->end = insn;
2783 current_loop = current_loop->outer;
2784 break;
2786 default:
2787 break;
2790 if (GET_CODE (insn) == CALL_INSN
2791 && find_reg_note (insn, REG_SETJMP, NULL))
2793 /* In this case, we must invalidate our current loop and any
2794 enclosing loop. */
2795 for (loop = current_loop; loop; loop = loop->outer)
2797 loop->invalid = 1;
2798 if (loop_dump_stream)
2799 fprintf (loop_dump_stream,
2800 "\nLoop at %d ignored due to setjmp.\n",
2801 INSN_UID (loop->start));
2805 /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2806 enclosing loop, but this doesn't matter. */
2807 uid_loop[INSN_UID (insn)] = current_loop;
2810 /* Any loop containing a label used in an initializer must be invalidated,
2811 because it can be jumped into from anywhere. */
2812 for (label = forced_labels; label; label = XEXP (label, 1))
2813 invalidate_loops_containing_label (XEXP (label, 0));
2815 /* Any loop containing a label used for an exception handler must be
2816 invalidated, because it can be jumped into from anywhere. */
2817 for_each_eh_label (invalidate_loops_containing_label);
2819 /* Now scan all insn's in the function. If any JUMP_INSN branches into a
2820 loop that it is not contained within, that loop is marked invalid.
2821 If any INSN or CALL_INSN uses a label's address, then the loop containing
2822 that label is marked invalid, because it could be jumped into from
2823 anywhere.
2825 Also look for blocks of code ending in an unconditional branch that
2826 exits the loop. If such a block is surrounded by a conditional
2827 branch around the block, move the block elsewhere (see below) and
2828 invert the jump to point to the code block. This may eliminate a
2829 label in our loop and will simplify processing by both us and a
2830 possible second cse pass. */
2832 for (insn = f; insn; insn = NEXT_INSN (insn))
2833 if (INSN_P (insn))
2835 struct loop *this_loop = uid_loop[INSN_UID (insn)];
2837 if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2839 rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2840 if (note)
2841 invalidate_loops_containing_label (XEXP (note, 0));
2844 if (GET_CODE (insn) != JUMP_INSN)
2845 continue;
2847 mark_loop_jump (PATTERN (insn), this_loop);
2849 /* See if this is an unconditional branch outside the loop. */
2850 if (this_loop
2851 && (GET_CODE (PATTERN (insn)) == RETURN
2852 || (any_uncondjump_p (insn)
2853 && onlyjump_p (insn)
2854 && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
2855 != this_loop)))
2856 && get_max_uid () < max_uid_for_loop)
2858 rtx p;
2859 rtx our_next = next_real_insn (insn);
2860 rtx last_insn_to_move = NEXT_INSN (insn);
2861 struct loop *dest_loop;
2862 struct loop *outer_loop = NULL;
2864 /* Go backwards until we reach the start of the loop, a label,
2865 or a JUMP_INSN. */
2866 for (p = PREV_INSN (insn);
2867 GET_CODE (p) != CODE_LABEL
2868 && ! (GET_CODE (p) == NOTE
2869 && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2870 && GET_CODE (p) != JUMP_INSN;
2871 p = PREV_INSN (p))
2874 /* Check for the case where we have a jump to an inner nested
2875 loop, and do not perform the optimization in that case. */
2877 if (JUMP_LABEL (insn))
2879 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
2880 if (dest_loop)
2882 for (outer_loop = dest_loop; outer_loop;
2883 outer_loop = outer_loop->outer)
2884 if (outer_loop == this_loop)
2885 break;
2889 /* Make sure that the target of P is within the current loop. */
2891 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2892 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
2893 outer_loop = this_loop;
2895 /* If we stopped on a JUMP_INSN to the next insn after INSN,
2896 we have a block of code to try to move.
2898 We look backward and then forward from the target of INSN
2899 to find a BARRIER at the same loop depth as the target.
2900 If we find such a BARRIER, we make a new label for the start
2901 of the block, invert the jump in P and point it to that label,
2902 and move the block of code to the spot we found. */
2904 if (! outer_loop
2905 && GET_CODE (p) == JUMP_INSN
2906 && JUMP_LABEL (p) != 0
2907 /* Just ignore jumps to labels that were never emitted.
2908 These always indicate compilation errors. */
2909 && INSN_UID (JUMP_LABEL (p)) != 0
2910 && any_condjump_p (p) && onlyjump_p (p)
2911 && next_real_insn (JUMP_LABEL (p)) == our_next
2912 /* If it's not safe to move the sequence, then we
2913 mustn't try. */
2914 && insns_safe_to_move_p (p, NEXT_INSN (insn),
2915 &last_insn_to_move))
2917 rtx target
2918 = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2919 struct loop *target_loop = uid_loop[INSN_UID (target)];
2920 rtx loc, loc2;
2921 rtx tmp;
2923 /* Search for possible garbage past the conditional jumps
2924 and look for the last barrier. */
2925 for (tmp = last_insn_to_move;
2926 tmp && GET_CODE (tmp) != CODE_LABEL; tmp = NEXT_INSN (tmp))
2927 if (GET_CODE (tmp) == BARRIER)
2928 last_insn_to_move = tmp;
2930 for (loc = target; loc; loc = PREV_INSN (loc))
2931 if (GET_CODE (loc) == BARRIER
2932 /* Don't move things inside a tablejump. */
2933 && ((loc2 = next_nonnote_insn (loc)) == 0
2934 || GET_CODE (loc2) != CODE_LABEL
2935 || (loc2 = next_nonnote_insn (loc2)) == 0
2936 || GET_CODE (loc2) != JUMP_INSN
2937 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2938 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2939 && uid_loop[INSN_UID (loc)] == target_loop)
2940 break;
2942 if (loc == 0)
2943 for (loc = target; loc; loc = NEXT_INSN (loc))
2944 if (GET_CODE (loc) == BARRIER
2945 /* Don't move things inside a tablejump. */
2946 && ((loc2 = next_nonnote_insn (loc)) == 0
2947 || GET_CODE (loc2) != CODE_LABEL
2948 || (loc2 = next_nonnote_insn (loc2)) == 0
2949 || GET_CODE (loc2) != JUMP_INSN
2950 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2951 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2952 && uid_loop[INSN_UID (loc)] == target_loop)
2953 break;
2955 if (loc)
2957 rtx cond_label = JUMP_LABEL (p);
2958 rtx new_label = get_label_after (p);
2960 /* Ensure our label doesn't go away. */
2961 LABEL_NUSES (cond_label)++;
2963 /* Verify that uid_loop is large enough and that
2964 we can invert P. */
2965 if (invert_jump (p, new_label, 1))
2967 rtx q, r;
2969 /* If no suitable BARRIER was found, create a suitable
2970 one before TARGET. Since TARGET is a fall through
2971 path, we'll need to insert a jump around our block
2972 and add a BARRIER before TARGET.
2974 This creates an extra unconditional jump outside
2975 the loop. However, the benefits of removing rarely
2976 executed instructions from inside the loop usually
2977 outweighs the cost of the extra unconditional jump
2978 outside the loop. */
2979 if (loc == 0)
2981 rtx temp;
2983 temp = gen_jump (JUMP_LABEL (insn));
2984 temp = emit_jump_insn_before (temp, target);
2985 JUMP_LABEL (temp) = JUMP_LABEL (insn);
2986 LABEL_NUSES (JUMP_LABEL (insn))++;
2987 loc = emit_barrier_before (target);
2990 /* Include the BARRIER after INSN and copy the
2991 block after LOC. */
2992 if (squeeze_notes (&new_label, &last_insn_to_move))
2993 abort ();
2994 reorder_insns (new_label, last_insn_to_move, loc);
2996 /* All those insns are now in TARGET_LOOP. */
2997 for (q = new_label;
2998 q != NEXT_INSN (last_insn_to_move);
2999 q = NEXT_INSN (q))
3000 uid_loop[INSN_UID (q)] = target_loop;
3002 /* The label jumped to by INSN is no longer a loop
3003 exit. Unless INSN does not have a label (e.g.,
3004 it is a RETURN insn), search loop->exit_labels
3005 to find its label_ref, and remove it. Also turn
3006 off LABEL_OUTSIDE_LOOP_P bit. */
3007 if (JUMP_LABEL (insn))
3009 for (q = 0, r = this_loop->exit_labels;
3011 q = r, r = LABEL_NEXTREF (r))
3012 if (XEXP (r, 0) == JUMP_LABEL (insn))
3014 LABEL_OUTSIDE_LOOP_P (r) = 0;
3015 if (q)
3016 LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
3017 else
3018 this_loop->exit_labels = LABEL_NEXTREF (r);
3019 break;
3022 for (loop = this_loop; loop && loop != target_loop;
3023 loop = loop->outer)
3024 loop->exit_count--;
3026 /* If we didn't find it, then something is
3027 wrong. */
3028 if (! r)
3029 abort ();
3032 /* P is now a jump outside the loop, so it must be put
3033 in loop->exit_labels, and marked as such.
3034 The easiest way to do this is to just call
3035 mark_loop_jump again for P. */
3036 mark_loop_jump (PATTERN (p), this_loop);
3038 /* If INSN now jumps to the insn after it,
3039 delete INSN. */
3040 if (JUMP_LABEL (insn) != 0
3041 && (next_real_insn (JUMP_LABEL (insn))
3042 == next_real_insn (insn)))
3043 delete_related_insns (insn);
3046 /* Continue the loop after where the conditional
3047 branch used to jump, since the only branch insn
3048 in the block (if it still remains) is an inter-loop
3049 branch and hence needs no processing. */
3050 insn = NEXT_INSN (cond_label);
3052 if (--LABEL_NUSES (cond_label) == 0)
3053 delete_related_insns (cond_label);
3055 /* This loop will be continued with NEXT_INSN (insn). */
3056 insn = PREV_INSN (insn);
3063 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
3064 loops it is contained in, mark the target loop invalid.
3066 For speed, we assume that X is part of a pattern of a JUMP_INSN. */
3068 static void
3069 mark_loop_jump (x, loop)
3070 rtx x;
3071 struct loop *loop;
3073 struct loop *dest_loop;
3074 struct loop *outer_loop;
3075 int i;
3077 switch (GET_CODE (x))
3079 case PC:
3080 case USE:
3081 case CLOBBER:
3082 case REG:
3083 case MEM:
3084 case CONST_INT:
3085 case CONST_DOUBLE:
3086 case RETURN:
3087 return;
3089 case CONST:
3090 /* There could be a label reference in here. */
3091 mark_loop_jump (XEXP (x, 0), loop);
3092 return;
3094 case PLUS:
3095 case MINUS:
3096 case MULT:
3097 mark_loop_jump (XEXP (x, 0), loop);
3098 mark_loop_jump (XEXP (x, 1), loop);
3099 return;
3101 case LO_SUM:
3102 /* This may refer to a LABEL_REF or SYMBOL_REF. */
3103 mark_loop_jump (XEXP (x, 1), loop);
3104 return;
3106 case SIGN_EXTEND:
3107 case ZERO_EXTEND:
3108 mark_loop_jump (XEXP (x, 0), loop);
3109 return;
3111 case LABEL_REF:
3112 dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3114 /* Link together all labels that branch outside the loop. This
3115 is used by final_[bg]iv_value and the loop unrolling code. Also
3116 mark this LABEL_REF so we know that this branch should predict
3117 false. */
3119 /* A check to make sure the label is not in an inner nested loop,
3120 since this does not count as a loop exit. */
3121 if (dest_loop)
3123 for (outer_loop = dest_loop; outer_loop;
3124 outer_loop = outer_loop->outer)
3125 if (outer_loop == loop)
3126 break;
3128 else
3129 outer_loop = NULL;
3131 if (loop && ! outer_loop)
3133 LABEL_OUTSIDE_LOOP_P (x) = 1;
3134 LABEL_NEXTREF (x) = loop->exit_labels;
3135 loop->exit_labels = x;
3137 for (outer_loop = loop;
3138 outer_loop && outer_loop != dest_loop;
3139 outer_loop = outer_loop->outer)
3140 outer_loop->exit_count++;
3143 /* If this is inside a loop, but not in the current loop or one enclosed
3144 by it, it invalidates at least one loop. */
3146 if (! dest_loop)
3147 return;
3149 /* We must invalidate every nested loop containing the target of this
3150 label, except those that also contain the jump insn. */
3152 for (; dest_loop; dest_loop = dest_loop->outer)
3154 /* Stop when we reach a loop that also contains the jump insn. */
3155 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3156 if (dest_loop == outer_loop)
3157 return;
3159 /* If we get here, we know we need to invalidate a loop. */
3160 if (loop_dump_stream && ! dest_loop->invalid)
3161 fprintf (loop_dump_stream,
3162 "\nLoop at %d ignored due to multiple entry points.\n",
3163 INSN_UID (dest_loop->start));
3165 dest_loop->invalid = 1;
3167 return;
3169 case SET:
3170 /* If this is not setting pc, ignore. */
3171 if (SET_DEST (x) == pc_rtx)
3172 mark_loop_jump (SET_SRC (x), loop);
3173 return;
3175 case IF_THEN_ELSE:
3176 mark_loop_jump (XEXP (x, 1), loop);
3177 mark_loop_jump (XEXP (x, 2), loop);
3178 return;
3180 case PARALLEL:
3181 case ADDR_VEC:
3182 for (i = 0; i < XVECLEN (x, 0); i++)
3183 mark_loop_jump (XVECEXP (x, 0, i), loop);
3184 return;
3186 case ADDR_DIFF_VEC:
3187 for (i = 0; i < XVECLEN (x, 1); i++)
3188 mark_loop_jump (XVECEXP (x, 1, i), loop);
3189 return;
3191 default:
3192 /* Strictly speaking this is not a jump into the loop, only a possible
3193 jump out of the loop. However, we have no way to link the destination
3194 of this jump onto the list of exit labels. To be safe we mark this
3195 loop and any containing loops as invalid. */
3196 if (loop)
3198 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3200 if (loop_dump_stream && ! outer_loop->invalid)
3201 fprintf (loop_dump_stream,
3202 "\nLoop at %d ignored due to unknown exit jump.\n",
3203 INSN_UID (outer_loop->start));
3204 outer_loop->invalid = 1;
3207 return;
3211 /* Return nonzero if there is a label in the range from
3212 insn INSN to and including the insn whose luid is END
3213 INSN must have an assigned luid (i.e., it must not have
3214 been previously created by loop.c). */
3216 static int
3217 labels_in_range_p (insn, end)
3218 rtx insn;
3219 int end;
3221 while (insn && INSN_LUID (insn) <= end)
3223 if (GET_CODE (insn) == CODE_LABEL)
3224 return 1;
3225 insn = NEXT_INSN (insn);
3228 return 0;
3231 /* Record that a memory reference X is being set. */
3233 static void
3234 note_addr_stored (x, y, data)
3235 rtx x;
3236 rtx y ATTRIBUTE_UNUSED;
3237 void *data ATTRIBUTE_UNUSED;
3239 struct loop_info *loop_info = data;
3241 if (x == 0 || GET_CODE (x) != MEM)
3242 return;
3244 /* Count number of memory writes.
3245 This affects heuristics in strength_reduce. */
3246 loop_info->num_mem_sets++;
3248 /* BLKmode MEM means all memory is clobbered. */
3249 if (GET_MODE (x) == BLKmode)
3251 if (RTX_UNCHANGING_P (x))
3252 loop_info->unknown_constant_address_altered = 1;
3253 else
3254 loop_info->unknown_address_altered = 1;
3256 return;
3259 loop_info->store_mems = gen_rtx_EXPR_LIST (VOIDmode, x,
3260 loop_info->store_mems);
3263 /* X is a value modified by an INSN that references a biv inside a loop
3264 exit test (ie, X is somehow related to the value of the biv). If X
3265 is a pseudo that is used more than once, then the biv is (effectively)
3266 used more than once. DATA is a pointer to a loop_regs structure. */
3268 static void
3269 note_set_pseudo_multiple_uses (x, y, data)
3270 rtx x;
3271 rtx y ATTRIBUTE_UNUSED;
3272 void *data;
3274 struct loop_regs *regs = (struct loop_regs *) data;
3276 if (x == 0)
3277 return;
3279 while (GET_CODE (x) == STRICT_LOW_PART
3280 || GET_CODE (x) == SIGN_EXTRACT
3281 || GET_CODE (x) == ZERO_EXTRACT
3282 || GET_CODE (x) == SUBREG)
3283 x = XEXP (x, 0);
3285 if (GET_CODE (x) != REG || REGNO (x) < FIRST_PSEUDO_REGISTER)
3286 return;
3288 /* If we do not have usage information, or if we know the register
3289 is used more than once, note that fact for check_dbra_loop. */
3290 if (REGNO (x) >= max_reg_before_loop
3291 || ! regs->array[REGNO (x)].single_usage
3292 || regs->array[REGNO (x)].single_usage == const0_rtx)
3293 regs->multiple_uses = 1;
3296 /* Return nonzero if the rtx X is invariant over the current loop.
3298 The value is 2 if we refer to something only conditionally invariant.
3300 A memory ref is invariant if it is not volatile and does not conflict
3301 with anything stored in `loop_info->store_mems'. */
3304 loop_invariant_p (loop, x)
3305 const struct loop *loop;
3306 rtx x;
3308 struct loop_info *loop_info = LOOP_INFO (loop);
3309 struct loop_regs *regs = LOOP_REGS (loop);
3310 int i;
3311 enum rtx_code code;
3312 const char *fmt;
3313 int conditional = 0;
3314 rtx mem_list_entry;
3316 if (x == 0)
3317 return 1;
3318 code = GET_CODE (x);
3319 switch (code)
3321 case CONST_INT:
3322 case CONST_DOUBLE:
3323 case SYMBOL_REF:
3324 case CONST:
3325 return 1;
3327 case LABEL_REF:
3328 /* A LABEL_REF is normally invariant, however, if we are unrolling
3329 loops, and this label is inside the loop, then it isn't invariant.
3330 This is because each unrolled copy of the loop body will have
3331 a copy of this label. If this was invariant, then an insn loading
3332 the address of this label into a register might get moved outside
3333 the loop, and then each loop body would end up using the same label.
3335 We don't know the loop bounds here though, so just fail for all
3336 labels. */
3337 if (flag_old_unroll_loops)
3338 return 0;
3339 else
3340 return 1;
3342 case PC:
3343 case CC0:
3344 case UNSPEC_VOLATILE:
3345 return 0;
3347 case REG:
3348 /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3349 since the reg might be set by initialization within the loop. */
3351 if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3352 || x == arg_pointer_rtx || x == pic_offset_table_rtx)
3353 && ! current_function_has_nonlocal_goto)
3354 return 1;
3356 if (LOOP_INFO (loop)->has_call
3357 && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3358 return 0;
3360 /* Out-of-range regs can occur when we are called from unrolling.
3361 These have always been created by the unroller and are set in
3362 the loop, hence are never invariant. */
3364 if (REGNO (x) >= (unsigned) regs->num)
3365 return 0;
3367 if (regs->array[REGNO (x)].set_in_loop < 0)
3368 return 2;
3370 return regs->array[REGNO (x)].set_in_loop == 0;
3372 case MEM:
3373 /* Volatile memory references must be rejected. Do this before
3374 checking for read-only items, so that volatile read-only items
3375 will be rejected also. */
3376 if (MEM_VOLATILE_P (x))
3377 return 0;
3379 /* See if there is any dependence between a store and this load. */
3380 mem_list_entry = loop_info->store_mems;
3381 while (mem_list_entry)
3383 if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3384 x, rtx_varies_p))
3385 return 0;
3387 mem_list_entry = XEXP (mem_list_entry, 1);
3390 /* It's not invalidated by a store in memory
3391 but we must still verify the address is invariant. */
3392 break;
3394 case ASM_OPERANDS:
3395 /* Don't mess with insns declared volatile. */
3396 if (MEM_VOLATILE_P (x))
3397 return 0;
3398 break;
3400 default:
3401 break;
3404 fmt = GET_RTX_FORMAT (code);
3405 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3407 if (fmt[i] == 'e')
3409 int tem = loop_invariant_p (loop, XEXP (x, i));
3410 if (tem == 0)
3411 return 0;
3412 if (tem == 2)
3413 conditional = 1;
3415 else if (fmt[i] == 'E')
3417 int j;
3418 for (j = 0; j < XVECLEN (x, i); j++)
3420 int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3421 if (tem == 0)
3422 return 0;
3423 if (tem == 2)
3424 conditional = 1;
3430 return 1 + conditional;
3433 /* Return nonzero if all the insns in the loop that set REG
3434 are INSN and the immediately following insns,
3435 and if each of those insns sets REG in an invariant way
3436 (not counting uses of REG in them).
3438 The value is 2 if some of these insns are only conditionally invariant.
3440 We assume that INSN itself is the first set of REG
3441 and that its source is invariant. */
3443 static int
3444 consec_sets_invariant_p (loop, reg, n_sets, insn)
3445 const struct loop *loop;
3446 int n_sets;
3447 rtx reg, insn;
3449 struct loop_regs *regs = LOOP_REGS (loop);
3450 rtx p = insn;
3451 unsigned int regno = REGNO (reg);
3452 rtx temp;
3453 /* Number of sets we have to insist on finding after INSN. */
3454 int count = n_sets - 1;
3455 int old = regs->array[regno].set_in_loop;
3456 int value = 0;
3457 int this;
3459 /* If N_SETS hit the limit, we can't rely on its value. */
3460 if (n_sets == 127)
3461 return 0;
3463 regs->array[regno].set_in_loop = 0;
3465 while (count > 0)
3467 enum rtx_code code;
3468 rtx set;
3470 p = NEXT_INSN (p);
3471 code = GET_CODE (p);
3473 /* If library call, skip to end of it. */
3474 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3475 p = XEXP (temp, 0);
3477 this = 0;
3478 if (code == INSN
3479 && (set = single_set (p))
3480 && GET_CODE (SET_DEST (set)) == REG
3481 && REGNO (SET_DEST (set)) == regno)
3483 this = loop_invariant_p (loop, SET_SRC (set));
3484 if (this != 0)
3485 value |= this;
3486 else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3488 /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3489 If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3490 notes are OK. */
3491 this = (CONSTANT_P (XEXP (temp, 0))
3492 || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3493 && loop_invariant_p (loop, XEXP (temp, 0))));
3494 if (this != 0)
3495 value |= this;
3498 if (this != 0)
3499 count--;
3500 else if (code != NOTE)
3502 regs->array[regno].set_in_loop = old;
3503 return 0;
3507 regs->array[regno].set_in_loop = old;
3508 /* If loop_invariant_p ever returned 2, we return 2. */
3509 return 1 + (value & 2);
3512 #if 0
3513 /* I don't think this condition is sufficient to allow INSN
3514 to be moved, so we no longer test it. */
3516 /* Return 1 if all insns in the basic block of INSN and following INSN
3517 that set REG are invariant according to TABLE. */
3519 static int
3520 all_sets_invariant_p (reg, insn, table)
3521 rtx reg, insn;
3522 short *table;
3524 rtx p = insn;
3525 int regno = REGNO (reg);
3527 while (1)
3529 enum rtx_code code;
3530 p = NEXT_INSN (p);
3531 code = GET_CODE (p);
3532 if (code == CODE_LABEL || code == JUMP_INSN)
3533 return 1;
3534 if (code == INSN && GET_CODE (PATTERN (p)) == SET
3535 && GET_CODE (SET_DEST (PATTERN (p))) == REG
3536 && REGNO (SET_DEST (PATTERN (p))) == regno)
3538 if (! loop_invariant_p (loop, SET_SRC (PATTERN (p)), table))
3539 return 0;
3543 #endif /* 0 */
3545 /* Look at all uses (not sets) of registers in X. For each, if it is
3546 the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3547 a different insn, set USAGE[REGNO] to const0_rtx. */
3549 static void
3550 find_single_use_in_loop (regs, insn, x)
3551 struct loop_regs *regs;
3552 rtx insn;
3553 rtx x;
3555 enum rtx_code code = GET_CODE (x);
3556 const char *fmt = GET_RTX_FORMAT (code);
3557 int i, j;
3559 if (code == REG)
3560 regs->array[REGNO (x)].single_usage
3561 = (regs->array[REGNO (x)].single_usage != 0
3562 && regs->array[REGNO (x)].single_usage != insn)
3563 ? const0_rtx : insn;
3565 else if (code == SET)
3567 /* Don't count SET_DEST if it is a REG; otherwise count things
3568 in SET_DEST because if a register is partially modified, it won't
3569 show up as a potential movable so we don't care how USAGE is set
3570 for it. */
3571 if (GET_CODE (SET_DEST (x)) != REG)
3572 find_single_use_in_loop (regs, insn, SET_DEST (x));
3573 find_single_use_in_loop (regs, insn, SET_SRC (x));
3575 else
3576 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3578 if (fmt[i] == 'e' && XEXP (x, i) != 0)
3579 find_single_use_in_loop (regs, insn, XEXP (x, i));
3580 else if (fmt[i] == 'E')
3581 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3582 find_single_use_in_loop (regs, insn, XVECEXP (x, i, j));
3586 /* Count and record any set in X which is contained in INSN. Update
3587 REGS->array[I].MAY_NOT_OPTIMIZE and LAST_SET for any register I set
3588 in X. */
3590 static void
3591 count_one_set (regs, insn, x, last_set)
3592 struct loop_regs *regs;
3593 rtx insn, x;
3594 rtx *last_set;
3596 if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3597 /* Don't move a reg that has an explicit clobber.
3598 It's not worth the pain to try to do it correctly. */
3599 regs->array[REGNO (XEXP (x, 0))].may_not_optimize = 1;
3601 if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3603 rtx dest = SET_DEST (x);
3604 while (GET_CODE (dest) == SUBREG
3605 || GET_CODE (dest) == ZERO_EXTRACT
3606 || GET_CODE (dest) == SIGN_EXTRACT
3607 || GET_CODE (dest) == STRICT_LOW_PART)
3608 dest = XEXP (dest, 0);
3609 if (GET_CODE (dest) == REG)
3611 int i;
3612 int regno = REGNO (dest);
3613 for (i = 0; i < LOOP_REGNO_NREGS (regno, dest); i++)
3615 /* If this is the first setting of this reg
3616 in current basic block, and it was set before,
3617 it must be set in two basic blocks, so it cannot
3618 be moved out of the loop. */
3619 if (regs->array[regno].set_in_loop > 0
3620 && last_set == 0)
3621 regs->array[regno+i].may_not_optimize = 1;
3622 /* If this is not first setting in current basic block,
3623 see if reg was used in between previous one and this.
3624 If so, neither one can be moved. */
3625 if (last_set[regno] != 0
3626 && reg_used_between_p (dest, last_set[regno], insn))
3627 regs->array[regno+i].may_not_optimize = 1;
3628 if (regs->array[regno+i].set_in_loop < 127)
3629 ++regs->array[regno+i].set_in_loop;
3630 last_set[regno+i] = insn;
3636 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3637 is entered at LOOP->SCAN_START, return 1 if the register set in SET
3638 contained in insn INSN is used by any insn that precedes INSN in
3639 cyclic order starting from the loop entry point.
3641 We don't want to use INSN_LUID here because if we restrict INSN to those
3642 that have a valid INSN_LUID, it means we cannot move an invariant out
3643 from an inner loop past two loops. */
3645 static int
3646 loop_reg_used_before_p (loop, set, insn)
3647 const struct loop *loop;
3648 rtx set, insn;
3650 rtx reg = SET_DEST (set);
3651 rtx p;
3653 /* Scan forward checking for register usage. If we hit INSN, we
3654 are done. Otherwise, if we hit LOOP->END, wrap around to LOOP->START. */
3655 for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3657 if (INSN_P (p) && reg_overlap_mentioned_p (reg, PATTERN (p)))
3658 return 1;
3660 if (p == loop->end)
3661 p = loop->start;
3664 return 0;
3668 /* Information we collect about arrays that we might want to prefetch. */
3669 struct prefetch_info
3671 struct iv_class *class; /* Class this prefetch is based on. */
3672 struct induction *giv; /* GIV this prefetch is based on. */
3673 rtx base_address; /* Start prefetching from this address plus
3674 index. */
3675 HOST_WIDE_INT index;
3676 HOST_WIDE_INT stride; /* Prefetch stride in bytes in each
3677 iteration. */
3678 unsigned int bytes_accessed; /* Sum of sizes of all accesses to this
3679 prefetch area in one iteration. */
3680 unsigned int total_bytes; /* Total bytes loop will access in this block.
3681 This is set only for loops with known
3682 iteration counts and is 0xffffffff
3683 otherwise. */
3684 int prefetch_in_loop; /* Number of prefetch insns in loop. */
3685 int prefetch_before_loop; /* Number of prefetch insns before loop. */
3686 unsigned int write : 1; /* 1 for read/write prefetches. */
3689 /* Data used by check_store function. */
3690 struct check_store_data
3692 rtx mem_address;
3693 int mem_write;
3696 static void check_store PARAMS ((rtx, rtx, void *));
3697 static void emit_prefetch_instructions PARAMS ((struct loop *));
3698 static int rtx_equal_for_prefetch_p PARAMS ((rtx, rtx));
3700 /* Set mem_write when mem_address is found. Used as callback to
3701 note_stores. */
3702 static void
3703 check_store (x, pat, data)
3704 rtx x, pat ATTRIBUTE_UNUSED;
3705 void *data;
3707 struct check_store_data *d = (struct check_store_data *) data;
3709 if ((GET_CODE (x) == MEM) && rtx_equal_p (d->mem_address, XEXP (x, 0)))
3710 d->mem_write = 1;
3713 /* Like rtx_equal_p, but attempts to swap commutative operands. This is
3714 important to get some addresses combined. Later more sophisticated
3715 transformations can be added when necessary.
3717 ??? Same trick with swapping operand is done at several other places.
3718 It can be nice to develop some common way to handle this. */
3720 static int
3721 rtx_equal_for_prefetch_p (x, y)
3722 rtx x, y;
3724 int i;
3725 int j;
3726 enum rtx_code code = GET_CODE (x);
3727 const char *fmt;
3729 if (x == y)
3730 return 1;
3731 if (code != GET_CODE (y))
3732 return 0;
3734 code = GET_CODE (x);
3736 if (GET_RTX_CLASS (code) == 'c')
3738 return ((rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 0))
3739 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 1)))
3740 || (rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 1))
3741 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 0))));
3743 /* Compare the elements. If any pair of corresponding elements fails to
3744 match, return 0 for the whole thing. */
3746 fmt = GET_RTX_FORMAT (code);
3747 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3749 switch (fmt[i])
3751 case 'w':
3752 if (XWINT (x, i) != XWINT (y, i))
3753 return 0;
3754 break;
3756 case 'i':
3757 if (XINT (x, i) != XINT (y, i))
3758 return 0;
3759 break;
3761 case 'E':
3762 /* Two vectors must have the same length. */
3763 if (XVECLEN (x, i) != XVECLEN (y, i))
3764 return 0;
3766 /* And the corresponding elements must match. */
3767 for (j = 0; j < XVECLEN (x, i); j++)
3768 if (rtx_equal_for_prefetch_p (XVECEXP (x, i, j),
3769 XVECEXP (y, i, j)) == 0)
3770 return 0;
3771 break;
3773 case 'e':
3774 if (rtx_equal_for_prefetch_p (XEXP (x, i), XEXP (y, i)) == 0)
3775 return 0;
3776 break;
3778 case 's':
3779 if (strcmp (XSTR (x, i), XSTR (y, i)))
3780 return 0;
3781 break;
3783 case 'u':
3784 /* These are just backpointers, so they don't matter. */
3785 break;
3787 case '0':
3788 break;
3790 /* It is believed that rtx's at this level will never
3791 contain anything but integers and other rtx's,
3792 except for within LABEL_REFs and SYMBOL_REFs. */
3793 default:
3794 abort ();
3797 return 1;
3800 /* Remove constant addition value from the expression X (when present)
3801 and return it. */
3803 static HOST_WIDE_INT
3804 remove_constant_addition (x)
3805 rtx *x;
3807 HOST_WIDE_INT addval = 0;
3808 rtx exp = *x;
3810 /* Avoid clobbering a shared CONST expression. */
3811 if (GET_CODE (exp) == CONST)
3813 if (GET_CODE (XEXP (exp, 0)) == PLUS
3814 && GET_CODE (XEXP (XEXP (exp, 0), 0)) == SYMBOL_REF
3815 && GET_CODE (XEXP (XEXP (exp, 0), 1)) == CONST_INT)
3817 *x = XEXP (XEXP (exp, 0), 0);
3818 return INTVAL (XEXP (XEXP (exp, 0), 1));
3820 return 0;
3823 if (GET_CODE (exp) == CONST_INT)
3825 addval = INTVAL (exp);
3826 *x = const0_rtx;
3829 /* For plus expression recurse on ourself. */
3830 else if (GET_CODE (exp) == PLUS)
3832 addval += remove_constant_addition (&XEXP (exp, 0));
3833 addval += remove_constant_addition (&XEXP (exp, 1));
3835 /* In case our parameter was constant, remove extra zero from the
3836 expression. */
3837 if (XEXP (exp, 0) == const0_rtx)
3838 *x = XEXP (exp, 1);
3839 else if (XEXP (exp, 1) == const0_rtx)
3840 *x = XEXP (exp, 0);
3843 return addval;
3846 /* Attempt to identify accesses to arrays that are most likely to cause cache
3847 misses, and emit prefetch instructions a few prefetch blocks forward.
3849 To detect the arrays we use the GIV information that was collected by the
3850 strength reduction pass.
3852 The prefetch instructions are generated after the GIV information is done
3853 and before the strength reduction process. The new GIVs are injected into
3854 the strength reduction tables, so the prefetch addresses are optimized as
3855 well.
3857 GIVs are split into base address, stride, and constant addition values.
3858 GIVs with the same address, stride and close addition values are combined
3859 into a single prefetch. Also writes to GIVs are detected, so that prefetch
3860 for write instructions can be used for the block we write to, on machines
3861 that support write prefetches.
3863 Several heuristics are used to determine when to prefetch. They are
3864 controlled by defined symbols that can be overridden for each target. */
3866 static void
3867 emit_prefetch_instructions (loop)
3868 struct loop *loop;
3870 int num_prefetches = 0;
3871 int num_real_prefetches = 0;
3872 int num_real_write_prefetches = 0;
3873 int num_prefetches_before = 0;
3874 int num_write_prefetches_before = 0;
3875 int ahead = 0;
3876 int i;
3877 struct iv_class *bl;
3878 struct induction *iv;
3879 struct prefetch_info info[MAX_PREFETCHES];
3880 struct loop_ivs *ivs = LOOP_IVS (loop);
3882 if (!HAVE_prefetch)
3883 return;
3885 /* Consider only loops w/o calls. When a call is done, the loop is probably
3886 slow enough to read the memory. */
3887 if (PREFETCH_NO_CALL && LOOP_INFO (loop)->has_call)
3889 if (loop_dump_stream)
3890 fprintf (loop_dump_stream, "Prefetch: ignoring loop: has call.\n");
3892 return;
3895 /* Don't prefetch in loops known to have few iterations. */
3896 if (PREFETCH_NO_LOW_LOOPCNT
3897 && LOOP_INFO (loop)->n_iterations
3898 && LOOP_INFO (loop)->n_iterations <= PREFETCH_LOW_LOOPCNT)
3900 if (loop_dump_stream)
3901 fprintf (loop_dump_stream,
3902 "Prefetch: ignoring loop: not enough iterations.\n");
3903 return;
3906 /* Search all induction variables and pick those interesting for the prefetch
3907 machinery. */
3908 for (bl = ivs->list; bl; bl = bl->next)
3910 struct induction *biv = bl->biv, *biv1;
3911 int basestride = 0;
3913 biv1 = biv;
3915 /* Expect all BIVs to be executed in each iteration. This makes our
3916 analysis more conservative. */
3917 while (biv1)
3919 /* Discard non-constant additions that we can't handle well yet, and
3920 BIVs that are executed multiple times; such BIVs ought to be
3921 handled in the nested loop. We accept not_every_iteration BIVs,
3922 since these only result in larger strides and make our
3923 heuristics more conservative. */
3924 if (GET_CODE (biv->add_val) != CONST_INT)
3926 if (loop_dump_stream)
3928 fprintf (loop_dump_stream,
3929 "Prefetch: ignoring biv %d: non-constant addition at insn %d:",
3930 REGNO (biv->src_reg), INSN_UID (biv->insn));
3931 print_rtl (loop_dump_stream, biv->add_val);
3932 fprintf (loop_dump_stream, "\n");
3934 break;
3937 if (biv->maybe_multiple)
3939 if (loop_dump_stream)
3941 fprintf (loop_dump_stream,
3942 "Prefetch: ignoring biv %d: maybe_multiple at insn %i:",
3943 REGNO (biv->src_reg), INSN_UID (biv->insn));
3944 print_rtl (loop_dump_stream, biv->add_val);
3945 fprintf (loop_dump_stream, "\n");
3947 break;
3950 basestride += INTVAL (biv1->add_val);
3951 biv1 = biv1->next_iv;
3954 if (biv1 || !basestride)
3955 continue;
3957 for (iv = bl->giv; iv; iv = iv->next_iv)
3959 rtx address;
3960 rtx temp;
3961 HOST_WIDE_INT index = 0;
3962 int add = 1;
3963 HOST_WIDE_INT stride = 0;
3964 int stride_sign = 1;
3965 struct check_store_data d;
3966 const char *ignore_reason = NULL;
3967 int size = GET_MODE_SIZE (GET_MODE (iv));
3969 /* See whether an induction variable is interesting to us and if
3970 not, report the reason. */
3971 if (iv->giv_type != DEST_ADDR)
3972 ignore_reason = "giv is not a destination address";
3974 /* We are interested only in constant stride memory references
3975 in order to be able to compute density easily. */
3976 else if (GET_CODE (iv->mult_val) != CONST_INT)
3977 ignore_reason = "stride is not constant";
3979 else
3981 stride = INTVAL (iv->mult_val) * basestride;
3982 if (stride < 0)
3984 stride = -stride;
3985 stride_sign = -1;
3988 /* On some targets, reversed order prefetches are not
3989 worthwhile. */
3990 if (PREFETCH_NO_REVERSE_ORDER && stride_sign < 0)
3991 ignore_reason = "reversed order stride";
3993 /* Prefetch of accesses with an extreme stride might not be
3994 worthwhile, either. */
3995 else if (PREFETCH_NO_EXTREME_STRIDE
3996 && stride > PREFETCH_EXTREME_STRIDE)
3997 ignore_reason = "extreme stride";
3999 /* Ignore GIVs with varying add values; we can't predict the
4000 value for the next iteration. */
4001 else if (!loop_invariant_p (loop, iv->add_val))
4002 ignore_reason = "giv has varying add value";
4004 /* Ignore GIVs in the nested loops; they ought to have been
4005 handled already. */
4006 else if (iv->maybe_multiple)
4007 ignore_reason = "giv is in nested loop";
4010 if (ignore_reason != NULL)
4012 if (loop_dump_stream)
4013 fprintf (loop_dump_stream,
4014 "Prefetch: ignoring giv at %d: %s.\n",
4015 INSN_UID (iv->insn), ignore_reason);
4016 continue;
4019 /* Determine the pointer to the basic array we are examining. It is
4020 the sum of the BIV's initial value and the GIV's add_val. */
4021 address = copy_rtx (iv->add_val);
4022 temp = copy_rtx (bl->initial_value);
4024 address = simplify_gen_binary (PLUS, Pmode, temp, address);
4025 index = remove_constant_addition (&address);
4027 d.mem_write = 0;
4028 d.mem_address = *iv->location;
4030 /* When the GIV is not always executed, we might be better off by
4031 not dirtying the cache pages. */
4032 if (PREFETCH_CONDITIONAL || iv->always_executed)
4033 note_stores (PATTERN (iv->insn), check_store, &d);
4034 else
4036 if (loop_dump_stream)
4037 fprintf (loop_dump_stream, "Prefetch: Ignoring giv at %d: %s\n",
4038 INSN_UID (iv->insn), "in conditional code.");
4039 continue;
4042 /* Attempt to find another prefetch to the same array and see if we
4043 can merge this one. */
4044 for (i = 0; i < num_prefetches; i++)
4045 if (rtx_equal_for_prefetch_p (address, info[i].base_address)
4046 && stride == info[i].stride)
4048 /* In case both access same array (same location
4049 just with small difference in constant indexes), merge
4050 the prefetches. Just do the later and the earlier will
4051 get prefetched from previous iteration.
4052 The artificial threshold should not be too small,
4053 but also not bigger than small portion of memory usually
4054 traversed by single loop. */
4055 if (index >= info[i].index
4056 && index - info[i].index < PREFETCH_EXTREME_DIFFERENCE)
4058 info[i].write |= d.mem_write;
4059 info[i].bytes_accessed += size;
4060 info[i].index = index;
4061 info[i].giv = iv;
4062 info[i].class = bl;
4063 info[num_prefetches].base_address = address;
4064 add = 0;
4065 break;
4068 if (index < info[i].index
4069 && info[i].index - index < PREFETCH_EXTREME_DIFFERENCE)
4071 info[i].write |= d.mem_write;
4072 info[i].bytes_accessed += size;
4073 add = 0;
4074 break;
4078 /* Merging failed. */
4079 if (add)
4081 info[num_prefetches].giv = iv;
4082 info[num_prefetches].class = bl;
4083 info[num_prefetches].index = index;
4084 info[num_prefetches].stride = stride;
4085 info[num_prefetches].base_address = address;
4086 info[num_prefetches].write = d.mem_write;
4087 info[num_prefetches].bytes_accessed = size;
4088 num_prefetches++;
4089 if (num_prefetches >= MAX_PREFETCHES)
4091 if (loop_dump_stream)
4092 fprintf (loop_dump_stream,
4093 "Maximal number of prefetches exceeded.\n");
4094 return;
4100 for (i = 0; i < num_prefetches; i++)
4102 int density;
4104 /* Attempt to calculate the total number of bytes fetched by all
4105 iterations of the loop. Avoid overflow. */
4106 if (LOOP_INFO (loop)->n_iterations
4107 && ((unsigned HOST_WIDE_INT) (0xffffffff / info[i].stride)
4108 >= LOOP_INFO (loop)->n_iterations))
4109 info[i].total_bytes = info[i].stride * LOOP_INFO (loop)->n_iterations;
4110 else
4111 info[i].total_bytes = 0xffffffff;
4113 density = info[i].bytes_accessed * 100 / info[i].stride;
4115 /* Prefetch might be worthwhile only when the loads/stores are dense. */
4116 if (PREFETCH_ONLY_DENSE_MEM)
4117 if (density * 256 > PREFETCH_DENSE_MEM * 100
4118 && (info[i].total_bytes / PREFETCH_BLOCK
4119 >= PREFETCH_BLOCKS_BEFORE_LOOP_MIN))
4121 info[i].prefetch_before_loop = 1;
4122 info[i].prefetch_in_loop
4123 = (info[i].total_bytes / PREFETCH_BLOCK
4124 > PREFETCH_BLOCKS_BEFORE_LOOP_MAX);
4126 else
4128 info[i].prefetch_in_loop = 0, info[i].prefetch_before_loop = 0;
4129 if (loop_dump_stream)
4130 fprintf (loop_dump_stream,
4131 "Prefetch: ignoring giv at %d: %d%% density is too low.\n",
4132 INSN_UID (info[i].giv->insn), density);
4134 else
4135 info[i].prefetch_in_loop = 1, info[i].prefetch_before_loop = 1;
4137 /* Find how many prefetch instructions we'll use within the loop. */
4138 if (info[i].prefetch_in_loop != 0)
4140 info[i].prefetch_in_loop = ((info[i].stride + PREFETCH_BLOCK - 1)
4141 / PREFETCH_BLOCK);
4142 num_real_prefetches += info[i].prefetch_in_loop;
4143 if (info[i].write)
4144 num_real_write_prefetches += info[i].prefetch_in_loop;
4148 /* Determine how many iterations ahead to prefetch within the loop, based
4149 on how many prefetches we currently expect to do within the loop. */
4150 if (num_real_prefetches != 0)
4152 if ((ahead = SIMULTANEOUS_PREFETCHES / num_real_prefetches) == 0)
4154 if (loop_dump_stream)
4155 fprintf (loop_dump_stream,
4156 "Prefetch: ignoring prefetches within loop: ahead is zero; %d < %d\n",
4157 SIMULTANEOUS_PREFETCHES, num_real_prefetches);
4158 num_real_prefetches = 0, num_real_write_prefetches = 0;
4161 /* We'll also use AHEAD to determine how many prefetch instructions to
4162 emit before a loop, so don't leave it zero. */
4163 if (ahead == 0)
4164 ahead = PREFETCH_BLOCKS_BEFORE_LOOP_MAX;
4166 for (i = 0; i < num_prefetches; i++)
4168 /* Update if we've decided not to prefetch anything within the loop. */
4169 if (num_real_prefetches == 0)
4170 info[i].prefetch_in_loop = 0;
4172 /* Find how many prefetch instructions we'll use before the loop. */
4173 if (info[i].prefetch_before_loop != 0)
4175 int n = info[i].total_bytes / PREFETCH_BLOCK;
4176 if (n > ahead)
4177 n = ahead;
4178 info[i].prefetch_before_loop = n;
4179 num_prefetches_before += n;
4180 if (info[i].write)
4181 num_write_prefetches_before += n;
4184 if (loop_dump_stream)
4186 if (info[i].prefetch_in_loop == 0
4187 && info[i].prefetch_before_loop == 0)
4188 continue;
4189 fprintf (loop_dump_stream, "Prefetch insn: %d",
4190 INSN_UID (info[i].giv->insn));
4191 fprintf (loop_dump_stream,
4192 "; in loop: %d; before: %d; %s\n",
4193 info[i].prefetch_in_loop,
4194 info[i].prefetch_before_loop,
4195 info[i].write ? "read/write" : "read only");
4196 fprintf (loop_dump_stream,
4197 " density: %d%%; bytes_accessed: %u; total_bytes: %u\n",
4198 (int) (info[i].bytes_accessed * 100 / info[i].stride),
4199 info[i].bytes_accessed, info[i].total_bytes);
4200 fprintf (loop_dump_stream, " index: " HOST_WIDE_INT_PRINT_DEC
4201 "; stride: " HOST_WIDE_INT_PRINT_DEC "; address: ",
4202 info[i].index, info[i].stride);
4203 print_rtl (loop_dump_stream, info[i].base_address);
4204 fprintf (loop_dump_stream, "\n");
4208 if (num_real_prefetches + num_prefetches_before > 0)
4210 /* Record that this loop uses prefetch instructions. */
4211 LOOP_INFO (loop)->has_prefetch = 1;
4213 if (loop_dump_stream)
4215 fprintf (loop_dump_stream, "Real prefetches needed within loop: %d (write: %d)\n",
4216 num_real_prefetches, num_real_write_prefetches);
4217 fprintf (loop_dump_stream, "Real prefetches needed before loop: %d (write: %d)\n",
4218 num_prefetches_before, num_write_prefetches_before);
4222 for (i = 0; i < num_prefetches; i++)
4224 int y;
4226 for (y = 0; y < info[i].prefetch_in_loop; y++)
4228 rtx loc = copy_rtx (*info[i].giv->location);
4229 rtx insn;
4230 int bytes_ahead = PREFETCH_BLOCK * (ahead + y);
4231 rtx before_insn = info[i].giv->insn;
4232 rtx prev_insn = PREV_INSN (info[i].giv->insn);
4233 rtx seq;
4235 /* We can save some effort by offsetting the address on
4236 architectures with offsettable memory references. */
4237 if (offsettable_address_p (0, VOIDmode, loc))
4238 loc = plus_constant (loc, bytes_ahead);
4239 else
4241 rtx reg = gen_reg_rtx (Pmode);
4242 loop_iv_add_mult_emit_before (loop, loc, const1_rtx,
4243 GEN_INT (bytes_ahead), reg,
4244 0, before_insn);
4245 loc = reg;
4248 start_sequence ();
4249 /* Make sure the address operand is valid for prefetch. */
4250 if (! (*insn_data[(int)CODE_FOR_prefetch].operand[0].predicate)
4251 (loc, insn_data[(int)CODE_FOR_prefetch].operand[0].mode))
4252 loc = force_reg (Pmode, loc);
4253 emit_insn (gen_prefetch (loc, GEN_INT (info[i].write),
4254 GEN_INT (3)));
4255 seq = get_insns ();
4256 end_sequence ();
4257 emit_insn_before (seq, before_insn);
4259 /* Check all insns emitted and record the new GIV
4260 information. */
4261 insn = NEXT_INSN (prev_insn);
4262 while (insn != before_insn)
4264 insn = check_insn_for_givs (loop, insn,
4265 info[i].giv->always_executed,
4266 info[i].giv->maybe_multiple);
4267 insn = NEXT_INSN (insn);
4271 if (PREFETCH_BEFORE_LOOP)
4273 /* Emit insns before the loop to fetch the first cache lines or,
4274 if we're not prefetching within the loop, everything we expect
4275 to need. */
4276 for (y = 0; y < info[i].prefetch_before_loop; y++)
4278 rtx reg = gen_reg_rtx (Pmode);
4279 rtx loop_start = loop->start;
4280 rtx init_val = info[i].class->initial_value;
4281 rtx add_val = simplify_gen_binary (PLUS, Pmode,
4282 info[i].giv->add_val,
4283 GEN_INT (y * PREFETCH_BLOCK));
4285 /* Functions called by LOOP_IV_ADD_EMIT_BEFORE expect a
4286 non-constant INIT_VAL to have the same mode as REG, which
4287 in this case we know to be Pmode. */
4288 if (GET_MODE (init_val) != Pmode && !CONSTANT_P (init_val))
4290 rtx seq;
4292 start_sequence ();
4293 init_val = convert_to_mode (Pmode, init_val, 0);
4294 seq = get_insns ();
4295 end_sequence ();
4296 loop_insn_emit_before (loop, 0, loop_start, seq);
4298 loop_iv_add_mult_emit_before (loop, init_val,
4299 info[i].giv->mult_val,
4300 add_val, reg, 0, loop_start);
4301 emit_insn_before (gen_prefetch (reg, GEN_INT (info[i].write),
4302 GEN_INT (3)),
4303 loop_start);
4308 return;
4311 /* A "basic induction variable" or biv is a pseudo reg that is set
4312 (within this loop) only by incrementing or decrementing it. */
4313 /* A "general induction variable" or giv is a pseudo reg whose
4314 value is a linear function of a biv. */
4316 /* Bivs are recognized by `basic_induction_var';
4317 Givs by `general_induction_var'. */
4319 /* Communication with routines called via `note_stores'. */
4321 static rtx note_insn;
4323 /* Dummy register to have nonzero DEST_REG for DEST_ADDR type givs. */
4325 static rtx addr_placeholder;
4327 /* ??? Unfinished optimizations, and possible future optimizations,
4328 for the strength reduction code. */
4330 /* ??? The interaction of biv elimination, and recognition of 'constant'
4331 bivs, may cause problems. */
4333 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
4334 performance problems.
4336 Perhaps don't eliminate things that can be combined with an addressing
4337 mode. Find all givs that have the same biv, mult_val, and add_val;
4338 then for each giv, check to see if its only use dies in a following
4339 memory address. If so, generate a new memory address and check to see
4340 if it is valid. If it is valid, then store the modified memory address,
4341 otherwise, mark the giv as not done so that it will get its own iv. */
4343 /* ??? Could try to optimize branches when it is known that a biv is always
4344 positive. */
4346 /* ??? When replace a biv in a compare insn, we should replace with closest
4347 giv so that an optimized branch can still be recognized by the combiner,
4348 e.g. the VAX acb insn. */
4350 /* ??? Many of the checks involving uid_luid could be simplified if regscan
4351 was rerun in loop_optimize whenever a register was added or moved.
4352 Also, some of the optimizations could be a little less conservative. */
4354 /* Scan the loop body and call FNCALL for each insn. In the addition to the
4355 LOOP and INSN parameters pass MAYBE_MULTIPLE and NOT_EVERY_ITERATION to the
4356 callback.
4358 NOT_EVERY_ITERATION is 1 if current insn is not known to be executed at
4359 least once for every loop iteration except for the last one.
4361 MAYBE_MULTIPLE is 1 if current insn may be executed more than once for every
4362 loop iteration.
4364 void
4365 for_each_insn_in_loop (loop, fncall)
4366 struct loop *loop;
4367 loop_insn_callback fncall;
4369 int not_every_iteration = 0;
4370 int maybe_multiple = 0;
4371 int past_loop_latch = 0;
4372 int loop_depth = 0;
4373 rtx p;
4375 /* If loop_scan_start points to the loop exit test, we have to be wary of
4376 subversive use of gotos inside expression statements. */
4377 if (prev_nonnote_insn (loop->scan_start) != prev_nonnote_insn (loop->start))
4378 maybe_multiple = back_branch_in_range_p (loop, loop->scan_start);
4380 /* Scan through loop and update NOT_EVERY_ITERATION and MAYBE_MULTIPLE. */
4381 for (p = next_insn_in_loop (loop, loop->scan_start);
4382 p != NULL_RTX;
4383 p = next_insn_in_loop (loop, p))
4385 p = fncall (loop, p, not_every_iteration, maybe_multiple);
4387 /* Past CODE_LABEL, we get to insns that may be executed multiple
4388 times. The only way we can be sure that they can't is if every
4389 jump insn between here and the end of the loop either
4390 returns, exits the loop, is a jump to a location that is still
4391 behind the label, or is a jump to the loop start. */
4393 if (GET_CODE (p) == CODE_LABEL)
4395 rtx insn = p;
4397 maybe_multiple = 0;
4399 while (1)
4401 insn = NEXT_INSN (insn);
4402 if (insn == loop->scan_start)
4403 break;
4404 if (insn == loop->end)
4406 if (loop->top != 0)
4407 insn = loop->top;
4408 else
4409 break;
4410 if (insn == loop->scan_start)
4411 break;
4414 if (GET_CODE (insn) == JUMP_INSN
4415 && GET_CODE (PATTERN (insn)) != RETURN
4416 && (!any_condjump_p (insn)
4417 || (JUMP_LABEL (insn) != 0
4418 && JUMP_LABEL (insn) != loop->scan_start
4419 && !loop_insn_first_p (p, JUMP_LABEL (insn)))))
4421 maybe_multiple = 1;
4422 break;
4427 /* Past a jump, we get to insns for which we can't count
4428 on whether they will be executed during each iteration. */
4429 /* This code appears twice in strength_reduce. There is also similar
4430 code in scan_loop. */
4431 if (GET_CODE (p) == JUMP_INSN
4432 /* If we enter the loop in the middle, and scan around to the
4433 beginning, don't set not_every_iteration for that.
4434 This can be any kind of jump, since we want to know if insns
4435 will be executed if the loop is executed. */
4436 && !(JUMP_LABEL (p) == loop->top
4437 && ((NEXT_INSN (NEXT_INSN (p)) == loop->end
4438 && any_uncondjump_p (p))
4439 || (NEXT_INSN (p) == loop->end && any_condjump_p (p)))))
4441 rtx label = 0;
4443 /* If this is a jump outside the loop, then it also doesn't
4444 matter. Check to see if the target of this branch is on the
4445 loop->exits_labels list. */
4447 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
4448 if (XEXP (label, 0) == JUMP_LABEL (p))
4449 break;
4451 if (!label)
4452 not_every_iteration = 1;
4455 else if (GET_CODE (p) == NOTE)
4457 /* At the virtual top of a converted loop, insns are again known to
4458 be executed each iteration: logically, the loop begins here
4459 even though the exit code has been duplicated.
4461 Insns are also again known to be executed each iteration at
4462 the LOOP_CONT note. */
4463 if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
4464 || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
4465 && loop_depth == 0)
4466 not_every_iteration = 0;
4467 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4468 loop_depth++;
4469 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4470 loop_depth--;
4473 /* Note if we pass a loop latch. If we do, then we can not clear
4474 NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
4475 a loop since a jump before the last CODE_LABEL may have started
4476 a new loop iteration.
4478 Note that LOOP_TOP is only set for rotated loops and we need
4479 this check for all loops, so compare against the CODE_LABEL
4480 which immediately follows LOOP_START. */
4481 if (GET_CODE (p) == JUMP_INSN
4482 && JUMP_LABEL (p) == NEXT_INSN (loop->start))
4483 past_loop_latch = 1;
4485 /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4486 an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4487 or not an insn is known to be executed each iteration of the
4488 loop, whether or not any iterations are known to occur.
4490 Therefore, if we have just passed a label and have no more labels
4491 between here and the test insn of the loop, and we have not passed
4492 a jump to the top of the loop, then we know these insns will be
4493 executed each iteration. */
4495 if (not_every_iteration
4496 && !past_loop_latch
4497 && GET_CODE (p) == CODE_LABEL
4498 && no_labels_between_p (p, loop->end)
4499 && loop_insn_first_p (p, loop->cont))
4500 not_every_iteration = 0;
4504 static void
4505 loop_bivs_find (loop)
4506 struct loop *loop;
4508 struct loop_regs *regs = LOOP_REGS (loop);
4509 struct loop_ivs *ivs = LOOP_IVS (loop);
4510 /* Temporary list pointers for traversing ivs->list. */
4511 struct iv_class *bl, **backbl;
4513 ivs->list = 0;
4515 for_each_insn_in_loop (loop, check_insn_for_bivs);
4517 /* Scan ivs->list to remove all regs that proved not to be bivs.
4518 Make a sanity check against regs->n_times_set. */
4519 for (backbl = &ivs->list, bl = *backbl; bl; bl = bl->next)
4521 if (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4522 /* Above happens if register modified by subreg, etc. */
4523 /* Make sure it is not recognized as a basic induction var: */
4524 || regs->array[bl->regno].n_times_set != bl->biv_count
4525 /* If never incremented, it is invariant that we decided not to
4526 move. So leave it alone. */
4527 || ! bl->incremented)
4529 if (loop_dump_stream)
4530 fprintf (loop_dump_stream, "Biv %d: discarded, %s\n",
4531 bl->regno,
4532 (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4533 ? "not induction variable"
4534 : (! bl->incremented ? "never incremented"
4535 : "count error")));
4537 REG_IV_TYPE (ivs, bl->regno) = NOT_BASIC_INDUCT;
4538 *backbl = bl->next;
4540 else
4542 backbl = &bl->next;
4544 if (loop_dump_stream)
4545 fprintf (loop_dump_stream, "Biv %d: verified\n", bl->regno);
4551 /* Determine how BIVS are initialized by looking through pre-header
4552 extended basic block. */
4553 static void
4554 loop_bivs_init_find (loop)
4555 struct loop *loop;
4557 struct loop_ivs *ivs = LOOP_IVS (loop);
4558 /* Temporary list pointers for traversing ivs->list. */
4559 struct iv_class *bl;
4560 int call_seen;
4561 rtx p;
4563 /* Find initial value for each biv by searching backwards from loop_start,
4564 halting at first label. Also record any test condition. */
4566 call_seen = 0;
4567 for (p = loop->start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
4569 rtx test;
4571 note_insn = p;
4573 if (GET_CODE (p) == CALL_INSN)
4574 call_seen = 1;
4576 if (INSN_P (p))
4577 note_stores (PATTERN (p), record_initial, ivs);
4579 /* Record any test of a biv that branches around the loop if no store
4580 between it and the start of loop. We only care about tests with
4581 constants and registers and only certain of those. */
4582 if (GET_CODE (p) == JUMP_INSN
4583 && JUMP_LABEL (p) != 0
4584 && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop->end)
4585 && (test = get_condition_for_loop (loop, p)) != 0
4586 && GET_CODE (XEXP (test, 0)) == REG
4587 && REGNO (XEXP (test, 0)) < max_reg_before_loop
4588 && (bl = REG_IV_CLASS (ivs, REGNO (XEXP (test, 0)))) != 0
4589 && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop->start)
4590 && bl->init_insn == 0)
4592 /* If an NE test, we have an initial value! */
4593 if (GET_CODE (test) == NE)
4595 bl->init_insn = p;
4596 bl->init_set = gen_rtx_SET (VOIDmode,
4597 XEXP (test, 0), XEXP (test, 1));
4599 else
4600 bl->initial_test = test;
4606 /* Look at the each biv and see if we can say anything better about its
4607 initial value from any initializing insns set up above. (This is done
4608 in two passes to avoid missing SETs in a PARALLEL.) */
4609 static void
4610 loop_bivs_check (loop)
4611 struct loop *loop;
4613 struct loop_ivs *ivs = LOOP_IVS (loop);
4614 /* Temporary list pointers for traversing ivs->list. */
4615 struct iv_class *bl;
4616 struct iv_class **backbl;
4618 for (backbl = &ivs->list; (bl = *backbl); backbl = &bl->next)
4620 rtx src;
4621 rtx note;
4623 if (! bl->init_insn)
4624 continue;
4626 /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4627 is a constant, use the value of that. */
4628 if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4629 && CONSTANT_P (XEXP (note, 0)))
4630 || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4631 && CONSTANT_P (XEXP (note, 0))))
4632 src = XEXP (note, 0);
4633 else
4634 src = SET_SRC (bl->init_set);
4636 if (loop_dump_stream)
4637 fprintf (loop_dump_stream,
4638 "Biv %d: initialized at insn %d: initial value ",
4639 bl->regno, INSN_UID (bl->init_insn));
4641 if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4642 || GET_MODE (src) == VOIDmode)
4643 && valid_initial_value_p (src, bl->init_insn,
4644 LOOP_INFO (loop)->pre_header_has_call,
4645 loop->start))
4647 bl->initial_value = src;
4649 if (loop_dump_stream)
4651 print_simple_rtl (loop_dump_stream, src);
4652 fputc ('\n', loop_dump_stream);
4655 /* If we can't make it a giv,
4656 let biv keep initial value of "itself". */
4657 else if (loop_dump_stream)
4658 fprintf (loop_dump_stream, "is complex\n");
4663 /* Search the loop for general induction variables. */
4665 static void
4666 loop_givs_find (loop)
4667 struct loop* loop;
4669 for_each_insn_in_loop (loop, check_insn_for_givs);
4673 /* For each giv for which we still don't know whether or not it is
4674 replaceable, check to see if it is replaceable because its final value
4675 can be calculated. */
4677 static void
4678 loop_givs_check (loop)
4679 struct loop *loop;
4681 struct loop_ivs *ivs = LOOP_IVS (loop);
4682 struct iv_class *bl;
4684 for (bl = ivs->list; bl; bl = bl->next)
4686 struct induction *v;
4688 for (v = bl->giv; v; v = v->next_iv)
4689 if (! v->replaceable && ! v->not_replaceable)
4690 check_final_value (loop, v);
4695 /* Return nonzero if it is possible to eliminate the biv BL provided
4696 all givs are reduced. This is possible if either the reg is not
4697 used outside the loop, or we can compute what its final value will
4698 be. */
4700 static int
4701 loop_biv_eliminable_p (loop, bl, threshold, insn_count)
4702 struct loop *loop;
4703 struct iv_class *bl;
4704 int threshold;
4705 int insn_count;
4707 /* For architectures with a decrement_and_branch_until_zero insn,
4708 don't do this if we put a REG_NONNEG note on the endtest for this
4709 biv. */
4711 #ifdef HAVE_decrement_and_branch_until_zero
4712 if (bl->nonneg)
4714 if (loop_dump_stream)
4715 fprintf (loop_dump_stream,
4716 "Cannot eliminate nonneg biv %d.\n", bl->regno);
4717 return 0;
4719 #endif
4721 /* Check that biv is used outside loop or if it has a final value.
4722 Compare against bl->init_insn rather than loop->start. We aren't
4723 concerned with any uses of the biv between init_insn and
4724 loop->start since these won't be affected by the value of the biv
4725 elsewhere in the function, so long as init_insn doesn't use the
4726 biv itself. */
4728 if ((REGNO_LAST_LUID (bl->regno) < INSN_LUID (loop->end)
4729 && bl->init_insn
4730 && INSN_UID (bl->init_insn) < max_uid_for_loop
4731 && REGNO_FIRST_LUID (bl->regno) >= INSN_LUID (bl->init_insn)
4732 && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4733 || (bl->final_value = final_biv_value (loop, bl)))
4734 return maybe_eliminate_biv (loop, bl, 0, threshold, insn_count);
4736 if (loop_dump_stream)
4738 fprintf (loop_dump_stream,
4739 "Cannot eliminate biv %d.\n",
4740 bl->regno);
4741 fprintf (loop_dump_stream,
4742 "First use: insn %d, last use: insn %d.\n",
4743 REGNO_FIRST_UID (bl->regno),
4744 REGNO_LAST_UID (bl->regno));
4746 return 0;
4750 /* Reduce each giv of BL that we have decided to reduce. */
4752 static void
4753 loop_givs_reduce (loop, bl)
4754 struct loop *loop;
4755 struct iv_class *bl;
4757 struct induction *v;
4759 for (v = bl->giv; v; v = v->next_iv)
4761 struct induction *tv;
4762 if (! v->ignore && v->same == 0)
4764 int auto_inc_opt = 0;
4766 /* If the code for derived givs immediately below has already
4767 allocated a new_reg, we must keep it. */
4768 if (! v->new_reg)
4769 v->new_reg = gen_reg_rtx (v->mode);
4771 #ifdef AUTO_INC_DEC
4772 /* If the target has auto-increment addressing modes, and
4773 this is an address giv, then try to put the increment
4774 immediately after its use, so that flow can create an
4775 auto-increment addressing mode. */
4776 if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4777 && bl->biv->always_executed && ! bl->biv->maybe_multiple
4778 /* We don't handle reversed biv's because bl->biv->insn
4779 does not have a valid INSN_LUID. */
4780 && ! bl->reversed
4781 && v->always_executed && ! v->maybe_multiple
4782 && INSN_UID (v->insn) < max_uid_for_loop)
4784 /* If other giv's have been combined with this one, then
4785 this will work only if all uses of the other giv's occur
4786 before this giv's insn. This is difficult to check.
4788 We simplify this by looking for the common case where
4789 there is one DEST_REG giv, and this giv's insn is the
4790 last use of the dest_reg of that DEST_REG giv. If the
4791 increment occurs after the address giv, then we can
4792 perform the optimization. (Otherwise, the increment
4793 would have to go before other_giv, and we would not be
4794 able to combine it with the address giv to get an
4795 auto-inc address.) */
4796 if (v->combined_with)
4798 struct induction *other_giv = 0;
4800 for (tv = bl->giv; tv; tv = tv->next_iv)
4801 if (tv->same == v)
4803 if (other_giv)
4804 break;
4805 else
4806 other_giv = tv;
4808 if (! tv && other_giv
4809 && REGNO (other_giv->dest_reg) < max_reg_before_loop
4810 && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4811 == INSN_UID (v->insn))
4812 && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4813 auto_inc_opt = 1;
4815 /* Check for case where increment is before the address
4816 giv. Do this test in "loop order". */
4817 else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4818 && (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4819 || (INSN_LUID (bl->biv->insn)
4820 > INSN_LUID (loop->scan_start))))
4821 || (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4822 && (INSN_LUID (loop->scan_start)
4823 < INSN_LUID (bl->biv->insn))))
4824 auto_inc_opt = -1;
4825 else
4826 auto_inc_opt = 1;
4828 #ifdef HAVE_cc0
4830 rtx prev;
4832 /* We can't put an insn immediately after one setting
4833 cc0, or immediately before one using cc0. */
4834 if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4835 || (auto_inc_opt == -1
4836 && (prev = prev_nonnote_insn (v->insn)) != 0
4837 && INSN_P (prev)
4838 && sets_cc0_p (PATTERN (prev))))
4839 auto_inc_opt = 0;
4841 #endif
4843 if (auto_inc_opt)
4844 v->auto_inc_opt = 1;
4846 #endif
4848 /* For each place where the biv is incremented, add an insn
4849 to increment the new, reduced reg for the giv. */
4850 for (tv = bl->biv; tv; tv = tv->next_iv)
4852 rtx insert_before;
4854 /* Skip if location is the same as a previous one. */
4855 if (tv->same)
4856 continue;
4857 if (! auto_inc_opt)
4858 insert_before = NEXT_INSN (tv->insn);
4859 else if (auto_inc_opt == 1)
4860 insert_before = NEXT_INSN (v->insn);
4861 else
4862 insert_before = v->insn;
4864 if (tv->mult_val == const1_rtx)
4865 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4866 v->new_reg, v->new_reg,
4867 0, insert_before);
4868 else /* tv->mult_val == const0_rtx */
4869 /* A multiply is acceptable here
4870 since this is presumed to be seldom executed. */
4871 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4872 v->add_val, v->new_reg,
4873 0, insert_before);
4876 /* Add code at loop start to initialize giv's reduced reg. */
4878 loop_iv_add_mult_hoist (loop,
4879 extend_value_for_giv (v, bl->initial_value),
4880 v->mult_val, v->add_val, v->new_reg);
4886 /* Check for givs whose first use is their definition and whose
4887 last use is the definition of another giv. If so, it is likely
4888 dead and should not be used to derive another giv nor to
4889 eliminate a biv. */
4891 static void
4892 loop_givs_dead_check (loop, bl)
4893 struct loop *loop ATTRIBUTE_UNUSED;
4894 struct iv_class *bl;
4896 struct induction *v;
4898 for (v = bl->giv; v; v = v->next_iv)
4900 if (v->ignore
4901 || (v->same && v->same->ignore))
4902 continue;
4904 if (v->giv_type == DEST_REG
4905 && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4907 struct induction *v1;
4909 for (v1 = bl->giv; v1; v1 = v1->next_iv)
4910 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4911 v->maybe_dead = 1;
4917 static void
4918 loop_givs_rescan (loop, bl, reg_map)
4919 struct loop *loop;
4920 struct iv_class *bl;
4921 rtx *reg_map;
4923 struct induction *v;
4925 for (v = bl->giv; v; v = v->next_iv)
4927 if (v->same && v->same->ignore)
4928 v->ignore = 1;
4930 if (v->ignore)
4931 continue;
4933 /* Update expression if this was combined, in case other giv was
4934 replaced. */
4935 if (v->same)
4936 v->new_reg = replace_rtx (v->new_reg,
4937 v->same->dest_reg, v->same->new_reg);
4939 /* See if this register is known to be a pointer to something. If
4940 so, see if we can find the alignment. First see if there is a
4941 destination register that is a pointer. If so, this shares the
4942 alignment too. Next see if we can deduce anything from the
4943 computational information. If not, and this is a DEST_ADDR
4944 giv, at least we know that it's a pointer, though we don't know
4945 the alignment. */
4946 if (GET_CODE (v->new_reg) == REG
4947 && v->giv_type == DEST_REG
4948 && REG_POINTER (v->dest_reg))
4949 mark_reg_pointer (v->new_reg,
4950 REGNO_POINTER_ALIGN (REGNO (v->dest_reg)));
4951 else if (GET_CODE (v->new_reg) == REG
4952 && REG_POINTER (v->src_reg))
4954 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->src_reg));
4956 if (align == 0
4957 || GET_CODE (v->add_val) != CONST_INT
4958 || INTVAL (v->add_val) % (align / BITS_PER_UNIT) != 0)
4959 align = 0;
4961 mark_reg_pointer (v->new_reg, align);
4963 else if (GET_CODE (v->new_reg) == REG
4964 && GET_CODE (v->add_val) == REG
4965 && REG_POINTER (v->add_val))
4967 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->add_val));
4969 if (align == 0 || GET_CODE (v->mult_val) != CONST_INT
4970 || INTVAL (v->mult_val) % (align / BITS_PER_UNIT) != 0)
4971 align = 0;
4973 mark_reg_pointer (v->new_reg, align);
4975 else if (GET_CODE (v->new_reg) == REG && v->giv_type == DEST_ADDR)
4976 mark_reg_pointer (v->new_reg, 0);
4978 if (v->giv_type == DEST_ADDR)
4979 /* Store reduced reg as the address in the memref where we found
4980 this giv. */
4981 validate_change (v->insn, v->location, v->new_reg, 0);
4982 else if (v->replaceable)
4984 reg_map[REGNO (v->dest_reg)] = v->new_reg;
4986 else
4988 rtx original_insn = v->insn;
4989 rtx note;
4991 /* Not replaceable; emit an insn to set the original giv reg from
4992 the reduced giv, same as above. */
4993 v->insn = loop_insn_emit_after (loop, 0, original_insn,
4994 gen_move_insn (v->dest_reg,
4995 v->new_reg));
4997 /* The original insn may have a REG_EQUAL note. This note is
4998 now incorrect and may result in invalid substitutions later.
4999 The original insn is dead, but may be part of a libcall
5000 sequence, which doesn't seem worth the bother of handling. */
5001 note = find_reg_note (original_insn, REG_EQUAL, NULL_RTX);
5002 if (note)
5003 remove_note (original_insn, note);
5006 /* When a loop is reversed, givs which depend on the reversed
5007 biv, and which are live outside the loop, must be set to their
5008 correct final value. This insn is only needed if the giv is
5009 not replaceable. The correct final value is the same as the
5010 value that the giv starts the reversed loop with. */
5011 if (bl->reversed && ! v->replaceable)
5012 loop_iv_add_mult_sink (loop,
5013 extend_value_for_giv (v, bl->initial_value),
5014 v->mult_val, v->add_val, v->dest_reg);
5015 else if (v->final_value)
5016 loop_insn_sink_or_swim (loop,
5017 gen_load_of_final_value (v->dest_reg,
5018 v->final_value));
5020 if (loop_dump_stream)
5022 fprintf (loop_dump_stream, "giv at %d reduced to ",
5023 INSN_UID (v->insn));
5024 print_simple_rtl (loop_dump_stream, v->new_reg);
5025 fprintf (loop_dump_stream, "\n");
5031 static int
5032 loop_giv_reduce_benefit (loop, bl, v, test_reg)
5033 struct loop *loop ATTRIBUTE_UNUSED;
5034 struct iv_class *bl;
5035 struct induction *v;
5036 rtx test_reg;
5038 int add_cost;
5039 int benefit;
5041 benefit = v->benefit;
5042 PUT_MODE (test_reg, v->mode);
5043 add_cost = iv_add_mult_cost (bl->biv->add_val, v->mult_val,
5044 test_reg, test_reg);
5046 /* Reduce benefit if not replaceable, since we will insert a
5047 move-insn to replace the insn that calculates this giv. Don't do
5048 this unless the giv is a user variable, since it will often be
5049 marked non-replaceable because of the duplication of the exit
5050 code outside the loop. In such a case, the copies we insert are
5051 dead and will be deleted. So they don't have a cost. Similar
5052 situations exist. */
5053 /* ??? The new final_[bg]iv_value code does a much better job of
5054 finding replaceable giv's, and hence this code may no longer be
5055 necessary. */
5056 if (! v->replaceable && ! bl->eliminable
5057 && REG_USERVAR_P (v->dest_reg))
5058 benefit -= copy_cost;
5060 /* Decrease the benefit to count the add-insns that we will insert
5061 to increment the reduced reg for the giv. ??? This can
5062 overestimate the run-time cost of the additional insns, e.g. if
5063 there are multiple basic blocks that increment the biv, but only
5064 one of these blocks is executed during each iteration. There is
5065 no good way to detect cases like this with the current structure
5066 of the loop optimizer. This code is more accurate for
5067 determining code size than run-time benefits. */
5068 benefit -= add_cost * bl->biv_count;
5070 /* Decide whether to strength-reduce this giv or to leave the code
5071 unchanged (recompute it from the biv each time it is used). This
5072 decision can be made independently for each giv. */
5074 #ifdef AUTO_INC_DEC
5075 /* Attempt to guess whether autoincrement will handle some of the
5076 new add insns; if so, increase BENEFIT (undo the subtraction of
5077 add_cost that was done above). */
5078 if (v->giv_type == DEST_ADDR
5079 /* Increasing the benefit is risky, since this is only a guess.
5080 Avoid increasing register pressure in cases where there would
5081 be no other benefit from reducing this giv. */
5082 && benefit > 0
5083 && GET_CODE (v->mult_val) == CONST_INT)
5085 int size = GET_MODE_SIZE (GET_MODE (v->mem));
5087 if (HAVE_POST_INCREMENT
5088 && INTVAL (v->mult_val) == size)
5089 benefit += add_cost * bl->biv_count;
5090 else if (HAVE_PRE_INCREMENT
5091 && INTVAL (v->mult_val) == size)
5092 benefit += add_cost * bl->biv_count;
5093 else if (HAVE_POST_DECREMENT
5094 && -INTVAL (v->mult_val) == size)
5095 benefit += add_cost * bl->biv_count;
5096 else if (HAVE_PRE_DECREMENT
5097 && -INTVAL (v->mult_val) == size)
5098 benefit += add_cost * bl->biv_count;
5100 #endif
5102 return benefit;
5106 /* Free IV structures for LOOP. */
5108 static void
5109 loop_ivs_free (loop)
5110 struct loop *loop;
5112 struct loop_ivs *ivs = LOOP_IVS (loop);
5113 struct iv_class *iv = ivs->list;
5115 free (ivs->regs);
5117 while (iv)
5119 struct iv_class *next = iv->next;
5120 struct induction *induction;
5121 struct induction *next_induction;
5123 for (induction = iv->biv; induction; induction = next_induction)
5125 next_induction = induction->next_iv;
5126 free (induction);
5128 for (induction = iv->giv; induction; induction = next_induction)
5130 next_induction = induction->next_iv;
5131 free (induction);
5134 free (iv);
5135 iv = next;
5140 /* Perform strength reduction and induction variable elimination.
5142 Pseudo registers created during this function will be beyond the
5143 last valid index in several tables including
5144 REGS->ARRAY[I].N_TIMES_SET and REGNO_LAST_UID. This does not cause a
5145 problem here, because the added registers cannot be givs outside of
5146 their loop, and hence will never be reconsidered. But scan_loop
5147 must check regnos to make sure they are in bounds. */
5149 static void
5150 strength_reduce (loop, flags)
5151 struct loop *loop;
5152 int flags;
5154 struct loop_info *loop_info = LOOP_INFO (loop);
5155 struct loop_regs *regs = LOOP_REGS (loop);
5156 struct loop_ivs *ivs = LOOP_IVS (loop);
5157 rtx p;
5158 /* Temporary list pointer for traversing ivs->list. */
5159 struct iv_class *bl;
5160 /* Ratio of extra register life span we can justify
5161 for saving an instruction. More if loop doesn't call subroutines
5162 since in that case saving an insn makes more difference
5163 and more registers are available. */
5164 /* ??? could set this to last value of threshold in move_movables */
5165 int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
5166 /* Map of pseudo-register replacements. */
5167 rtx *reg_map = NULL;
5168 int reg_map_size;
5169 int unrolled_insn_copies = 0;
5170 rtx test_reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
5171 int insn_count = count_insns_in_loop (loop);
5173 addr_placeholder = gen_reg_rtx (Pmode);
5175 ivs->n_regs = max_reg_before_loop;
5176 ivs->regs = (struct iv *) xcalloc (ivs->n_regs, sizeof (struct iv));
5178 /* Find all BIVs in loop. */
5179 loop_bivs_find (loop);
5181 /* Exit if there are no bivs. */
5182 if (! ivs->list)
5184 /* Can still unroll the loop anyways, but indicate that there is no
5185 strength reduction info available. */
5186 if (flags & LOOP_UNROLL)
5187 unroll_loop (loop, insn_count, 0);
5189 loop_ivs_free (loop);
5190 return;
5193 /* Determine how BIVS are initialized by looking through pre-header
5194 extended basic block. */
5195 loop_bivs_init_find (loop);
5197 /* Look at the each biv and see if we can say anything better about its
5198 initial value from any initializing insns set up above. */
5199 loop_bivs_check (loop);
5201 /* Search the loop for general induction variables. */
5202 loop_givs_find (loop);
5204 /* Try to calculate and save the number of loop iterations. This is
5205 set to zero if the actual number can not be calculated. This must
5206 be called after all giv's have been identified, since otherwise it may
5207 fail if the iteration variable is a giv. */
5208 loop_iterations (loop);
5210 #ifdef HAVE_prefetch
5211 if (flags & LOOP_PREFETCH)
5212 emit_prefetch_instructions (loop);
5213 #endif
5215 /* Now for each giv for which we still don't know whether or not it is
5216 replaceable, check to see if it is replaceable because its final value
5217 can be calculated. This must be done after loop_iterations is called,
5218 so that final_giv_value will work correctly. */
5219 loop_givs_check (loop);
5221 /* Try to prove that the loop counter variable (if any) is always
5222 nonnegative; if so, record that fact with a REG_NONNEG note
5223 so that "decrement and branch until zero" insn can be used. */
5224 check_dbra_loop (loop, insn_count);
5226 /* Create reg_map to hold substitutions for replaceable giv regs.
5227 Some givs might have been made from biv increments, so look at
5228 ivs->reg_iv_type for a suitable size. */
5229 reg_map_size = ivs->n_regs;
5230 reg_map = (rtx *) xcalloc (reg_map_size, sizeof (rtx));
5232 /* Examine each iv class for feasibility of strength reduction/induction
5233 variable elimination. */
5235 for (bl = ivs->list; bl; bl = bl->next)
5237 struct induction *v;
5238 int benefit;
5240 /* Test whether it will be possible to eliminate this biv
5241 provided all givs are reduced. */
5242 bl->eliminable = loop_biv_eliminable_p (loop, bl, threshold, insn_count);
5244 /* This will be true at the end, if all givs which depend on this
5245 biv have been strength reduced.
5246 We can't (currently) eliminate the biv unless this is so. */
5247 bl->all_reduced = 1;
5249 /* Check each extension dependent giv in this class to see if its
5250 root biv is safe from wrapping in the interior mode. */
5251 check_ext_dependent_givs (bl, loop_info);
5253 /* Combine all giv's for this iv_class. */
5254 combine_givs (regs, bl);
5256 for (v = bl->giv; v; v = v->next_iv)
5258 struct induction *tv;
5260 if (v->ignore || v->same)
5261 continue;
5263 benefit = loop_giv_reduce_benefit (loop, bl, v, test_reg);
5265 /* If an insn is not to be strength reduced, then set its ignore
5266 flag, and clear bl->all_reduced. */
5268 /* A giv that depends on a reversed biv must be reduced if it is
5269 used after the loop exit, otherwise, it would have the wrong
5270 value after the loop exit. To make it simple, just reduce all
5271 of such giv's whether or not we know they are used after the loop
5272 exit. */
5274 if (! flag_reduce_all_givs
5275 && v->lifetime * threshold * benefit < insn_count
5276 && ! bl->reversed)
5278 if (loop_dump_stream)
5279 fprintf (loop_dump_stream,
5280 "giv of insn %d not worth while, %d vs %d.\n",
5281 INSN_UID (v->insn),
5282 v->lifetime * threshold * benefit, insn_count);
5283 v->ignore = 1;
5284 bl->all_reduced = 0;
5286 else
5288 /* Check that we can increment the reduced giv without a
5289 multiply insn. If not, reject it. */
5291 for (tv = bl->biv; tv; tv = tv->next_iv)
5292 if (tv->mult_val == const1_rtx
5293 && ! product_cheap_p (tv->add_val, v->mult_val))
5295 if (loop_dump_stream)
5296 fprintf (loop_dump_stream,
5297 "giv of insn %d: would need a multiply.\n",
5298 INSN_UID (v->insn));
5299 v->ignore = 1;
5300 bl->all_reduced = 0;
5301 break;
5306 /* Check for givs whose first use is their definition and whose
5307 last use is the definition of another giv. If so, it is likely
5308 dead and should not be used to derive another giv nor to
5309 eliminate a biv. */
5310 loop_givs_dead_check (loop, bl);
5312 /* Reduce each giv that we decided to reduce. */
5313 loop_givs_reduce (loop, bl);
5315 /* Rescan all givs. If a giv is the same as a giv not reduced, mark it
5316 as not reduced.
5318 For each giv register that can be reduced now: if replaceable,
5319 substitute reduced reg wherever the old giv occurs;
5320 else add new move insn "giv_reg = reduced_reg". */
5321 loop_givs_rescan (loop, bl, reg_map);
5323 /* All the givs based on the biv bl have been reduced if they
5324 merit it. */
5326 /* For each giv not marked as maybe dead that has been combined with a
5327 second giv, clear any "maybe dead" mark on that second giv.
5328 v->new_reg will either be or refer to the register of the giv it
5329 combined with.
5331 Doing this clearing avoids problems in biv elimination where
5332 a giv's new_reg is a complex value that can't be put in the
5333 insn but the giv combined with (with a reg as new_reg) is
5334 marked maybe_dead. Since the register will be used in either
5335 case, we'd prefer it be used from the simpler giv. */
5337 for (v = bl->giv; v; v = v->next_iv)
5338 if (! v->maybe_dead && v->same)
5339 v->same->maybe_dead = 0;
5341 /* Try to eliminate the biv, if it is a candidate.
5342 This won't work if ! bl->all_reduced,
5343 since the givs we planned to use might not have been reduced.
5345 We have to be careful that we didn't initially think we could
5346 eliminate this biv because of a giv that we now think may be
5347 dead and shouldn't be used as a biv replacement.
5349 Also, there is the possibility that we may have a giv that looks
5350 like it can be used to eliminate a biv, but the resulting insn
5351 isn't valid. This can happen, for example, on the 88k, where a
5352 JUMP_INSN can compare a register only with zero. Attempts to
5353 replace it with a compare with a constant will fail.
5355 Note that in cases where this call fails, we may have replaced some
5356 of the occurrences of the biv with a giv, but no harm was done in
5357 doing so in the rare cases where it can occur. */
5359 if (bl->all_reduced == 1 && bl->eliminable
5360 && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
5362 /* ?? If we created a new test to bypass the loop entirely,
5363 or otherwise drop straight in, based on this test, then
5364 we might want to rewrite it also. This way some later
5365 pass has more hope of removing the initialization of this
5366 biv entirely. */
5368 /* If final_value != 0, then the biv may be used after loop end
5369 and we must emit an insn to set it just in case.
5371 Reversed bivs already have an insn after the loop setting their
5372 value, so we don't need another one. We can't calculate the
5373 proper final value for such a biv here anyways. */
5374 if (bl->final_value && ! bl->reversed)
5375 loop_insn_sink_or_swim (loop,
5376 gen_load_of_final_value (bl->biv->dest_reg,
5377 bl->final_value));
5379 if (loop_dump_stream)
5380 fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
5381 bl->regno);
5383 /* See above note wrt final_value. But since we couldn't eliminate
5384 the biv, we must set the value after the loop instead of before. */
5385 else if (bl->final_value && ! bl->reversed)
5386 loop_insn_sink (loop, gen_load_of_final_value (bl->biv->dest_reg,
5387 bl->final_value));
5390 /* Go through all the instructions in the loop, making all the
5391 register substitutions scheduled in REG_MAP. */
5393 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
5394 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5395 || GET_CODE (p) == CALL_INSN)
5397 replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
5398 replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
5399 INSN_CODE (p) = -1;
5402 if (loop_info->n_iterations > 0)
5404 /* When we completely unroll a loop we will likely not need the increment
5405 of the loop BIV and we will not need the conditional branch at the
5406 end of the loop. */
5407 unrolled_insn_copies = insn_count - 2;
5409 #ifdef HAVE_cc0
5410 /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5411 need the comparison before the conditional branch at the end of the
5412 loop. */
5413 unrolled_insn_copies -= 1;
5414 #endif
5416 /* We'll need one copy for each loop iteration. */
5417 unrolled_insn_copies *= loop_info->n_iterations;
5419 /* A little slop to account for the ability to remove initialization
5420 code, better CSE, and other secondary benefits of completely
5421 unrolling some loops. */
5422 unrolled_insn_copies -= 1;
5424 /* Clamp the value. */
5425 if (unrolled_insn_copies < 0)
5426 unrolled_insn_copies = 0;
5429 /* Unroll loops from within strength reduction so that we can use the
5430 induction variable information that strength_reduce has already
5431 collected. Always unroll loops that would be as small or smaller
5432 unrolled than when rolled. */
5433 if ((flags & LOOP_UNROLL)
5434 || ((flags & LOOP_AUTO_UNROLL)
5435 && loop_info->n_iterations > 0
5436 && unrolled_insn_copies <= insn_count))
5437 unroll_loop (loop, insn_count, 1);
5439 #ifdef HAVE_doloop_end
5440 if (HAVE_doloop_end && (flags & LOOP_BCT) && flag_branch_on_count_reg)
5441 doloop_optimize (loop);
5442 #endif /* HAVE_doloop_end */
5444 /* In case number of iterations is known, drop branch prediction note
5445 in the branch. Do that only in second loop pass, as loop unrolling
5446 may change the number of iterations performed. */
5447 if (flags & LOOP_BCT)
5449 unsigned HOST_WIDE_INT n
5450 = loop_info->n_iterations / loop_info->unroll_number;
5451 if (n > 1)
5452 predict_insn (prev_nonnote_insn (loop->end), PRED_LOOP_ITERATIONS,
5453 REG_BR_PROB_BASE - REG_BR_PROB_BASE / n);
5456 if (loop_dump_stream)
5457 fprintf (loop_dump_stream, "\n");
5459 loop_ivs_free (loop);
5460 if (reg_map)
5461 free (reg_map);
5464 /*Record all basic induction variables calculated in the insn. */
5465 static rtx
5466 check_insn_for_bivs (loop, p, not_every_iteration, maybe_multiple)
5467 struct loop *loop;
5468 rtx p;
5469 int not_every_iteration;
5470 int maybe_multiple;
5472 struct loop_ivs *ivs = LOOP_IVS (loop);
5473 rtx set;
5474 rtx dest_reg;
5475 rtx inc_val;
5476 rtx mult_val;
5477 rtx *location;
5479 if (GET_CODE (p) == INSN
5480 && (set = single_set (p))
5481 && GET_CODE (SET_DEST (set)) == REG)
5483 dest_reg = SET_DEST (set);
5484 if (REGNO (dest_reg) < max_reg_before_loop
5485 && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
5486 && REG_IV_TYPE (ivs, REGNO (dest_reg)) != NOT_BASIC_INDUCT)
5488 if (basic_induction_var (loop, SET_SRC (set),
5489 GET_MODE (SET_SRC (set)),
5490 dest_reg, p, &inc_val, &mult_val,
5491 &location))
5493 /* It is a possible basic induction variable.
5494 Create and initialize an induction structure for it. */
5496 struct induction *v
5497 = (struct induction *) xmalloc (sizeof (struct induction));
5499 record_biv (loop, v, p, dest_reg, inc_val, mult_val, location,
5500 not_every_iteration, maybe_multiple);
5501 REG_IV_TYPE (ivs, REGNO (dest_reg)) = BASIC_INDUCT;
5503 else if (REGNO (dest_reg) < ivs->n_regs)
5504 REG_IV_TYPE (ivs, REGNO (dest_reg)) = NOT_BASIC_INDUCT;
5507 return p;
5510 /* Record all givs calculated in the insn.
5511 A register is a giv if: it is only set once, it is a function of a
5512 biv and a constant (or invariant), and it is not a biv. */
5513 static rtx
5514 check_insn_for_givs (loop, p, not_every_iteration, maybe_multiple)
5515 struct loop *loop;
5516 rtx p;
5517 int not_every_iteration;
5518 int maybe_multiple;
5520 struct loop_regs *regs = LOOP_REGS (loop);
5522 rtx set;
5523 /* Look for a general induction variable in a register. */
5524 if (GET_CODE (p) == INSN
5525 && (set = single_set (p))
5526 && GET_CODE (SET_DEST (set)) == REG
5527 && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
5529 rtx src_reg;
5530 rtx dest_reg;
5531 rtx add_val;
5532 rtx mult_val;
5533 rtx ext_val;
5534 int benefit;
5535 rtx regnote = 0;
5536 rtx last_consec_insn;
5538 dest_reg = SET_DEST (set);
5539 if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
5540 return p;
5542 if (/* SET_SRC is a giv. */
5543 (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
5544 &mult_val, &ext_val, 0, &benefit, VOIDmode)
5545 /* Equivalent expression is a giv. */
5546 || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
5547 && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
5548 &add_val, &mult_val, &ext_val, 0,
5549 &benefit, VOIDmode)))
5550 /* Don't try to handle any regs made by loop optimization.
5551 We have nothing on them in regno_first_uid, etc. */
5552 && REGNO (dest_reg) < max_reg_before_loop
5553 /* Don't recognize a BASIC_INDUCT_VAR here. */
5554 && dest_reg != src_reg
5555 /* This must be the only place where the register is set. */
5556 && (regs->array[REGNO (dest_reg)].n_times_set == 1
5557 /* or all sets must be consecutive and make a giv. */
5558 || (benefit = consec_sets_giv (loop, benefit, p,
5559 src_reg, dest_reg,
5560 &add_val, &mult_val, &ext_val,
5561 &last_consec_insn))))
5563 struct induction *v
5564 = (struct induction *) xmalloc (sizeof (struct induction));
5566 /* If this is a library call, increase benefit. */
5567 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5568 benefit += libcall_benefit (p);
5570 /* Skip the consecutive insns, if there are any. */
5571 if (regs->array[REGNO (dest_reg)].n_times_set != 1)
5572 p = last_consec_insn;
5574 record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
5575 ext_val, benefit, DEST_REG, not_every_iteration,
5576 maybe_multiple, (rtx*) 0);
5581 #ifndef DONT_REDUCE_ADDR
5582 /* Look for givs which are memory addresses. */
5583 /* This resulted in worse code on a VAX 8600. I wonder if it
5584 still does. */
5585 if (GET_CODE (p) == INSN)
5586 find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
5587 maybe_multiple);
5588 #endif
5590 /* Update the status of whether giv can derive other givs. This can
5591 change when we pass a label or an insn that updates a biv. */
5592 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5593 || GET_CODE (p) == CODE_LABEL)
5594 update_giv_derive (loop, p);
5595 return p;
5598 /* Return 1 if X is a valid source for an initial value (or as value being
5599 compared against in an initial test).
5601 X must be either a register or constant and must not be clobbered between
5602 the current insn and the start of the loop.
5604 INSN is the insn containing X. */
5606 static int
5607 valid_initial_value_p (x, insn, call_seen, loop_start)
5608 rtx x;
5609 rtx insn;
5610 int call_seen;
5611 rtx loop_start;
5613 if (CONSTANT_P (x))
5614 return 1;
5616 /* Only consider pseudos we know about initialized in insns whose luids
5617 we know. */
5618 if (GET_CODE (x) != REG
5619 || REGNO (x) >= max_reg_before_loop)
5620 return 0;
5622 /* Don't use call-clobbered registers across a call which clobbers it. On
5623 some machines, don't use any hard registers at all. */
5624 if (REGNO (x) < FIRST_PSEUDO_REGISTER
5625 && (SMALL_REGISTER_CLASSES
5626 || (call_used_regs[REGNO (x)] && call_seen)))
5627 return 0;
5629 /* Don't use registers that have been clobbered before the start of the
5630 loop. */
5631 if (reg_set_between_p (x, insn, loop_start))
5632 return 0;
5634 return 1;
5637 /* Scan X for memory refs and check each memory address
5638 as a possible giv. INSN is the insn whose pattern X comes from.
5639 NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5640 every loop iteration. MAYBE_MULTIPLE is 1 if the insn might be executed
5641 more than once in each loop iteration. */
5643 static void
5644 find_mem_givs (loop, x, insn, not_every_iteration, maybe_multiple)
5645 const struct loop *loop;
5646 rtx x;
5647 rtx insn;
5648 int not_every_iteration, maybe_multiple;
5650 int i, j;
5651 enum rtx_code code;
5652 const char *fmt;
5654 if (x == 0)
5655 return;
5657 code = GET_CODE (x);
5658 switch (code)
5660 case REG:
5661 case CONST_INT:
5662 case CONST:
5663 case CONST_DOUBLE:
5664 case SYMBOL_REF:
5665 case LABEL_REF:
5666 case PC:
5667 case CC0:
5668 case ADDR_VEC:
5669 case ADDR_DIFF_VEC:
5670 case USE:
5671 case CLOBBER:
5672 return;
5674 case MEM:
5676 rtx src_reg;
5677 rtx add_val;
5678 rtx mult_val;
5679 rtx ext_val;
5680 int benefit;
5682 /* This code used to disable creating GIVs with mult_val == 1 and
5683 add_val == 0. However, this leads to lost optimizations when
5684 it comes time to combine a set of related DEST_ADDR GIVs, since
5685 this one would not be seen. */
5687 if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
5688 &mult_val, &ext_val, 1, &benefit,
5689 GET_MODE (x)))
5691 /* Found one; record it. */
5692 struct induction *v
5693 = (struct induction *) xmalloc (sizeof (struct induction));
5695 record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
5696 add_val, ext_val, benefit, DEST_ADDR,
5697 not_every_iteration, maybe_multiple, &XEXP (x, 0));
5699 v->mem = x;
5702 return;
5704 default:
5705 break;
5708 /* Recursively scan the subexpressions for other mem refs. */
5710 fmt = GET_RTX_FORMAT (code);
5711 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5712 if (fmt[i] == 'e')
5713 find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
5714 maybe_multiple);
5715 else if (fmt[i] == 'E')
5716 for (j = 0; j < XVECLEN (x, i); j++)
5717 find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
5718 maybe_multiple);
5721 /* Fill in the data about one biv update.
5722 V is the `struct induction' in which we record the biv. (It is
5723 allocated by the caller, with alloca.)
5724 INSN is the insn that sets it.
5725 DEST_REG is the biv's reg.
5727 MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5728 INC_VAL is the increment. Otherwise, MULT_VAL is const0_rtx and the biv is
5729 being set to INC_VAL.
5731 NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5732 executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5733 can be executed more than once per iteration. If MAYBE_MULTIPLE
5734 and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5735 executed exactly once per iteration. */
5737 static void
5738 record_biv (loop, v, insn, dest_reg, inc_val, mult_val, location,
5739 not_every_iteration, maybe_multiple)
5740 struct loop *loop;
5741 struct induction *v;
5742 rtx insn;
5743 rtx dest_reg;
5744 rtx inc_val;
5745 rtx mult_val;
5746 rtx *location;
5747 int not_every_iteration;
5748 int maybe_multiple;
5750 struct loop_ivs *ivs = LOOP_IVS (loop);
5751 struct iv_class *bl;
5753 v->insn = insn;
5754 v->src_reg = dest_reg;
5755 v->dest_reg = dest_reg;
5756 v->mult_val = mult_val;
5757 v->add_val = inc_val;
5758 v->ext_dependent = NULL_RTX;
5759 v->location = location;
5760 v->mode = GET_MODE (dest_reg);
5761 v->always_computable = ! not_every_iteration;
5762 v->always_executed = ! not_every_iteration;
5763 v->maybe_multiple = maybe_multiple;
5764 v->same = 0;
5766 /* Add this to the reg's iv_class, creating a class
5767 if this is the first incrementation of the reg. */
5769 bl = REG_IV_CLASS (ivs, REGNO (dest_reg));
5770 if (bl == 0)
5772 /* Create and initialize new iv_class. */
5774 bl = (struct iv_class *) xmalloc (sizeof (struct iv_class));
5776 bl->regno = REGNO (dest_reg);
5777 bl->biv = 0;
5778 bl->giv = 0;
5779 bl->biv_count = 0;
5780 bl->giv_count = 0;
5782 /* Set initial value to the reg itself. */
5783 bl->initial_value = dest_reg;
5784 bl->final_value = 0;
5785 /* We haven't seen the initializing insn yet */
5786 bl->init_insn = 0;
5787 bl->init_set = 0;
5788 bl->initial_test = 0;
5789 bl->incremented = 0;
5790 bl->eliminable = 0;
5791 bl->nonneg = 0;
5792 bl->reversed = 0;
5793 bl->total_benefit = 0;
5795 /* Add this class to ivs->list. */
5796 bl->next = ivs->list;
5797 ivs->list = bl;
5799 /* Put it in the array of biv register classes. */
5800 REG_IV_CLASS (ivs, REGNO (dest_reg)) = bl;
5802 else
5804 /* Check if location is the same as a previous one. */
5805 struct induction *induction;
5806 for (induction = bl->biv; induction; induction = induction->next_iv)
5807 if (location == induction->location)
5809 v->same = induction;
5810 break;
5814 /* Update IV_CLASS entry for this biv. */
5815 v->next_iv = bl->biv;
5816 bl->biv = v;
5817 bl->biv_count++;
5818 if (mult_val == const1_rtx)
5819 bl->incremented = 1;
5821 if (loop_dump_stream)
5822 loop_biv_dump (v, loop_dump_stream, 0);
5825 /* Fill in the data about one giv.
5826 V is the `struct induction' in which we record the giv. (It is
5827 allocated by the caller, with alloca.)
5828 INSN is the insn that sets it.
5829 BENEFIT estimates the savings from deleting this insn.
5830 TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5831 into a register or is used as a memory address.
5833 SRC_REG is the biv reg which the giv is computed from.
5834 DEST_REG is the giv's reg (if the giv is stored in a reg).
5835 MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5836 LOCATION points to the place where this giv's value appears in INSN. */
5838 static void
5839 record_giv (loop, v, insn, src_reg, dest_reg, mult_val, add_val, ext_val,
5840 benefit, type, not_every_iteration, maybe_multiple, location)
5841 const struct loop *loop;
5842 struct induction *v;
5843 rtx insn;
5844 rtx src_reg;
5845 rtx dest_reg;
5846 rtx mult_val, add_val, ext_val;
5847 int benefit;
5848 enum g_types type;
5849 int not_every_iteration, maybe_multiple;
5850 rtx *location;
5852 struct loop_ivs *ivs = LOOP_IVS (loop);
5853 struct induction *b;
5854 struct iv_class *bl;
5855 rtx set = single_set (insn);
5856 rtx temp;
5858 /* Attempt to prove constantness of the values. Don't let simplify_rtx
5859 undo the MULT canonicalization that we performed earlier. */
5860 temp = simplify_rtx (add_val);
5861 if (temp
5862 && ! (GET_CODE (add_val) == MULT
5863 && GET_CODE (temp) == ASHIFT))
5864 add_val = temp;
5866 v->insn = insn;
5867 v->src_reg = src_reg;
5868 v->giv_type = type;
5869 v->dest_reg = dest_reg;
5870 v->mult_val = mult_val;
5871 v->add_val = add_val;
5872 v->ext_dependent = ext_val;
5873 v->benefit = benefit;
5874 v->location = location;
5875 v->cant_derive = 0;
5876 v->combined_with = 0;
5877 v->maybe_multiple = maybe_multiple;
5878 v->maybe_dead = 0;
5879 v->derive_adjustment = 0;
5880 v->same = 0;
5881 v->ignore = 0;
5882 v->new_reg = 0;
5883 v->final_value = 0;
5884 v->same_insn = 0;
5885 v->auto_inc_opt = 0;
5886 v->unrolled = 0;
5887 v->shared = 0;
5889 /* The v->always_computable field is used in update_giv_derive, to
5890 determine whether a giv can be used to derive another giv. For a
5891 DEST_REG giv, INSN computes a new value for the giv, so its value
5892 isn't computable if INSN insn't executed every iteration.
5893 However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5894 it does not compute a new value. Hence the value is always computable
5895 regardless of whether INSN is executed each iteration. */
5897 if (type == DEST_ADDR)
5898 v->always_computable = 1;
5899 else
5900 v->always_computable = ! not_every_iteration;
5902 v->always_executed = ! not_every_iteration;
5904 if (type == DEST_ADDR)
5906 v->mode = GET_MODE (*location);
5907 v->lifetime = 1;
5909 else /* type == DEST_REG */
5911 v->mode = GET_MODE (SET_DEST (set));
5913 v->lifetime = LOOP_REG_LIFETIME (loop, REGNO (dest_reg));
5915 /* If the lifetime is zero, it means that this register is
5916 really a dead store. So mark this as a giv that can be
5917 ignored. This will not prevent the biv from being eliminated. */
5918 if (v->lifetime == 0)
5919 v->ignore = 1;
5921 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
5922 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
5925 /* Add the giv to the class of givs computed from one biv. */
5927 bl = REG_IV_CLASS (ivs, REGNO (src_reg));
5928 if (bl)
5930 v->next_iv = bl->giv;
5931 bl->giv = v;
5932 /* Don't count DEST_ADDR. This is supposed to count the number of
5933 insns that calculate givs. */
5934 if (type == DEST_REG)
5935 bl->giv_count++;
5936 bl->total_benefit += benefit;
5938 else
5939 /* Fatal error, biv missing for this giv? */
5940 abort ();
5942 if (type == DEST_ADDR)
5944 v->replaceable = 1;
5945 v->not_replaceable = 0;
5947 else
5949 /* The giv can be replaced outright by the reduced register only if all
5950 of the following conditions are true:
5951 - the insn that sets the giv is always executed on any iteration
5952 on which the giv is used at all
5953 (there are two ways to deduce this:
5954 either the insn is executed on every iteration,
5955 or all uses follow that insn in the same basic block),
5956 - the giv is not used outside the loop
5957 - no assignments to the biv occur during the giv's lifetime. */
5959 if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5960 /* Previous line always fails if INSN was moved by loop opt. */
5961 && REGNO_LAST_LUID (REGNO (dest_reg))
5962 < INSN_LUID (loop->end)
5963 && (! not_every_iteration
5964 || last_use_this_basic_block (dest_reg, insn)))
5966 /* Now check that there are no assignments to the biv within the
5967 giv's lifetime. This requires two separate checks. */
5969 /* Check each biv update, and fail if any are between the first
5970 and last use of the giv.
5972 If this loop contains an inner loop that was unrolled, then
5973 the insn modifying the biv may have been emitted by the loop
5974 unrolling code, and hence does not have a valid luid. Just
5975 mark the biv as not replaceable in this case. It is not very
5976 useful as a biv, because it is used in two different loops.
5977 It is very unlikely that we would be able to optimize the giv
5978 using this biv anyways. */
5980 v->replaceable = 1;
5981 v->not_replaceable = 0;
5982 for (b = bl->biv; b; b = b->next_iv)
5984 if (INSN_UID (b->insn) >= max_uid_for_loop
5985 || ((INSN_LUID (b->insn)
5986 >= REGNO_FIRST_LUID (REGNO (dest_reg)))
5987 && (INSN_LUID (b->insn)
5988 <= REGNO_LAST_LUID (REGNO (dest_reg)))))
5990 v->replaceable = 0;
5991 v->not_replaceable = 1;
5992 break;
5996 /* If there are any backwards branches that go from after the
5997 biv update to before it, then this giv is not replaceable. */
5998 if (v->replaceable)
5999 for (b = bl->biv; b; b = b->next_iv)
6000 if (back_branch_in_range_p (loop, b->insn))
6002 v->replaceable = 0;
6003 v->not_replaceable = 1;
6004 break;
6007 else
6009 /* May still be replaceable, we don't have enough info here to
6010 decide. */
6011 v->replaceable = 0;
6012 v->not_replaceable = 0;
6016 /* Record whether the add_val contains a const_int, for later use by
6017 combine_givs. */
6019 rtx tem = add_val;
6021 v->no_const_addval = 1;
6022 if (tem == const0_rtx)
6024 else if (CONSTANT_P (add_val))
6025 v->no_const_addval = 0;
6026 if (GET_CODE (tem) == PLUS)
6028 while (1)
6030 if (GET_CODE (XEXP (tem, 0)) == PLUS)
6031 tem = XEXP (tem, 0);
6032 else if (GET_CODE (XEXP (tem, 1)) == PLUS)
6033 tem = XEXP (tem, 1);
6034 else
6035 break;
6037 if (CONSTANT_P (XEXP (tem, 1)))
6038 v->no_const_addval = 0;
6042 if (loop_dump_stream)
6043 loop_giv_dump (v, loop_dump_stream, 0);
6046 /* All this does is determine whether a giv can be made replaceable because
6047 its final value can be calculated. This code can not be part of record_giv
6048 above, because final_giv_value requires that the number of loop iterations
6049 be known, and that can not be accurately calculated until after all givs
6050 have been identified. */
6052 static void
6053 check_final_value (loop, v)
6054 const struct loop *loop;
6055 struct induction *v;
6057 rtx final_value = 0;
6059 /* DEST_ADDR givs will never reach here, because they are always marked
6060 replaceable above in record_giv. */
6062 /* The giv can be replaced outright by the reduced register only if all
6063 of the following conditions are true:
6064 - the insn that sets the giv is always executed on any iteration
6065 on which the giv is used at all
6066 (there are two ways to deduce this:
6067 either the insn is executed on every iteration,
6068 or all uses follow that insn in the same basic block),
6069 - its final value can be calculated (this condition is different
6070 than the one above in record_giv)
6071 - it's not used before the it's set
6072 - no assignments to the biv occur during the giv's lifetime. */
6074 #if 0
6075 /* This is only called now when replaceable is known to be false. */
6076 /* Clear replaceable, so that it won't confuse final_giv_value. */
6077 v->replaceable = 0;
6078 #endif
6080 if ((final_value = final_giv_value (loop, v))
6081 && (v->always_executed
6082 || last_use_this_basic_block (v->dest_reg, v->insn)))
6084 int biv_increment_seen = 0, before_giv_insn = 0;
6085 rtx p = v->insn;
6086 rtx last_giv_use;
6088 v->replaceable = 1;
6089 v->not_replaceable = 0;
6091 /* When trying to determine whether or not a biv increment occurs
6092 during the lifetime of the giv, we can ignore uses of the variable
6093 outside the loop because final_value is true. Hence we can not
6094 use regno_last_uid and regno_first_uid as above in record_giv. */
6096 /* Search the loop to determine whether any assignments to the
6097 biv occur during the giv's lifetime. Start with the insn
6098 that sets the giv, and search around the loop until we come
6099 back to that insn again.
6101 Also fail if there is a jump within the giv's lifetime that jumps
6102 to somewhere outside the lifetime but still within the loop. This
6103 catches spaghetti code where the execution order is not linear, and
6104 hence the above test fails. Here we assume that the giv lifetime
6105 does not extend from one iteration of the loop to the next, so as
6106 to make the test easier. Since the lifetime isn't known yet,
6107 this requires two loops. See also record_giv above. */
6109 last_giv_use = v->insn;
6111 while (1)
6113 p = NEXT_INSN (p);
6114 if (p == loop->end)
6116 before_giv_insn = 1;
6117 p = NEXT_INSN (loop->start);
6119 if (p == v->insn)
6120 break;
6122 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
6123 || GET_CODE (p) == CALL_INSN)
6125 /* It is possible for the BIV increment to use the GIV if we
6126 have a cycle. Thus we must be sure to check each insn for
6127 both BIV and GIV uses, and we must check for BIV uses
6128 first. */
6130 if (! biv_increment_seen
6131 && reg_set_p (v->src_reg, PATTERN (p)))
6132 biv_increment_seen = 1;
6134 if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
6136 if (biv_increment_seen || before_giv_insn)
6138 v->replaceable = 0;
6139 v->not_replaceable = 1;
6140 break;
6142 last_giv_use = p;
6147 /* Now that the lifetime of the giv is known, check for branches
6148 from within the lifetime to outside the lifetime if it is still
6149 replaceable. */
6151 if (v->replaceable)
6153 p = v->insn;
6154 while (1)
6156 p = NEXT_INSN (p);
6157 if (p == loop->end)
6158 p = NEXT_INSN (loop->start);
6159 if (p == last_giv_use)
6160 break;
6162 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
6163 && LABEL_NAME (JUMP_LABEL (p))
6164 && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
6165 && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
6166 || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
6167 && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
6169 v->replaceable = 0;
6170 v->not_replaceable = 1;
6172 if (loop_dump_stream)
6173 fprintf (loop_dump_stream,
6174 "Found branch outside giv lifetime.\n");
6176 break;
6181 /* If it is replaceable, then save the final value. */
6182 if (v->replaceable)
6183 v->final_value = final_value;
6186 if (loop_dump_stream && v->replaceable)
6187 fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
6188 INSN_UID (v->insn), REGNO (v->dest_reg));
6191 /* Update the status of whether a giv can derive other givs.
6193 We need to do something special if there is or may be an update to the biv
6194 between the time the giv is defined and the time it is used to derive
6195 another giv.
6197 In addition, a giv that is only conditionally set is not allowed to
6198 derive another giv once a label has been passed.
6200 The cases we look at are when a label or an update to a biv is passed. */
6202 static void
6203 update_giv_derive (loop, p)
6204 const struct loop *loop;
6205 rtx p;
6207 struct loop_ivs *ivs = LOOP_IVS (loop);
6208 struct iv_class *bl;
6209 struct induction *biv, *giv;
6210 rtx tem;
6211 int dummy;
6213 /* Search all IV classes, then all bivs, and finally all givs.
6215 There are three cases we are concerned with. First we have the situation
6216 of a giv that is only updated conditionally. In that case, it may not
6217 derive any givs after a label is passed.
6219 The second case is when a biv update occurs, or may occur, after the
6220 definition of a giv. For certain biv updates (see below) that are
6221 known to occur between the giv definition and use, we can adjust the
6222 giv definition. For others, or when the biv update is conditional,
6223 we must prevent the giv from deriving any other givs. There are two
6224 sub-cases within this case.
6226 If this is a label, we are concerned with any biv update that is done
6227 conditionally, since it may be done after the giv is defined followed by
6228 a branch here (actually, we need to pass both a jump and a label, but
6229 this extra tracking doesn't seem worth it).
6231 If this is a jump, we are concerned about any biv update that may be
6232 executed multiple times. We are actually only concerned about
6233 backward jumps, but it is probably not worth performing the test
6234 on the jump again here.
6236 If this is a biv update, we must adjust the giv status to show that a
6237 subsequent biv update was performed. If this adjustment cannot be done,
6238 the giv cannot derive further givs. */
6240 for (bl = ivs->list; bl; bl = bl->next)
6241 for (biv = bl->biv; biv; biv = biv->next_iv)
6242 if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
6243 || biv->insn == p)
6245 for (giv = bl->giv; giv; giv = giv->next_iv)
6247 /* If cant_derive is already true, there is no point in
6248 checking all of these conditions again. */
6249 if (giv->cant_derive)
6250 continue;
6252 /* If this giv is conditionally set and we have passed a label,
6253 it cannot derive anything. */
6254 if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
6255 giv->cant_derive = 1;
6257 /* Skip givs that have mult_val == 0, since
6258 they are really invariants. Also skip those that are
6259 replaceable, since we know their lifetime doesn't contain
6260 any biv update. */
6261 else if (giv->mult_val == const0_rtx || giv->replaceable)
6262 continue;
6264 /* The only way we can allow this giv to derive another
6265 is if this is a biv increment and we can form the product
6266 of biv->add_val and giv->mult_val. In this case, we will
6267 be able to compute a compensation. */
6268 else if (biv->insn == p)
6270 rtx ext_val_dummy;
6272 tem = 0;
6273 if (biv->mult_val == const1_rtx)
6274 tem = simplify_giv_expr (loop,
6275 gen_rtx_MULT (giv->mode,
6276 biv->add_val,
6277 giv->mult_val),
6278 &ext_val_dummy, &dummy);
6280 if (tem && giv->derive_adjustment)
6281 tem = simplify_giv_expr
6282 (loop,
6283 gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
6284 &ext_val_dummy, &dummy);
6286 if (tem)
6287 giv->derive_adjustment = tem;
6288 else
6289 giv->cant_derive = 1;
6291 else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
6292 || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
6293 giv->cant_derive = 1;
6298 /* Check whether an insn is an increment legitimate for a basic induction var.
6299 X is the source of insn P, or a part of it.
6300 MODE is the mode in which X should be interpreted.
6302 DEST_REG is the putative biv, also the destination of the insn.
6303 We accept patterns of these forms:
6304 REG = REG + INVARIANT (includes REG = REG - CONSTANT)
6305 REG = INVARIANT + REG
6307 If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
6308 store the additive term into *INC_VAL, and store the place where
6309 we found the additive term into *LOCATION.
6311 If X is an assignment of an invariant into DEST_REG, we set
6312 *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
6314 We also want to detect a BIV when it corresponds to a variable
6315 whose mode was promoted via PROMOTED_MODE. In that case, an increment
6316 of the variable may be a PLUS that adds a SUBREG of that variable to
6317 an invariant and then sign- or zero-extends the result of the PLUS
6318 into the variable.
6320 Most GIVs in such cases will be in the promoted mode, since that is the
6321 probably the natural computation mode (and almost certainly the mode
6322 used for addresses) on the machine. So we view the pseudo-reg containing
6323 the variable as the BIV, as if it were simply incremented.
6325 Note that treating the entire pseudo as a BIV will result in making
6326 simple increments to any GIVs based on it. However, if the variable
6327 overflows in its declared mode but not its promoted mode, the result will
6328 be incorrect. This is acceptable if the variable is signed, since
6329 overflows in such cases are undefined, but not if it is unsigned, since
6330 those overflows are defined. So we only check for SIGN_EXTEND and
6331 not ZERO_EXTEND.
6333 If we cannot find a biv, we return 0. */
6335 static int
6336 basic_induction_var (loop, x, mode, dest_reg, p, inc_val, mult_val, location)
6337 const struct loop *loop;
6338 rtx x;
6339 enum machine_mode mode;
6340 rtx dest_reg;
6341 rtx p;
6342 rtx *inc_val;
6343 rtx *mult_val;
6344 rtx **location;
6346 enum rtx_code code;
6347 rtx *argp, arg;
6348 rtx insn, set = 0;
6350 code = GET_CODE (x);
6351 *location = NULL;
6352 switch (code)
6354 case PLUS:
6355 if (rtx_equal_p (XEXP (x, 0), dest_reg)
6356 || (GET_CODE (XEXP (x, 0)) == SUBREG
6357 && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
6358 && SUBREG_REG (XEXP (x, 0)) == dest_reg))
6360 argp = &XEXP (x, 1);
6362 else if (rtx_equal_p (XEXP (x, 1), dest_reg)
6363 || (GET_CODE (XEXP (x, 1)) == SUBREG
6364 && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
6365 && SUBREG_REG (XEXP (x, 1)) == dest_reg))
6367 argp = &XEXP (x, 0);
6369 else
6370 return 0;
6372 arg = *argp;
6373 if (loop_invariant_p (loop, arg) != 1)
6374 return 0;
6376 *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
6377 *mult_val = const1_rtx;
6378 *location = argp;
6379 return 1;
6381 case SUBREG:
6382 /* If what's inside the SUBREG is a BIV, then the SUBREG. This will
6383 handle addition of promoted variables.
6384 ??? The comment at the start of this function is wrong: promoted
6385 variable increments don't look like it says they do. */
6386 return basic_induction_var (loop, SUBREG_REG (x),
6387 GET_MODE (SUBREG_REG (x)),
6388 dest_reg, p, inc_val, mult_val, location);
6390 case REG:
6391 /* If this register is assigned in a previous insn, look at its
6392 source, but don't go outside the loop or past a label. */
6394 /* If this sets a register to itself, we would repeat any previous
6395 biv increment if we applied this strategy blindly. */
6396 if (rtx_equal_p (dest_reg, x))
6397 return 0;
6399 insn = p;
6400 while (1)
6402 rtx dest;
6405 insn = PREV_INSN (insn);
6407 while (insn && GET_CODE (insn) == NOTE
6408 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6410 if (!insn)
6411 break;
6412 set = single_set (insn);
6413 if (set == 0)
6414 break;
6415 dest = SET_DEST (set);
6416 if (dest == x
6417 || (GET_CODE (dest) == SUBREG
6418 && (GET_MODE_SIZE (GET_MODE (dest)) <= UNITS_PER_WORD)
6419 && (GET_MODE_CLASS (GET_MODE (dest)) == MODE_INT)
6420 && SUBREG_REG (dest) == x))
6421 return basic_induction_var (loop, SET_SRC (set),
6422 (GET_MODE (SET_SRC (set)) == VOIDmode
6423 ? GET_MODE (x)
6424 : GET_MODE (SET_SRC (set))),
6425 dest_reg, insn,
6426 inc_val, mult_val, location);
6428 while (GET_CODE (dest) == SIGN_EXTRACT
6429 || GET_CODE (dest) == ZERO_EXTRACT
6430 || GET_CODE (dest) == SUBREG
6431 || GET_CODE (dest) == STRICT_LOW_PART)
6432 dest = XEXP (dest, 0);
6433 if (dest == x)
6434 break;
6436 /* Fall through. */
6438 /* Can accept constant setting of biv only when inside inner most loop.
6439 Otherwise, a biv of an inner loop may be incorrectly recognized
6440 as a biv of the outer loop,
6441 causing code to be moved INTO the inner loop. */
6442 case MEM:
6443 if (loop_invariant_p (loop, x) != 1)
6444 return 0;
6445 case CONST_INT:
6446 case SYMBOL_REF:
6447 case CONST:
6448 /* convert_modes aborts if we try to convert to or from CCmode, so just
6449 exclude that case. It is very unlikely that a condition code value
6450 would be a useful iterator anyways. convert_modes aborts if we try to
6451 convert a float mode to non-float or vice versa too. */
6452 if (loop->level == 1
6453 && GET_MODE_CLASS (mode) == GET_MODE_CLASS (GET_MODE (dest_reg))
6454 && GET_MODE_CLASS (mode) != MODE_CC)
6456 /* Possible bug here? Perhaps we don't know the mode of X. */
6457 *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6458 *mult_val = const0_rtx;
6459 return 1;
6461 else
6462 return 0;
6464 case SIGN_EXTEND:
6465 /* Ignore this BIV if signed arithmetic overflow is defined. */
6466 if (flag_wrapv)
6467 return 0;
6468 return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6469 dest_reg, p, inc_val, mult_val, location);
6471 case ASHIFTRT:
6472 /* Similar, since this can be a sign extension. */
6473 for (insn = PREV_INSN (p);
6474 (insn && GET_CODE (insn) == NOTE
6475 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6476 insn = PREV_INSN (insn))
6479 if (insn)
6480 set = single_set (insn);
6482 if (! rtx_equal_p (dest_reg, XEXP (x, 0))
6483 && set && SET_DEST (set) == XEXP (x, 0)
6484 && GET_CODE (XEXP (x, 1)) == CONST_INT
6485 && INTVAL (XEXP (x, 1)) >= 0
6486 && GET_CODE (SET_SRC (set)) == ASHIFT
6487 && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
6488 return basic_induction_var (loop, XEXP (SET_SRC (set), 0),
6489 GET_MODE (XEXP (x, 0)),
6490 dest_reg, insn, inc_val, mult_val,
6491 location);
6492 return 0;
6494 default:
6495 return 0;
6499 /* A general induction variable (giv) is any quantity that is a linear
6500 function of a basic induction variable,
6501 i.e. giv = biv * mult_val + add_val.
6502 The coefficients can be any loop invariant quantity.
6503 A giv need not be computed directly from the biv;
6504 it can be computed by way of other givs. */
6506 /* Determine whether X computes a giv.
6507 If it does, return a nonzero value
6508 which is the benefit from eliminating the computation of X;
6509 set *SRC_REG to the register of the biv that it is computed from;
6510 set *ADD_VAL and *MULT_VAL to the coefficients,
6511 such that the value of X is biv * mult + add; */
6513 static int
6514 general_induction_var (loop, x, src_reg, add_val, mult_val, ext_val,
6515 is_addr, pbenefit, addr_mode)
6516 const struct loop *loop;
6517 rtx x;
6518 rtx *src_reg;
6519 rtx *add_val;
6520 rtx *mult_val;
6521 rtx *ext_val;
6522 int is_addr;
6523 int *pbenefit;
6524 enum machine_mode addr_mode;
6526 struct loop_ivs *ivs = LOOP_IVS (loop);
6527 rtx orig_x = x;
6529 /* If this is an invariant, forget it, it isn't a giv. */
6530 if (loop_invariant_p (loop, x) == 1)
6531 return 0;
6533 *pbenefit = 0;
6534 *ext_val = NULL_RTX;
6535 x = simplify_giv_expr (loop, x, ext_val, pbenefit);
6536 if (x == 0)
6537 return 0;
6539 switch (GET_CODE (x))
6541 case USE:
6542 case CONST_INT:
6543 /* Since this is now an invariant and wasn't before, it must be a giv
6544 with MULT_VAL == 0. It doesn't matter which BIV we associate this
6545 with. */
6546 *src_reg = ivs->list->biv->dest_reg;
6547 *mult_val = const0_rtx;
6548 *add_val = x;
6549 break;
6551 case REG:
6552 /* This is equivalent to a BIV. */
6553 *src_reg = x;
6554 *mult_val = const1_rtx;
6555 *add_val = const0_rtx;
6556 break;
6558 case PLUS:
6559 /* Either (plus (biv) (invar)) or
6560 (plus (mult (biv) (invar_1)) (invar_2)). */
6561 if (GET_CODE (XEXP (x, 0)) == MULT)
6563 *src_reg = XEXP (XEXP (x, 0), 0);
6564 *mult_val = XEXP (XEXP (x, 0), 1);
6566 else
6568 *src_reg = XEXP (x, 0);
6569 *mult_val = const1_rtx;
6571 *add_val = XEXP (x, 1);
6572 break;
6574 case MULT:
6575 /* ADD_VAL is zero. */
6576 *src_reg = XEXP (x, 0);
6577 *mult_val = XEXP (x, 1);
6578 *add_val = const0_rtx;
6579 break;
6581 default:
6582 abort ();
6585 /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6586 unless they are CONST_INT). */
6587 if (GET_CODE (*add_val) == USE)
6588 *add_val = XEXP (*add_val, 0);
6589 if (GET_CODE (*mult_val) == USE)
6590 *mult_val = XEXP (*mult_val, 0);
6592 if (is_addr)
6593 *pbenefit += address_cost (orig_x, addr_mode) - reg_address_cost;
6594 else
6595 *pbenefit += rtx_cost (orig_x, SET);
6597 /* Always return true if this is a giv so it will be detected as such,
6598 even if the benefit is zero or negative. This allows elimination
6599 of bivs that might otherwise not be eliminated. */
6600 return 1;
6603 /* Given an expression, X, try to form it as a linear function of a biv.
6604 We will canonicalize it to be of the form
6605 (plus (mult (BIV) (invar_1))
6606 (invar_2))
6607 with possible degeneracies.
6609 The invariant expressions must each be of a form that can be used as a
6610 machine operand. We surround then with a USE rtx (a hack, but localized
6611 and certainly unambiguous!) if not a CONST_INT for simplicity in this
6612 routine; it is the caller's responsibility to strip them.
6614 If no such canonicalization is possible (i.e., two biv's are used or an
6615 expression that is neither invariant nor a biv or giv), this routine
6616 returns 0.
6618 For a nonzero return, the result will have a code of CONST_INT, USE,
6619 REG (for a BIV), PLUS, or MULT. No other codes will occur.
6621 *BENEFIT will be incremented by the benefit of any sub-giv encountered. */
6623 static rtx sge_plus PARAMS ((enum machine_mode, rtx, rtx));
6624 static rtx sge_plus_constant PARAMS ((rtx, rtx));
6626 static rtx
6627 simplify_giv_expr (loop, x, ext_val, benefit)
6628 const struct loop *loop;
6629 rtx x;
6630 rtx *ext_val;
6631 int *benefit;
6633 struct loop_ivs *ivs = LOOP_IVS (loop);
6634 struct loop_regs *regs = LOOP_REGS (loop);
6635 enum machine_mode mode = GET_MODE (x);
6636 rtx arg0, arg1;
6637 rtx tem;
6639 /* If this is not an integer mode, or if we cannot do arithmetic in this
6640 mode, this can't be a giv. */
6641 if (mode != VOIDmode
6642 && (GET_MODE_CLASS (mode) != MODE_INT
6643 || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6644 return NULL_RTX;
6646 switch (GET_CODE (x))
6648 case PLUS:
6649 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6650 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6651 if (arg0 == 0 || arg1 == 0)
6652 return NULL_RTX;
6654 /* Put constant last, CONST_INT last if both constant. */
6655 if ((GET_CODE (arg0) == USE
6656 || GET_CODE (arg0) == CONST_INT)
6657 && ! ((GET_CODE (arg0) == USE
6658 && GET_CODE (arg1) == USE)
6659 || GET_CODE (arg1) == CONST_INT))
6660 tem = arg0, arg0 = arg1, arg1 = tem;
6662 /* Handle addition of zero, then addition of an invariant. */
6663 if (arg1 == const0_rtx)
6664 return arg0;
6665 else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6666 switch (GET_CODE (arg0))
6668 case CONST_INT:
6669 case USE:
6670 /* Adding two invariants must result in an invariant, so enclose
6671 addition operation inside a USE and return it. */
6672 if (GET_CODE (arg0) == USE)
6673 arg0 = XEXP (arg0, 0);
6674 if (GET_CODE (arg1) == USE)
6675 arg1 = XEXP (arg1, 0);
6677 if (GET_CODE (arg0) == CONST_INT)
6678 tem = arg0, arg0 = arg1, arg1 = tem;
6679 if (GET_CODE (arg1) == CONST_INT)
6680 tem = sge_plus_constant (arg0, arg1);
6681 else
6682 tem = sge_plus (mode, arg0, arg1);
6684 if (GET_CODE (tem) != CONST_INT)
6685 tem = gen_rtx_USE (mode, tem);
6686 return tem;
6688 case REG:
6689 case MULT:
6690 /* biv + invar or mult + invar. Return sum. */
6691 return gen_rtx_PLUS (mode, arg0, arg1);
6693 case PLUS:
6694 /* (a + invar_1) + invar_2. Associate. */
6695 return
6696 simplify_giv_expr (loop,
6697 gen_rtx_PLUS (mode,
6698 XEXP (arg0, 0),
6699 gen_rtx_PLUS (mode,
6700 XEXP (arg0, 1),
6701 arg1)),
6702 ext_val, benefit);
6704 default:
6705 abort ();
6708 /* Each argument must be either REG, PLUS, or MULT. Convert REG to
6709 MULT to reduce cases. */
6710 if (GET_CODE (arg0) == REG)
6711 arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6712 if (GET_CODE (arg1) == REG)
6713 arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6715 /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6716 Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6717 Recurse to associate the second PLUS. */
6718 if (GET_CODE (arg1) == MULT)
6719 tem = arg0, arg0 = arg1, arg1 = tem;
6721 if (GET_CODE (arg1) == PLUS)
6722 return
6723 simplify_giv_expr (loop,
6724 gen_rtx_PLUS (mode,
6725 gen_rtx_PLUS (mode, arg0,
6726 XEXP (arg1, 0)),
6727 XEXP (arg1, 1)),
6728 ext_val, benefit);
6730 /* Now must have MULT + MULT. Distribute if same biv, else not giv. */
6731 if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6732 return NULL_RTX;
6734 if (!rtx_equal_p (arg0, arg1))
6735 return NULL_RTX;
6737 return simplify_giv_expr (loop,
6738 gen_rtx_MULT (mode,
6739 XEXP (arg0, 0),
6740 gen_rtx_PLUS (mode,
6741 XEXP (arg0, 1),
6742 XEXP (arg1, 1))),
6743 ext_val, benefit);
6745 case MINUS:
6746 /* Handle "a - b" as "a + b * (-1)". */
6747 return simplify_giv_expr (loop,
6748 gen_rtx_PLUS (mode,
6749 XEXP (x, 0),
6750 gen_rtx_MULT (mode,
6751 XEXP (x, 1),
6752 constm1_rtx)),
6753 ext_val, benefit);
6755 case MULT:
6756 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6757 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6758 if (arg0 == 0 || arg1 == 0)
6759 return NULL_RTX;
6761 /* Put constant last, CONST_INT last if both constant. */
6762 if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6763 && GET_CODE (arg1) != CONST_INT)
6764 tem = arg0, arg0 = arg1, arg1 = tem;
6766 /* If second argument is not now constant, not giv. */
6767 if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6768 return NULL_RTX;
6770 /* Handle multiply by 0 or 1. */
6771 if (arg1 == const0_rtx)
6772 return const0_rtx;
6774 else if (arg1 == const1_rtx)
6775 return arg0;
6777 switch (GET_CODE (arg0))
6779 case REG:
6780 /* biv * invar. Done. */
6781 return gen_rtx_MULT (mode, arg0, arg1);
6783 case CONST_INT:
6784 /* Product of two constants. */
6785 return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6787 case USE:
6788 /* invar * invar is a giv, but attempt to simplify it somehow. */
6789 if (GET_CODE (arg1) != CONST_INT)
6790 return NULL_RTX;
6792 arg0 = XEXP (arg0, 0);
6793 if (GET_CODE (arg0) == MULT)
6795 /* (invar_0 * invar_1) * invar_2. Associate. */
6796 return simplify_giv_expr (loop,
6797 gen_rtx_MULT (mode,
6798 XEXP (arg0, 0),
6799 gen_rtx_MULT (mode,
6800 XEXP (arg0,
6802 arg1)),
6803 ext_val, benefit);
6805 /* Propagate the MULT expressions to the intermost nodes. */
6806 else if (GET_CODE (arg0) == PLUS)
6808 /* (invar_0 + invar_1) * invar_2. Distribute. */
6809 return simplify_giv_expr (loop,
6810 gen_rtx_PLUS (mode,
6811 gen_rtx_MULT (mode,
6812 XEXP (arg0,
6814 arg1),
6815 gen_rtx_MULT (mode,
6816 XEXP (arg0,
6818 arg1)),
6819 ext_val, benefit);
6821 return gen_rtx_USE (mode, gen_rtx_MULT (mode, arg0, arg1));
6823 case MULT:
6824 /* (a * invar_1) * invar_2. Associate. */
6825 return simplify_giv_expr (loop,
6826 gen_rtx_MULT (mode,
6827 XEXP (arg0, 0),
6828 gen_rtx_MULT (mode,
6829 XEXP (arg0, 1),
6830 arg1)),
6831 ext_val, benefit);
6833 case PLUS:
6834 /* (a + invar_1) * invar_2. Distribute. */
6835 return simplify_giv_expr (loop,
6836 gen_rtx_PLUS (mode,
6837 gen_rtx_MULT (mode,
6838 XEXP (arg0, 0),
6839 arg1),
6840 gen_rtx_MULT (mode,
6841 XEXP (arg0, 1),
6842 arg1)),
6843 ext_val, benefit);
6845 default:
6846 abort ();
6849 case ASHIFT:
6850 /* Shift by constant is multiply by power of two. */
6851 if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6852 return 0;
6854 return
6855 simplify_giv_expr (loop,
6856 gen_rtx_MULT (mode,
6857 XEXP (x, 0),
6858 GEN_INT ((HOST_WIDE_INT) 1
6859 << INTVAL (XEXP (x, 1)))),
6860 ext_val, benefit);
6862 case NEG:
6863 /* "-a" is "a * (-1)" */
6864 return simplify_giv_expr (loop,
6865 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6866 ext_val, benefit);
6868 case NOT:
6869 /* "~a" is "-a - 1". Silly, but easy. */
6870 return simplify_giv_expr (loop,
6871 gen_rtx_MINUS (mode,
6872 gen_rtx_NEG (mode, XEXP (x, 0)),
6873 const1_rtx),
6874 ext_val, benefit);
6876 case USE:
6877 /* Already in proper form for invariant. */
6878 return x;
6880 case SIGN_EXTEND:
6881 case ZERO_EXTEND:
6882 case TRUNCATE:
6883 /* Conditionally recognize extensions of simple IVs. After we've
6884 computed loop traversal counts and verified the range of the
6885 source IV, we'll reevaluate this as a GIV. */
6886 if (*ext_val == NULL_RTX)
6888 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6889 if (arg0 && *ext_val == NULL_RTX && GET_CODE (arg0) == REG)
6891 *ext_val = gen_rtx_fmt_e (GET_CODE (x), mode, arg0);
6892 return arg0;
6895 goto do_default;
6897 case REG:
6898 /* If this is a new register, we can't deal with it. */
6899 if (REGNO (x) >= max_reg_before_loop)
6900 return 0;
6902 /* Check for biv or giv. */
6903 switch (REG_IV_TYPE (ivs, REGNO (x)))
6905 case BASIC_INDUCT:
6906 return x;
6907 case GENERAL_INDUCT:
6909 struct induction *v = REG_IV_INFO (ivs, REGNO (x));
6911 /* Form expression from giv and add benefit. Ensure this giv
6912 can derive another and subtract any needed adjustment if so. */
6914 /* Increasing the benefit here is risky. The only case in which it
6915 is arguably correct is if this is the only use of V. In other
6916 cases, this will artificially inflate the benefit of the current
6917 giv, and lead to suboptimal code. Thus, it is disabled, since
6918 potentially not reducing an only marginally beneficial giv is
6919 less harmful than reducing many givs that are not really
6920 beneficial. */
6922 rtx single_use = regs->array[REGNO (x)].single_usage;
6923 if (single_use && single_use != const0_rtx)
6924 *benefit += v->benefit;
6927 if (v->cant_derive)
6928 return 0;
6930 tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6931 v->src_reg, v->mult_val),
6932 v->add_val);
6934 if (v->derive_adjustment)
6935 tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6936 arg0 = simplify_giv_expr (loop, tem, ext_val, benefit);
6937 if (*ext_val)
6939 if (!v->ext_dependent)
6940 return arg0;
6942 else
6944 *ext_val = v->ext_dependent;
6945 return arg0;
6947 return 0;
6950 default:
6951 do_default:
6952 /* If it isn't an induction variable, and it is invariant, we
6953 may be able to simplify things further by looking through
6954 the bits we just moved outside the loop. */
6955 if (loop_invariant_p (loop, x) == 1)
6957 struct movable *m;
6958 struct loop_movables *movables = LOOP_MOVABLES (loop);
6960 for (m = movables->head; m; m = m->next)
6961 if (rtx_equal_p (x, m->set_dest))
6963 /* Ok, we found a match. Substitute and simplify. */
6965 /* If we match another movable, we must use that, as
6966 this one is going away. */
6967 if (m->match)
6968 return simplify_giv_expr (loop, m->match->set_dest,
6969 ext_val, benefit);
6971 /* If consec is nonzero, this is a member of a group of
6972 instructions that were moved together. We handle this
6973 case only to the point of seeking to the last insn and
6974 looking for a REG_EQUAL. Fail if we don't find one. */
6975 if (m->consec != 0)
6977 int i = m->consec;
6978 tem = m->insn;
6981 tem = NEXT_INSN (tem);
6983 while (--i > 0);
6985 tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6986 if (tem)
6987 tem = XEXP (tem, 0);
6989 else
6991 tem = single_set (m->insn);
6992 if (tem)
6993 tem = SET_SRC (tem);
6996 if (tem)
6998 /* What we are most interested in is pointer
6999 arithmetic on invariants -- only take
7000 patterns we may be able to do something with. */
7001 if (GET_CODE (tem) == PLUS
7002 || GET_CODE (tem) == MULT
7003 || GET_CODE (tem) == ASHIFT
7004 || GET_CODE (tem) == CONST_INT
7005 || GET_CODE (tem) == SYMBOL_REF)
7007 tem = simplify_giv_expr (loop, tem, ext_val,
7008 benefit);
7009 if (tem)
7010 return tem;
7012 else if (GET_CODE (tem) == CONST
7013 && GET_CODE (XEXP (tem, 0)) == PLUS
7014 && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
7015 && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
7017 tem = simplify_giv_expr (loop, XEXP (tem, 0),
7018 ext_val, benefit);
7019 if (tem)
7020 return tem;
7023 break;
7026 break;
7029 /* Fall through to general case. */
7030 default:
7031 /* If invariant, return as USE (unless CONST_INT).
7032 Otherwise, not giv. */
7033 if (GET_CODE (x) == USE)
7034 x = XEXP (x, 0);
7036 if (loop_invariant_p (loop, x) == 1)
7038 if (GET_CODE (x) == CONST_INT)
7039 return x;
7040 if (GET_CODE (x) == CONST
7041 && GET_CODE (XEXP (x, 0)) == PLUS
7042 && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
7043 && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
7044 x = XEXP (x, 0);
7045 return gen_rtx_USE (mode, x);
7047 else
7048 return 0;
7052 /* This routine folds invariants such that there is only ever one
7053 CONST_INT in the summation. It is only used by simplify_giv_expr. */
7055 static rtx
7056 sge_plus_constant (x, c)
7057 rtx x, c;
7059 if (GET_CODE (x) == CONST_INT)
7060 return GEN_INT (INTVAL (x) + INTVAL (c));
7061 else if (GET_CODE (x) != PLUS)
7062 return gen_rtx_PLUS (GET_MODE (x), x, c);
7063 else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7065 return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
7066 GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
7068 else if (GET_CODE (XEXP (x, 0)) == PLUS
7069 || GET_CODE (XEXP (x, 1)) != PLUS)
7071 return gen_rtx_PLUS (GET_MODE (x),
7072 sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
7074 else
7076 return gen_rtx_PLUS (GET_MODE (x),
7077 sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
7081 static rtx
7082 sge_plus (mode, x, y)
7083 enum machine_mode mode;
7084 rtx x, y;
7086 while (GET_CODE (y) == PLUS)
7088 rtx a = XEXP (y, 0);
7089 if (GET_CODE (a) == CONST_INT)
7090 x = sge_plus_constant (x, a);
7091 else
7092 x = gen_rtx_PLUS (mode, x, a);
7093 y = XEXP (y, 1);
7095 if (GET_CODE (y) == CONST_INT)
7096 x = sge_plus_constant (x, y);
7097 else
7098 x = gen_rtx_PLUS (mode, x, y);
7099 return x;
7102 /* Help detect a giv that is calculated by several consecutive insns;
7103 for example,
7104 giv = biv * M
7105 giv = giv + A
7106 The caller has already identified the first insn P as having a giv as dest;
7107 we check that all other insns that set the same register follow
7108 immediately after P, that they alter nothing else,
7109 and that the result of the last is still a giv.
7111 The value is 0 if the reg set in P is not really a giv.
7112 Otherwise, the value is the amount gained by eliminating
7113 all the consecutive insns that compute the value.
7115 FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
7116 SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
7118 The coefficients of the ultimate giv value are stored in
7119 *MULT_VAL and *ADD_VAL. */
7121 static int
7122 consec_sets_giv (loop, first_benefit, p, src_reg, dest_reg,
7123 add_val, mult_val, ext_val, last_consec_insn)
7124 const struct loop *loop;
7125 int first_benefit;
7126 rtx p;
7127 rtx src_reg;
7128 rtx dest_reg;
7129 rtx *add_val;
7130 rtx *mult_val;
7131 rtx *ext_val;
7132 rtx *last_consec_insn;
7134 struct loop_ivs *ivs = LOOP_IVS (loop);
7135 struct loop_regs *regs = LOOP_REGS (loop);
7136 int count;
7137 enum rtx_code code;
7138 int benefit;
7139 rtx temp;
7140 rtx set;
7142 /* Indicate that this is a giv so that we can update the value produced in
7143 each insn of the multi-insn sequence.
7145 This induction structure will be used only by the call to
7146 general_induction_var below, so we can allocate it on our stack.
7147 If this is a giv, our caller will replace the induct var entry with
7148 a new induction structure. */
7149 struct induction *v;
7151 if (REG_IV_TYPE (ivs, REGNO (dest_reg)) != UNKNOWN_INDUCT)
7152 return 0;
7154 v = (struct induction *) alloca (sizeof (struct induction));
7155 v->src_reg = src_reg;
7156 v->mult_val = *mult_val;
7157 v->add_val = *add_val;
7158 v->benefit = first_benefit;
7159 v->cant_derive = 0;
7160 v->derive_adjustment = 0;
7161 v->ext_dependent = NULL_RTX;
7163 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
7164 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
7166 count = regs->array[REGNO (dest_reg)].n_times_set - 1;
7168 while (count > 0)
7170 p = NEXT_INSN (p);
7171 code = GET_CODE (p);
7173 /* If libcall, skip to end of call sequence. */
7174 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
7175 p = XEXP (temp, 0);
7177 if (code == INSN
7178 && (set = single_set (p))
7179 && GET_CODE (SET_DEST (set)) == REG
7180 && SET_DEST (set) == dest_reg
7181 && (general_induction_var (loop, SET_SRC (set), &src_reg,
7182 add_val, mult_val, ext_val, 0,
7183 &benefit, VOIDmode)
7184 /* Giv created by equivalent expression. */
7185 || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
7186 && general_induction_var (loop, XEXP (temp, 0), &src_reg,
7187 add_val, mult_val, ext_val, 0,
7188 &benefit, VOIDmode)))
7189 && src_reg == v->src_reg)
7191 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
7192 benefit += libcall_benefit (p);
7194 count--;
7195 v->mult_val = *mult_val;
7196 v->add_val = *add_val;
7197 v->benefit += benefit;
7199 else if (code != NOTE)
7201 /* Allow insns that set something other than this giv to a
7202 constant. Such insns are needed on machines which cannot
7203 include long constants and should not disqualify a giv. */
7204 if (code == INSN
7205 && (set = single_set (p))
7206 && SET_DEST (set) != dest_reg
7207 && CONSTANT_P (SET_SRC (set)))
7208 continue;
7210 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7211 return 0;
7215 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7216 *last_consec_insn = p;
7217 return v->benefit;
7220 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7221 represented by G1. If no such expression can be found, or it is clear that
7222 it cannot possibly be a valid address, 0 is returned.
7224 To perform the computation, we note that
7225 G1 = x * v + a and
7226 G2 = y * v + b
7227 where `v' is the biv.
7229 So G2 = (y/b) * G1 + (b - a*y/x).
7231 Note that MULT = y/x.
7233 Update: A and B are now allowed to be additive expressions such that
7234 B contains all variables in A. That is, computing B-A will not require
7235 subtracting variables. */
7237 static rtx
7238 express_from_1 (a, b, mult)
7239 rtx a, b, mult;
7241 /* If MULT is zero, then A*MULT is zero, and our expression is B. */
7243 if (mult == const0_rtx)
7244 return b;
7246 /* If MULT is not 1, we cannot handle A with non-constants, since we
7247 would then be required to subtract multiples of the registers in A.
7248 This is theoretically possible, and may even apply to some Fortran
7249 constructs, but it is a lot of work and we do not attempt it here. */
7251 if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
7252 return NULL_RTX;
7254 /* In general these structures are sorted top to bottom (down the PLUS
7255 chain), but not left to right across the PLUS. If B is a higher
7256 order giv than A, we can strip one level and recurse. If A is higher
7257 order, we'll eventually bail out, but won't know that until the end.
7258 If they are the same, we'll strip one level around this loop. */
7260 while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
7262 rtx ra, rb, oa, ob, tmp;
7264 ra = XEXP (a, 0), oa = XEXP (a, 1);
7265 if (GET_CODE (ra) == PLUS)
7266 tmp = ra, ra = oa, oa = tmp;
7268 rb = XEXP (b, 0), ob = XEXP (b, 1);
7269 if (GET_CODE (rb) == PLUS)
7270 tmp = rb, rb = ob, ob = tmp;
7272 if (rtx_equal_p (ra, rb))
7273 /* We matched: remove one reg completely. */
7274 a = oa, b = ob;
7275 else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
7276 /* An alternate match. */
7277 a = oa, b = rb;
7278 else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
7279 /* An alternate match. */
7280 a = ra, b = ob;
7281 else
7283 /* Indicates an extra register in B. Strip one level from B and
7284 recurse, hoping B was the higher order expression. */
7285 ob = express_from_1 (a, ob, mult);
7286 if (ob == NULL_RTX)
7287 return NULL_RTX;
7288 return gen_rtx_PLUS (GET_MODE (b), rb, ob);
7292 /* Here we are at the last level of A, go through the cases hoping to
7293 get rid of everything but a constant. */
7295 if (GET_CODE (a) == PLUS)
7297 rtx ra, oa;
7299 ra = XEXP (a, 0), oa = XEXP (a, 1);
7300 if (rtx_equal_p (oa, b))
7301 oa = ra;
7302 else if (!rtx_equal_p (ra, b))
7303 return NULL_RTX;
7305 if (GET_CODE (oa) != CONST_INT)
7306 return NULL_RTX;
7308 return GEN_INT (-INTVAL (oa) * INTVAL (mult));
7310 else if (GET_CODE (a) == CONST_INT)
7312 return plus_constant (b, -INTVAL (a) * INTVAL (mult));
7314 else if (CONSTANT_P (a))
7316 enum machine_mode mode_a = GET_MODE (a);
7317 enum machine_mode mode_b = GET_MODE (b);
7318 enum machine_mode mode = mode_b == VOIDmode ? mode_a : mode_b;
7319 return simplify_gen_binary (MINUS, mode, b, a);
7321 else if (GET_CODE (b) == PLUS)
7323 if (rtx_equal_p (a, XEXP (b, 0)))
7324 return XEXP (b, 1);
7325 else if (rtx_equal_p (a, XEXP (b, 1)))
7326 return XEXP (b, 0);
7327 else
7328 return NULL_RTX;
7330 else if (rtx_equal_p (a, b))
7331 return const0_rtx;
7333 return NULL_RTX;
7337 express_from (g1, g2)
7338 struct induction *g1, *g2;
7340 rtx mult, add;
7342 /* The value that G1 will be multiplied by must be a constant integer. Also,
7343 the only chance we have of getting a valid address is if b*c/a (see above
7344 for notation) is also an integer. */
7345 if (GET_CODE (g1->mult_val) == CONST_INT
7346 && GET_CODE (g2->mult_val) == CONST_INT)
7348 if (g1->mult_val == const0_rtx
7349 || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
7350 return NULL_RTX;
7351 mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
7353 else if (rtx_equal_p (g1->mult_val, g2->mult_val))
7354 mult = const1_rtx;
7355 else
7357 /* ??? Find out if the one is a multiple of the other? */
7358 return NULL_RTX;
7361 add = express_from_1 (g1->add_val, g2->add_val, mult);
7362 if (add == NULL_RTX)
7364 /* Failed. If we've got a multiplication factor between G1 and G2,
7365 scale G1's addend and try again. */
7366 if (INTVAL (mult) > 1)
7368 rtx g1_add_val = g1->add_val;
7369 if (GET_CODE (g1_add_val) == MULT
7370 && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
7372 HOST_WIDE_INT m;
7373 m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
7374 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
7375 XEXP (g1_add_val, 0), GEN_INT (m));
7377 else
7379 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
7380 mult);
7383 add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
7386 if (add == NULL_RTX)
7387 return NULL_RTX;
7389 /* Form simplified final result. */
7390 if (mult == const0_rtx)
7391 return add;
7392 else if (mult == const1_rtx)
7393 mult = g1->dest_reg;
7394 else
7395 mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
7397 if (add == const0_rtx)
7398 return mult;
7399 else
7401 if (GET_CODE (add) == PLUS
7402 && CONSTANT_P (XEXP (add, 1)))
7404 rtx tem = XEXP (add, 1);
7405 mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
7406 add = tem;
7409 return gen_rtx_PLUS (g2->mode, mult, add);
7413 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7414 represented by G1. This indicates that G2 should be combined with G1 and
7415 that G2 can use (either directly or via an address expression) a register
7416 used to represent G1. */
7418 static rtx
7419 combine_givs_p (g1, g2)
7420 struct induction *g1, *g2;
7422 rtx comb, ret;
7424 /* With the introduction of ext dependent givs, we must care for modes.
7425 G2 must not use a wider mode than G1. */
7426 if (GET_MODE_SIZE (g1->mode) < GET_MODE_SIZE (g2->mode))
7427 return NULL_RTX;
7429 ret = comb = express_from (g1, g2);
7430 if (comb == NULL_RTX)
7431 return NULL_RTX;
7432 if (g1->mode != g2->mode)
7433 ret = gen_lowpart (g2->mode, comb);
7435 /* If these givs are identical, they can be combined. We use the results
7436 of express_from because the addends are not in a canonical form, so
7437 rtx_equal_p is a weaker test. */
7438 /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
7439 combination to be the other way round. */
7440 if (comb == g1->dest_reg
7441 && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
7443 return ret;
7446 /* If G2 can be expressed as a function of G1 and that function is valid
7447 as an address and no more expensive than using a register for G2,
7448 the expression of G2 in terms of G1 can be used. */
7449 if (ret != NULL_RTX
7450 && g2->giv_type == DEST_ADDR
7451 && memory_address_p (GET_MODE (g2->mem), ret))
7452 return ret;
7454 return NULL_RTX;
7457 /* Check each extension dependent giv in this class to see if its
7458 root biv is safe from wrapping in the interior mode, which would
7459 make the giv illegal. */
7461 static void
7462 check_ext_dependent_givs (bl, loop_info)
7463 struct iv_class *bl;
7464 struct loop_info *loop_info;
7466 int ze_ok = 0, se_ok = 0, info_ok = 0;
7467 enum machine_mode biv_mode = GET_MODE (bl->biv->src_reg);
7468 HOST_WIDE_INT start_val;
7469 unsigned HOST_WIDE_INT u_end_val = 0;
7470 unsigned HOST_WIDE_INT u_start_val = 0;
7471 rtx incr = pc_rtx;
7472 struct induction *v;
7474 /* Make sure the iteration data is available. We must have
7475 constants in order to be certain of no overflow. */
7476 /* ??? An unknown iteration count with an increment of +-1
7477 combined with friendly exit tests of against an invariant
7478 value is also amenable to optimization. Not implemented. */
7479 if (loop_info->n_iterations > 0
7480 && bl->initial_value
7481 && GET_CODE (bl->initial_value) == CONST_INT
7482 && (incr = biv_total_increment (bl))
7483 && GET_CODE (incr) == CONST_INT
7484 /* Make sure the host can represent the arithmetic. */
7485 && HOST_BITS_PER_WIDE_INT >= GET_MODE_BITSIZE (biv_mode))
7487 unsigned HOST_WIDE_INT abs_incr, total_incr;
7488 HOST_WIDE_INT s_end_val;
7489 int neg_incr;
7491 info_ok = 1;
7492 start_val = INTVAL (bl->initial_value);
7493 u_start_val = start_val;
7495 neg_incr = 0, abs_incr = INTVAL (incr);
7496 if (INTVAL (incr) < 0)
7497 neg_incr = 1, abs_incr = -abs_incr;
7498 total_incr = abs_incr * loop_info->n_iterations;
7500 /* Check for host arithmetic overflow. */
7501 if (total_incr / loop_info->n_iterations == abs_incr)
7503 unsigned HOST_WIDE_INT u_max;
7504 HOST_WIDE_INT s_max;
7506 u_end_val = start_val + (neg_incr ? -total_incr : total_incr);
7507 s_end_val = u_end_val;
7508 u_max = GET_MODE_MASK (biv_mode);
7509 s_max = u_max >> 1;
7511 /* Check zero extension of biv ok. */
7512 if (start_val >= 0
7513 /* Check for host arithmetic overflow. */
7514 && (neg_incr
7515 ? u_end_val < u_start_val
7516 : u_end_val > u_start_val)
7517 /* Check for target arithmetic overflow. */
7518 && (neg_incr
7519 ? 1 /* taken care of with host overflow */
7520 : u_end_val <= u_max))
7522 ze_ok = 1;
7525 /* Check sign extension of biv ok. */
7526 /* ??? While it is true that overflow with signed and pointer
7527 arithmetic is undefined, I fear too many programmers don't
7528 keep this fact in mind -- myself included on occasion.
7529 So leave alone with the signed overflow optimizations. */
7530 if (start_val >= -s_max - 1
7531 /* Check for host arithmetic overflow. */
7532 && (neg_incr
7533 ? s_end_val < start_val
7534 : s_end_val > start_val)
7535 /* Check for target arithmetic overflow. */
7536 && (neg_incr
7537 ? s_end_val >= -s_max - 1
7538 : s_end_val <= s_max))
7540 se_ok = 1;
7545 /* Invalidate givs that fail the tests. */
7546 for (v = bl->giv; v; v = v->next_iv)
7547 if (v->ext_dependent)
7549 enum rtx_code code = GET_CODE (v->ext_dependent);
7550 int ok = 0;
7552 switch (code)
7554 case SIGN_EXTEND:
7555 ok = se_ok;
7556 break;
7557 case ZERO_EXTEND:
7558 ok = ze_ok;
7559 break;
7561 case TRUNCATE:
7562 /* We don't know whether this value is being used as either
7563 signed or unsigned, so to safely truncate we must satisfy
7564 both. The initial check here verifies the BIV itself;
7565 once that is successful we may check its range wrt the
7566 derived GIV. */
7567 if (se_ok && ze_ok)
7569 enum machine_mode outer_mode = GET_MODE (v->ext_dependent);
7570 unsigned HOST_WIDE_INT max = GET_MODE_MASK (outer_mode) >> 1;
7572 /* We know from the above that both endpoints are nonnegative,
7573 and that there is no wrapping. Verify that both endpoints
7574 are within the (signed) range of the outer mode. */
7575 if (u_start_val <= max && u_end_val <= max)
7576 ok = 1;
7578 break;
7580 default:
7581 abort ();
7584 if (ok)
7586 if (loop_dump_stream)
7588 fprintf (loop_dump_stream,
7589 "Verified ext dependent giv at %d of reg %d\n",
7590 INSN_UID (v->insn), bl->regno);
7593 else
7595 if (loop_dump_stream)
7597 const char *why;
7599 if (info_ok)
7600 why = "biv iteration values overflowed";
7601 else
7603 if (incr == pc_rtx)
7604 incr = biv_total_increment (bl);
7605 if (incr == const1_rtx)
7606 why = "biv iteration info incomplete; incr by 1";
7607 else
7608 why = "biv iteration info incomplete";
7611 fprintf (loop_dump_stream,
7612 "Failed ext dependent giv at %d, %s\n",
7613 INSN_UID (v->insn), why);
7615 v->ignore = 1;
7616 bl->all_reduced = 0;
7621 /* Generate a version of VALUE in a mode appropriate for initializing V. */
7624 extend_value_for_giv (v, value)
7625 struct induction *v;
7626 rtx value;
7628 rtx ext_dep = v->ext_dependent;
7630 if (! ext_dep)
7631 return value;
7633 /* Recall that check_ext_dependent_givs verified that the known bounds
7634 of a biv did not overflow or wrap with respect to the extension for
7635 the giv. Therefore, constants need no additional adjustment. */
7636 if (CONSTANT_P (value) && GET_MODE (value) == VOIDmode)
7637 return value;
7639 /* Otherwise, we must adjust the value to compensate for the
7640 differing modes of the biv and the giv. */
7641 return gen_rtx_fmt_e (GET_CODE (ext_dep), GET_MODE (ext_dep), value);
7644 struct combine_givs_stats
7646 int giv_number;
7647 int total_benefit;
7650 static int
7651 cmp_combine_givs_stats (xp, yp)
7652 const PTR xp;
7653 const PTR yp;
7655 const struct combine_givs_stats * const x =
7656 (const struct combine_givs_stats *) xp;
7657 const struct combine_givs_stats * const y =
7658 (const struct combine_givs_stats *) yp;
7659 int d;
7660 d = y->total_benefit - x->total_benefit;
7661 /* Stabilize the sort. */
7662 if (!d)
7663 d = x->giv_number - y->giv_number;
7664 return d;
7667 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7668 any other. If so, point SAME to the giv combined with and set NEW_REG to
7669 be an expression (in terms of the other giv's DEST_REG) equivalent to the
7670 giv. Also, update BENEFIT and related fields for cost/benefit analysis. */
7672 static void
7673 combine_givs (regs, bl)
7674 struct loop_regs *regs;
7675 struct iv_class *bl;
7677 /* Additional benefit to add for being combined multiple times. */
7678 const int extra_benefit = 3;
7680 struct induction *g1, *g2, **giv_array;
7681 int i, j, k, giv_count;
7682 struct combine_givs_stats *stats;
7683 rtx *can_combine;
7685 /* Count givs, because bl->giv_count is incorrect here. */
7686 giv_count = 0;
7687 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7688 if (!g1->ignore)
7689 giv_count++;
7691 giv_array
7692 = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7693 i = 0;
7694 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7695 if (!g1->ignore)
7696 giv_array[i++] = g1;
7698 stats = (struct combine_givs_stats *) xcalloc (giv_count, sizeof (*stats));
7699 can_combine = (rtx *) xcalloc (giv_count, giv_count * sizeof (rtx));
7701 for (i = 0; i < giv_count; i++)
7703 int this_benefit;
7704 rtx single_use;
7706 g1 = giv_array[i];
7707 stats[i].giv_number = i;
7709 /* If a DEST_REG GIV is used only once, do not allow it to combine
7710 with anything, for in doing so we will gain nothing that cannot
7711 be had by simply letting the GIV with which we would have combined
7712 to be reduced on its own. The losage shows up in particular with
7713 DEST_ADDR targets on hosts with reg+reg addressing, though it can
7714 be seen elsewhere as well. */
7715 if (g1->giv_type == DEST_REG
7716 && (single_use = regs->array[REGNO (g1->dest_reg)].single_usage)
7717 && single_use != const0_rtx)
7718 continue;
7720 this_benefit = g1->benefit;
7721 /* Add an additional weight for zero addends. */
7722 if (g1->no_const_addval)
7723 this_benefit += 1;
7725 for (j = 0; j < giv_count; j++)
7727 rtx this_combine;
7729 g2 = giv_array[j];
7730 if (g1 != g2
7731 && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7733 can_combine[i * giv_count + j] = this_combine;
7734 this_benefit += g2->benefit + extra_benefit;
7737 stats[i].total_benefit = this_benefit;
7740 /* Iterate, combining until we can't. */
7741 restart:
7742 qsort (stats, giv_count, sizeof (*stats), cmp_combine_givs_stats);
7744 if (loop_dump_stream)
7746 fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7747 for (k = 0; k < giv_count; k++)
7749 g1 = giv_array[stats[k].giv_number];
7750 if (!g1->combined_with && !g1->same)
7751 fprintf (loop_dump_stream, " {%d, %d}",
7752 INSN_UID (giv_array[stats[k].giv_number]->insn),
7753 stats[k].total_benefit);
7755 putc ('\n', loop_dump_stream);
7758 for (k = 0; k < giv_count; k++)
7760 int g1_add_benefit = 0;
7762 i = stats[k].giv_number;
7763 g1 = giv_array[i];
7765 /* If it has already been combined, skip. */
7766 if (g1->combined_with || g1->same)
7767 continue;
7769 for (j = 0; j < giv_count; j++)
7771 g2 = giv_array[j];
7772 if (g1 != g2 && can_combine[i * giv_count + j]
7773 /* If it has already been combined, skip. */
7774 && ! g2->same && ! g2->combined_with)
7776 int l;
7778 g2->new_reg = can_combine[i * giv_count + j];
7779 g2->same = g1;
7780 /* For destination, we now may replace by mem expression instead
7781 of register. This changes the costs considerably, so add the
7782 compensation. */
7783 if (g2->giv_type == DEST_ADDR)
7784 g2->benefit = (g2->benefit + reg_address_cost
7785 - address_cost (g2->new_reg,
7786 GET_MODE (g2->mem)));
7787 g1->combined_with++;
7788 g1->lifetime += g2->lifetime;
7790 g1_add_benefit += g2->benefit;
7792 /* ??? The new final_[bg]iv_value code does a much better job
7793 of finding replaceable giv's, and hence this code may no
7794 longer be necessary. */
7795 if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7796 g1_add_benefit -= copy_cost;
7798 /* To help optimize the next set of combinations, remove
7799 this giv from the benefits of other potential mates. */
7800 for (l = 0; l < giv_count; ++l)
7802 int m = stats[l].giv_number;
7803 if (can_combine[m * giv_count + j])
7804 stats[l].total_benefit -= g2->benefit + extra_benefit;
7807 if (loop_dump_stream)
7808 fprintf (loop_dump_stream,
7809 "giv at %d combined with giv at %d; new benefit %d + %d, lifetime %d\n",
7810 INSN_UID (g2->insn), INSN_UID (g1->insn),
7811 g1->benefit, g1_add_benefit, g1->lifetime);
7815 /* To help optimize the next set of combinations, remove
7816 this giv from the benefits of other potential mates. */
7817 if (g1->combined_with)
7819 for (j = 0; j < giv_count; ++j)
7821 int m = stats[j].giv_number;
7822 if (can_combine[m * giv_count + i])
7823 stats[j].total_benefit -= g1->benefit + extra_benefit;
7826 g1->benefit += g1_add_benefit;
7828 /* We've finished with this giv, and everything it touched.
7829 Restart the combination so that proper weights for the
7830 rest of the givs are properly taken into account. */
7831 /* ??? Ideally we would compact the arrays at this point, so
7832 as to not cover old ground. But sanely compacting
7833 can_combine is tricky. */
7834 goto restart;
7838 /* Clean up. */
7839 free (stats);
7840 free (can_combine);
7843 /* Generate sequence for REG = B * M + A. */
7845 static rtx
7846 gen_add_mult (b, m, a, reg)
7847 rtx b; /* initial value of basic induction variable */
7848 rtx m; /* multiplicative constant */
7849 rtx a; /* additive constant */
7850 rtx reg; /* destination register */
7852 rtx seq;
7853 rtx result;
7855 start_sequence ();
7856 /* Use unsigned arithmetic. */
7857 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
7858 if (reg != result)
7859 emit_move_insn (reg, result);
7860 seq = get_insns ();
7861 end_sequence ();
7863 return seq;
7867 /* Update registers created in insn sequence SEQ. */
7869 static void
7870 loop_regs_update (loop, seq)
7871 const struct loop *loop ATTRIBUTE_UNUSED;
7872 rtx seq;
7874 rtx insn;
7876 /* Update register info for alias analysis. */
7878 if (seq == NULL_RTX)
7879 return;
7881 if (INSN_P (seq))
7883 insn = seq;
7884 while (insn != NULL_RTX)
7886 rtx set = single_set (insn);
7888 if (set && GET_CODE (SET_DEST (set)) == REG)
7889 record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7891 insn = NEXT_INSN (insn);
7894 else if (GET_CODE (seq) == SET
7895 && GET_CODE (SET_DEST (seq)) == REG)
7896 record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
7900 /* EMIT code before BEFORE_BB/BEFORE_INSN to set REG = B * M + A. */
7902 void
7903 loop_iv_add_mult_emit_before (loop, b, m, a, reg, before_bb, before_insn)
7904 const struct loop *loop;
7905 rtx b; /* initial value of basic induction variable */
7906 rtx m; /* multiplicative constant */
7907 rtx a; /* additive constant */
7908 rtx reg; /* destination register */
7909 basic_block before_bb;
7910 rtx before_insn;
7912 rtx seq;
7914 if (! before_insn)
7916 loop_iv_add_mult_hoist (loop, b, m, a, reg);
7917 return;
7920 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7921 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7923 /* Increase the lifetime of any invariants moved further in code. */
7924 update_reg_last_use (a, before_insn);
7925 update_reg_last_use (b, before_insn);
7926 update_reg_last_use (m, before_insn);
7928 loop_insn_emit_before (loop, before_bb, before_insn, seq);
7930 /* It is possible that the expansion created lots of new registers.
7931 Iterate over the sequence we just created and record them all. */
7932 loop_regs_update (loop, seq);
7936 /* Emit insns in loop pre-header to set REG = B * M + A. */
7938 void
7939 loop_iv_add_mult_sink (loop, b, m, a, reg)
7940 const struct loop *loop;
7941 rtx b; /* initial value of basic induction variable */
7942 rtx m; /* multiplicative constant */
7943 rtx a; /* additive constant */
7944 rtx reg; /* destination register */
7946 rtx seq;
7948 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7949 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7951 /* Increase the lifetime of any invariants moved further in code.
7952 ???? Is this really necessary? */
7953 update_reg_last_use (a, loop->sink);
7954 update_reg_last_use (b, loop->sink);
7955 update_reg_last_use (m, loop->sink);
7957 loop_insn_sink (loop, seq);
7959 /* It is possible that the expansion created lots of new registers.
7960 Iterate over the sequence we just created and record them all. */
7961 loop_regs_update (loop, seq);
7965 /* Emit insns after loop to set REG = B * M + A. */
7967 void
7968 loop_iv_add_mult_hoist (loop, b, m, a, reg)
7969 const struct loop *loop;
7970 rtx b; /* initial value of basic induction variable */
7971 rtx m; /* multiplicative constant */
7972 rtx a; /* additive constant */
7973 rtx reg; /* destination register */
7975 rtx seq;
7977 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7978 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7980 loop_insn_hoist (loop, seq);
7982 /* It is possible that the expansion created lots of new registers.
7983 Iterate over the sequence we just created and record them all. */
7984 loop_regs_update (loop, seq);
7989 /* Similar to gen_add_mult, but compute cost rather than generating
7990 sequence. */
7992 static int
7993 iv_add_mult_cost (b, m, a, reg)
7994 rtx b; /* initial value of basic induction variable */
7995 rtx m; /* multiplicative constant */
7996 rtx a; /* additive constant */
7997 rtx reg; /* destination register */
7999 int cost = 0;
8000 rtx last, result;
8002 start_sequence ();
8003 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
8004 if (reg != result)
8005 emit_move_insn (reg, result);
8006 last = get_last_insn ();
8007 while (last)
8009 rtx t = single_set (last);
8010 if (t)
8011 cost += rtx_cost (SET_SRC (t), SET);
8012 last = PREV_INSN (last);
8014 end_sequence ();
8015 return cost;
8018 /* Test whether A * B can be computed without
8019 an actual multiply insn. Value is 1 if so.
8021 ??? This function stinks because it generates a ton of wasted RTL
8022 ??? and as a result fragments GC memory to no end. There are other
8023 ??? places in the compiler which are invoked a lot and do the same
8024 ??? thing, generate wasted RTL just to see if something is possible. */
8026 static int
8027 product_cheap_p (a, b)
8028 rtx a;
8029 rtx b;
8031 rtx tmp;
8032 int win, n_insns;
8034 /* If only one is constant, make it B. */
8035 if (GET_CODE (a) == CONST_INT)
8036 tmp = a, a = b, b = tmp;
8038 /* If first constant, both constant, so don't need multiply. */
8039 if (GET_CODE (a) == CONST_INT)
8040 return 1;
8042 /* If second not constant, neither is constant, so would need multiply. */
8043 if (GET_CODE (b) != CONST_INT)
8044 return 0;
8046 /* One operand is constant, so might not need multiply insn. Generate the
8047 code for the multiply and see if a call or multiply, or long sequence
8048 of insns is generated. */
8050 start_sequence ();
8051 expand_mult (GET_MODE (a), a, b, NULL_RTX, 1);
8052 tmp = get_insns ();
8053 end_sequence ();
8055 win = 1;
8056 if (INSN_P (tmp))
8058 n_insns = 0;
8059 while (tmp != NULL_RTX)
8061 rtx next = NEXT_INSN (tmp);
8063 if (++n_insns > 3
8064 || GET_CODE (tmp) != INSN
8065 || (GET_CODE (PATTERN (tmp)) == SET
8066 && GET_CODE (SET_SRC (PATTERN (tmp))) == MULT)
8067 || (GET_CODE (PATTERN (tmp)) == PARALLEL
8068 && GET_CODE (XVECEXP (PATTERN (tmp), 0, 0)) == SET
8069 && GET_CODE (SET_SRC (XVECEXP (PATTERN (tmp), 0, 0))) == MULT))
8071 win = 0;
8072 break;
8075 tmp = next;
8078 else if (GET_CODE (tmp) == SET
8079 && GET_CODE (SET_SRC (tmp)) == MULT)
8080 win = 0;
8081 else if (GET_CODE (tmp) == PARALLEL
8082 && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
8083 && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
8084 win = 0;
8086 return win;
8089 /* Check to see if loop can be terminated by a "decrement and branch until
8090 zero" instruction. If so, add a REG_NONNEG note to the branch insn if so.
8091 Also try reversing an increment loop to a decrement loop
8092 to see if the optimization can be performed.
8093 Value is nonzero if optimization was performed. */
8095 /* This is useful even if the architecture doesn't have such an insn,
8096 because it might change a loops which increments from 0 to n to a loop
8097 which decrements from n to 0. A loop that decrements to zero is usually
8098 faster than one that increments from zero. */
8100 /* ??? This could be rewritten to use some of the loop unrolling procedures,
8101 such as approx_final_value, biv_total_increment, loop_iterations, and
8102 final_[bg]iv_value. */
8104 static int
8105 check_dbra_loop (loop, insn_count)
8106 struct loop *loop;
8107 int insn_count;
8109 struct loop_info *loop_info = LOOP_INFO (loop);
8110 struct loop_regs *regs = LOOP_REGS (loop);
8111 struct loop_ivs *ivs = LOOP_IVS (loop);
8112 struct iv_class *bl;
8113 rtx reg;
8114 rtx jump_label;
8115 rtx final_value;
8116 rtx start_value;
8117 rtx new_add_val;
8118 rtx comparison;
8119 rtx before_comparison;
8120 rtx p;
8121 rtx jump;
8122 rtx first_compare;
8123 int compare_and_branch;
8124 rtx loop_start = loop->start;
8125 rtx loop_end = loop->end;
8127 /* If last insn is a conditional branch, and the insn before tests a
8128 register value, try to optimize it. Otherwise, we can't do anything. */
8130 jump = PREV_INSN (loop_end);
8131 comparison = get_condition_for_loop (loop, jump);
8132 if (comparison == 0)
8133 return 0;
8134 if (!onlyjump_p (jump))
8135 return 0;
8137 /* Try to compute whether the compare/branch at the loop end is one or
8138 two instructions. */
8139 get_condition (jump, &first_compare);
8140 if (first_compare == jump)
8141 compare_and_branch = 1;
8142 else if (first_compare == prev_nonnote_insn (jump))
8143 compare_and_branch = 2;
8144 else
8145 return 0;
8148 /* If more than one condition is present to control the loop, then
8149 do not proceed, as this function does not know how to rewrite
8150 loop tests with more than one condition.
8152 Look backwards from the first insn in the last comparison
8153 sequence and see if we've got another comparison sequence. */
8155 rtx jump1;
8156 if ((jump1 = prev_nonnote_insn (first_compare)) != loop->cont)
8157 if (GET_CODE (jump1) == JUMP_INSN)
8158 return 0;
8161 /* Check all of the bivs to see if the compare uses one of them.
8162 Skip biv's set more than once because we can't guarantee that
8163 it will be zero on the last iteration. Also skip if the biv is
8164 used between its update and the test insn. */
8166 for (bl = ivs->list; bl; bl = bl->next)
8168 if (bl->biv_count == 1
8169 && ! bl->biv->maybe_multiple
8170 && bl->biv->dest_reg == XEXP (comparison, 0)
8171 && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
8172 first_compare))
8173 break;
8176 if (! bl)
8177 return 0;
8179 /* Look for the case where the basic induction variable is always
8180 nonnegative, and equals zero on the last iteration.
8181 In this case, add a reg_note REG_NONNEG, which allows the
8182 m68k DBRA instruction to be used. */
8184 if (((GET_CODE (comparison) == GT
8185 && GET_CODE (XEXP (comparison, 1)) == CONST_INT
8186 && INTVAL (XEXP (comparison, 1)) == -1)
8187 || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
8188 && GET_CODE (bl->biv->add_val) == CONST_INT
8189 && INTVAL (bl->biv->add_val) < 0)
8191 /* Initial value must be greater than 0,
8192 init_val % -dec_value == 0 to ensure that it equals zero on
8193 the last iteration */
8195 if (GET_CODE (bl->initial_value) == CONST_INT
8196 && INTVAL (bl->initial_value) > 0
8197 && (INTVAL (bl->initial_value)
8198 % (-INTVAL (bl->biv->add_val))) == 0)
8200 /* register always nonnegative, add REG_NOTE to branch */
8201 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8202 REG_NOTES (jump)
8203 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8204 REG_NOTES (jump));
8205 bl->nonneg = 1;
8207 return 1;
8210 /* If the decrement is 1 and the value was tested as >= 0 before
8211 the loop, then we can safely optimize. */
8212 for (p = loop_start; p; p = PREV_INSN (p))
8214 if (GET_CODE (p) == CODE_LABEL)
8215 break;
8216 if (GET_CODE (p) != JUMP_INSN)
8217 continue;
8219 before_comparison = get_condition_for_loop (loop, p);
8220 if (before_comparison
8221 && XEXP (before_comparison, 0) == bl->biv->dest_reg
8222 && GET_CODE (before_comparison) == LT
8223 && XEXP (before_comparison, 1) == const0_rtx
8224 && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
8225 && INTVAL (bl->biv->add_val) == -1)
8227 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8228 REG_NOTES (jump)
8229 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8230 REG_NOTES (jump));
8231 bl->nonneg = 1;
8233 return 1;
8237 else if (GET_CODE (bl->biv->add_val) == CONST_INT
8238 && INTVAL (bl->biv->add_val) > 0)
8240 /* Try to change inc to dec, so can apply above optimization. */
8241 /* Can do this if:
8242 all registers modified are induction variables or invariant,
8243 all memory references have non-overlapping addresses
8244 (obviously true if only one write)
8245 allow 2 insns for the compare/jump at the end of the loop. */
8246 /* Also, we must avoid any instructions which use both the reversed
8247 biv and another biv. Such instructions will fail if the loop is
8248 reversed. We meet this condition by requiring that either
8249 no_use_except_counting is true, or else that there is only
8250 one biv. */
8251 int num_nonfixed_reads = 0;
8252 /* 1 if the iteration var is used only to count iterations. */
8253 int no_use_except_counting = 0;
8254 /* 1 if the loop has no memory store, or it has a single memory store
8255 which is reversible. */
8256 int reversible_mem_store = 1;
8258 if (bl->giv_count == 0
8259 && !loop->exit_count
8260 && !loop_info->has_multiple_exit_targets)
8262 rtx bivreg = regno_reg_rtx[bl->regno];
8263 struct iv_class *blt;
8265 /* If there are no givs for this biv, and the only exit is the
8266 fall through at the end of the loop, then
8267 see if perhaps there are no uses except to count. */
8268 no_use_except_counting = 1;
8269 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8270 if (INSN_P (p))
8272 rtx set = single_set (p);
8274 if (set && GET_CODE (SET_DEST (set)) == REG
8275 && REGNO (SET_DEST (set)) == bl->regno)
8276 /* An insn that sets the biv is okay. */
8278 else if (!reg_mentioned_p (bivreg, PATTERN (p)))
8279 /* An insn that doesn't mention the biv is okay. */
8281 else if (p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
8282 || p == prev_nonnote_insn (loop_end))
8284 /* If either of these insns uses the biv and sets a pseudo
8285 that has more than one usage, then the biv has uses
8286 other than counting since it's used to derive a value
8287 that is used more than one time. */
8288 note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
8289 regs);
8290 if (regs->multiple_uses)
8292 no_use_except_counting = 0;
8293 break;
8296 else
8298 no_use_except_counting = 0;
8299 break;
8303 /* A biv has uses besides counting if it is used to set
8304 another biv. */
8305 for (blt = ivs->list; blt; blt = blt->next)
8306 if (blt->init_set
8307 && reg_mentioned_p (bivreg, SET_SRC (blt->init_set)))
8309 no_use_except_counting = 0;
8310 break;
8314 if (no_use_except_counting)
8315 /* No need to worry about MEMs. */
8317 else if (loop_info->num_mem_sets <= 1)
8319 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8320 if (INSN_P (p))
8321 num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
8323 /* If the loop has a single store, and the destination address is
8324 invariant, then we can't reverse the loop, because this address
8325 might then have the wrong value at loop exit.
8326 This would work if the source was invariant also, however, in that
8327 case, the insn should have been moved out of the loop. */
8329 if (loop_info->num_mem_sets == 1)
8331 struct induction *v;
8333 /* If we could prove that each of the memory locations
8334 written to was different, then we could reverse the
8335 store -- but we don't presently have any way of
8336 knowing that. */
8337 reversible_mem_store = 0;
8339 /* If the store depends on a register that is set after the
8340 store, it depends on the initial value, and is thus not
8341 reversible. */
8342 for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
8344 if (v->giv_type == DEST_REG
8345 && reg_mentioned_p (v->dest_reg,
8346 PATTERN (loop_info->first_loop_store_insn))
8347 && loop_insn_first_p (loop_info->first_loop_store_insn,
8348 v->insn))
8349 reversible_mem_store = 0;
8353 else
8354 return 0;
8356 /* This code only acts for innermost loops. Also it simplifies
8357 the memory address check by only reversing loops with
8358 zero or one memory access.
8359 Two memory accesses could involve parts of the same array,
8360 and that can't be reversed.
8361 If the biv is used only for counting, than we don't need to worry
8362 about all these things. */
8364 if ((num_nonfixed_reads <= 1
8365 && ! loop_info->has_nonconst_call
8366 && ! loop_info->has_prefetch
8367 && ! loop_info->has_volatile
8368 && reversible_mem_store
8369 && (bl->giv_count + bl->biv_count + loop_info->num_mem_sets
8370 + num_unmoved_movables (loop) + compare_and_branch == insn_count)
8371 && (bl == ivs->list && bl->next == 0))
8372 || (no_use_except_counting && ! loop_info->has_prefetch))
8374 rtx tem;
8376 /* Loop can be reversed. */
8377 if (loop_dump_stream)
8378 fprintf (loop_dump_stream, "Can reverse loop\n");
8380 /* Now check other conditions:
8382 The increment must be a constant, as must the initial value,
8383 and the comparison code must be LT.
8385 This test can probably be improved since +/- 1 in the constant
8386 can be obtained by changing LT to LE and vice versa; this is
8387 confusing. */
8389 if (comparison
8390 /* for constants, LE gets turned into LT */
8391 && (GET_CODE (comparison) == LT
8392 || (GET_CODE (comparison) == LE
8393 && no_use_except_counting)))
8395 HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8396 rtx initial_value, comparison_value;
8397 int nonneg = 0;
8398 enum rtx_code cmp_code;
8399 int comparison_const_width;
8400 unsigned HOST_WIDE_INT comparison_sign_mask;
8402 add_val = INTVAL (bl->biv->add_val);
8403 comparison_value = XEXP (comparison, 1);
8404 if (GET_MODE (comparison_value) == VOIDmode)
8405 comparison_const_width
8406 = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8407 else
8408 comparison_const_width
8409 = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8410 if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8411 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8412 comparison_sign_mask
8413 = (unsigned HOST_WIDE_INT) 1 << (comparison_const_width - 1);
8415 /* If the comparison value is not a loop invariant, then we
8416 can not reverse this loop.
8418 ??? If the insns which initialize the comparison value as
8419 a whole compute an invariant result, then we could move
8420 them out of the loop and proceed with loop reversal. */
8421 if (! loop_invariant_p (loop, comparison_value))
8422 return 0;
8424 if (GET_CODE (comparison_value) == CONST_INT)
8425 comparison_val = INTVAL (comparison_value);
8426 initial_value = bl->initial_value;
8428 /* Normalize the initial value if it is an integer and
8429 has no other use except as a counter. This will allow
8430 a few more loops to be reversed. */
8431 if (no_use_except_counting
8432 && GET_CODE (comparison_value) == CONST_INT
8433 && GET_CODE (initial_value) == CONST_INT)
8435 comparison_val = comparison_val - INTVAL (bl->initial_value);
8436 /* The code below requires comparison_val to be a multiple
8437 of add_val in order to do the loop reversal, so
8438 round up comparison_val to a multiple of add_val.
8439 Since comparison_value is constant, we know that the
8440 current comparison code is LT. */
8441 comparison_val = comparison_val + add_val - 1;
8442 comparison_val
8443 -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8444 /* We postpone overflow checks for COMPARISON_VAL here;
8445 even if there is an overflow, we might still be able to
8446 reverse the loop, if converting the loop exit test to
8447 NE is possible. */
8448 initial_value = const0_rtx;
8451 /* First check if we can do a vanilla loop reversal. */
8452 if (initial_value == const0_rtx
8453 /* If we have a decrement_and_branch_on_count,
8454 prefer the NE test, since this will allow that
8455 instruction to be generated. Note that we must
8456 use a vanilla loop reversal if the biv is used to
8457 calculate a giv or has a non-counting use. */
8458 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8459 && defined (HAVE_decrement_and_branch_on_count)
8460 && (! (add_val == 1 && loop->vtop
8461 && (bl->biv_count == 0
8462 || no_use_except_counting)))
8463 #endif
8464 && GET_CODE (comparison_value) == CONST_INT
8465 /* Now do postponed overflow checks on COMPARISON_VAL. */
8466 && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8467 & comparison_sign_mask))
8469 /* Register will always be nonnegative, with value
8470 0 on last iteration */
8471 add_adjust = add_val;
8472 nonneg = 1;
8473 cmp_code = GE;
8475 else if (add_val == 1 && loop->vtop
8476 && (bl->biv_count == 0
8477 || no_use_except_counting))
8479 add_adjust = 0;
8480 cmp_code = NE;
8482 else
8483 return 0;
8485 if (GET_CODE (comparison) == LE)
8486 add_adjust -= add_val;
8488 /* If the initial value is not zero, or if the comparison
8489 value is not an exact multiple of the increment, then we
8490 can not reverse this loop. */
8491 if (initial_value == const0_rtx
8492 && GET_CODE (comparison_value) == CONST_INT)
8494 if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8495 return 0;
8497 else
8499 if (! no_use_except_counting || add_val != 1)
8500 return 0;
8503 final_value = comparison_value;
8505 /* Reset these in case we normalized the initial value
8506 and comparison value above. */
8507 if (GET_CODE (comparison_value) == CONST_INT
8508 && GET_CODE (initial_value) == CONST_INT)
8510 comparison_value = GEN_INT (comparison_val);
8511 final_value
8512 = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8514 bl->initial_value = initial_value;
8516 /* Save some info needed to produce the new insns. */
8517 reg = bl->biv->dest_reg;
8518 jump_label = condjump_label (PREV_INSN (loop_end));
8519 new_add_val = GEN_INT (-INTVAL (bl->biv->add_val));
8521 /* Set start_value; if this is not a CONST_INT, we need
8522 to generate a SUB.
8523 Initialize biv to start_value before loop start.
8524 The old initializing insn will be deleted as a
8525 dead store by flow.c. */
8526 if (initial_value == const0_rtx
8527 && GET_CODE (comparison_value) == CONST_INT)
8529 start_value = GEN_INT (comparison_val - add_adjust);
8530 loop_insn_hoist (loop, gen_move_insn (reg, start_value));
8532 else if (GET_CODE (initial_value) == CONST_INT)
8534 enum machine_mode mode = GET_MODE (reg);
8535 rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8536 rtx add_insn = gen_add3_insn (reg, comparison_value, offset);
8538 if (add_insn == 0)
8539 return 0;
8541 start_value
8542 = gen_rtx_PLUS (mode, comparison_value, offset);
8543 loop_insn_hoist (loop, add_insn);
8544 if (GET_CODE (comparison) == LE)
8545 final_value = gen_rtx_PLUS (mode, comparison_value,
8546 GEN_INT (add_val));
8548 else if (! add_adjust)
8550 enum machine_mode mode = GET_MODE (reg);
8551 rtx sub_insn = gen_sub3_insn (reg, comparison_value,
8552 initial_value);
8554 if (sub_insn == 0)
8555 return 0;
8556 start_value
8557 = gen_rtx_MINUS (mode, comparison_value, initial_value);
8558 loop_insn_hoist (loop, sub_insn);
8560 else
8561 /* We could handle the other cases too, but it'll be
8562 better to have a testcase first. */
8563 return 0;
8565 /* We may not have a single insn which can increment a reg, so
8566 create a sequence to hold all the insns from expand_inc. */
8567 start_sequence ();
8568 expand_inc (reg, new_add_val);
8569 tem = get_insns ();
8570 end_sequence ();
8572 p = loop_insn_emit_before (loop, 0, bl->biv->insn, tem);
8573 delete_insn (bl->biv->insn);
8575 /* Update biv info to reflect its new status. */
8576 bl->biv->insn = p;
8577 bl->initial_value = start_value;
8578 bl->biv->add_val = new_add_val;
8580 /* Update loop info. */
8581 loop_info->initial_value = reg;
8582 loop_info->initial_equiv_value = reg;
8583 loop_info->final_value = const0_rtx;
8584 loop_info->final_equiv_value = const0_rtx;
8585 loop_info->comparison_value = const0_rtx;
8586 loop_info->comparison_code = cmp_code;
8587 loop_info->increment = new_add_val;
8589 /* Inc LABEL_NUSES so that delete_insn will
8590 not delete the label. */
8591 LABEL_NUSES (XEXP (jump_label, 0))++;
8593 /* Emit an insn after the end of the loop to set the biv's
8594 proper exit value if it is used anywhere outside the loop. */
8595 if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8596 || ! bl->init_insn
8597 || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8598 loop_insn_sink (loop, gen_load_of_final_value (reg, final_value));
8600 /* Delete compare/branch at end of loop. */
8601 delete_related_insns (PREV_INSN (loop_end));
8602 if (compare_and_branch == 2)
8603 delete_related_insns (first_compare);
8605 /* Add new compare/branch insn at end of loop. */
8606 start_sequence ();
8607 emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8608 GET_MODE (reg), 0,
8609 XEXP (jump_label, 0));
8610 tem = get_insns ();
8611 end_sequence ();
8612 emit_jump_insn_before (tem, loop_end);
8614 for (tem = PREV_INSN (loop_end);
8615 tem && GET_CODE (tem) != JUMP_INSN;
8616 tem = PREV_INSN (tem))
8619 if (tem)
8620 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8622 if (nonneg)
8624 if (tem)
8626 /* Increment of LABEL_NUSES done above. */
8627 /* Register is now always nonnegative,
8628 so add REG_NONNEG note to the branch. */
8629 REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, reg,
8630 REG_NOTES (tem));
8632 bl->nonneg = 1;
8635 /* No insn may reference both the reversed and another biv or it
8636 will fail (see comment near the top of the loop reversal
8637 code).
8638 Earlier on, we have verified that the biv has no use except
8639 counting, or it is the only biv in this function.
8640 However, the code that computes no_use_except_counting does
8641 not verify reg notes. It's possible to have an insn that
8642 references another biv, and has a REG_EQUAL note with an
8643 expression based on the reversed biv. To avoid this case,
8644 remove all REG_EQUAL notes based on the reversed biv
8645 here. */
8646 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8647 if (INSN_P (p))
8649 rtx *pnote;
8650 rtx set = single_set (p);
8651 /* If this is a set of a GIV based on the reversed biv, any
8652 REG_EQUAL notes should still be correct. */
8653 if (! set
8654 || GET_CODE (SET_DEST (set)) != REG
8655 || (size_t) REGNO (SET_DEST (set)) >= ivs->n_regs
8656 || REG_IV_TYPE (ivs, REGNO (SET_DEST (set))) != GENERAL_INDUCT
8657 || REG_IV_INFO (ivs, REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8658 for (pnote = &REG_NOTES (p); *pnote;)
8660 if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8661 && reg_mentioned_p (regno_reg_rtx[bl->regno],
8662 XEXP (*pnote, 0)))
8663 *pnote = XEXP (*pnote, 1);
8664 else
8665 pnote = &XEXP (*pnote, 1);
8669 /* Mark that this biv has been reversed. Each giv which depends
8670 on this biv, and which is also live past the end of the loop
8671 will have to be fixed up. */
8673 bl->reversed = 1;
8675 if (loop_dump_stream)
8677 fprintf (loop_dump_stream, "Reversed loop");
8678 if (bl->nonneg)
8679 fprintf (loop_dump_stream, " and added reg_nonneg\n");
8680 else
8681 fprintf (loop_dump_stream, "\n");
8684 return 1;
8689 return 0;
8692 /* Verify whether the biv BL appears to be eliminable,
8693 based on the insns in the loop that refer to it.
8695 If ELIMINATE_P is nonzero, actually do the elimination.
8697 THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8698 determine whether invariant insns should be placed inside or at the
8699 start of the loop. */
8701 static int
8702 maybe_eliminate_biv (loop, bl, eliminate_p, threshold, insn_count)
8703 const struct loop *loop;
8704 struct iv_class *bl;
8705 int eliminate_p;
8706 int threshold, insn_count;
8708 struct loop_ivs *ivs = LOOP_IVS (loop);
8709 rtx reg = bl->biv->dest_reg;
8710 rtx p;
8712 /* Scan all insns in the loop, stopping if we find one that uses the
8713 biv in a way that we cannot eliminate. */
8715 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
8717 enum rtx_code code = GET_CODE (p);
8718 basic_block where_bb = 0;
8719 rtx where_insn = threshold >= insn_count ? 0 : p;
8720 rtx note;
8722 /* If this is a libcall that sets a giv, skip ahead to its end. */
8723 if (GET_RTX_CLASS (code) == 'i')
8725 note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8727 if (note)
8729 rtx last = XEXP (note, 0);
8730 rtx set = single_set (last);
8732 if (set && GET_CODE (SET_DEST (set)) == REG)
8734 unsigned int regno = REGNO (SET_DEST (set));
8736 if (regno < ivs->n_regs
8737 && REG_IV_TYPE (ivs, regno) == GENERAL_INDUCT
8738 && REG_IV_INFO (ivs, regno)->src_reg == bl->biv->src_reg)
8739 p = last;
8744 /* Closely examine the insn if the biv is mentioned. */
8745 if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8746 && reg_mentioned_p (reg, PATTERN (p))
8747 && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
8748 eliminate_p, where_bb, where_insn))
8750 if (loop_dump_stream)
8751 fprintf (loop_dump_stream,
8752 "Cannot eliminate biv %d: biv used in insn %d.\n",
8753 bl->regno, INSN_UID (p));
8754 break;
8757 /* If we are eliminating, kill REG_EQUAL notes mentioning the biv. */
8758 if (eliminate_p
8759 && (note = find_reg_note (p, REG_EQUAL, NULL_RTX)) != NULL_RTX
8760 && reg_mentioned_p (reg, XEXP (note, 0)))
8761 remove_note (p, note);
8764 if (p == loop->end)
8766 if (loop_dump_stream)
8767 fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8768 bl->regno, eliminate_p ? "was" : "can be");
8769 return 1;
8772 return 0;
8775 /* INSN and REFERENCE are instructions in the same insn chain.
8776 Return nonzero if INSN is first. */
8779 loop_insn_first_p (insn, reference)
8780 rtx insn, reference;
8782 rtx p, q;
8784 for (p = insn, q = reference;;)
8786 /* Start with test for not first so that INSN == REFERENCE yields not
8787 first. */
8788 if (q == insn || ! p)
8789 return 0;
8790 if (p == reference || ! q)
8791 return 1;
8793 /* Either of P or Q might be a NOTE. Notes have the same LUID as the
8794 previous insn, hence the <= comparison below does not work if
8795 P is a note. */
8796 if (INSN_UID (p) < max_uid_for_loop
8797 && INSN_UID (q) < max_uid_for_loop
8798 && GET_CODE (p) != NOTE)
8799 return INSN_LUID (p) <= INSN_LUID (q);
8801 if (INSN_UID (p) >= max_uid_for_loop
8802 || GET_CODE (p) == NOTE)
8803 p = NEXT_INSN (p);
8804 if (INSN_UID (q) >= max_uid_for_loop)
8805 q = NEXT_INSN (q);
8809 /* We are trying to eliminate BIV in INSN using GIV. Return nonzero if
8810 the offset that we have to take into account due to auto-increment /
8811 div derivation is zero. */
8812 static int
8813 biv_elimination_giv_has_0_offset (biv, giv, insn)
8814 struct induction *biv, *giv;
8815 rtx insn;
8817 /* If the giv V had the auto-inc address optimization applied
8818 to it, and INSN occurs between the giv insn and the biv
8819 insn, then we'd have to adjust the value used here.
8820 This is rare, so we don't bother to make this possible. */
8821 if (giv->auto_inc_opt
8822 && ((loop_insn_first_p (giv->insn, insn)
8823 && loop_insn_first_p (insn, biv->insn))
8824 || (loop_insn_first_p (biv->insn, insn)
8825 && loop_insn_first_p (insn, giv->insn))))
8826 return 0;
8828 return 1;
8831 /* If BL appears in X (part of the pattern of INSN), see if we can
8832 eliminate its use. If so, return 1. If not, return 0.
8834 If BIV does not appear in X, return 1.
8836 If ELIMINATE_P is nonzero, actually do the elimination.
8837 WHERE_INSN/WHERE_BB indicate where extra insns should be added.
8838 Depending on how many items have been moved out of the loop, it
8839 will either be before INSN (when WHERE_INSN is nonzero) or at the
8840 start of the loop (when WHERE_INSN is zero). */
8842 static int
8843 maybe_eliminate_biv_1 (loop, x, insn, bl, eliminate_p, where_bb, where_insn)
8844 const struct loop *loop;
8845 rtx x, insn;
8846 struct iv_class *bl;
8847 int eliminate_p;
8848 basic_block where_bb;
8849 rtx where_insn;
8851 enum rtx_code code = GET_CODE (x);
8852 rtx reg = bl->biv->dest_reg;
8853 enum machine_mode mode = GET_MODE (reg);
8854 struct induction *v;
8855 rtx arg, tem;
8856 #ifdef HAVE_cc0
8857 rtx new;
8858 #endif
8859 int arg_operand;
8860 const char *fmt;
8861 int i, j;
8863 switch (code)
8865 case REG:
8866 /* If we haven't already been able to do something with this BIV,
8867 we can't eliminate it. */
8868 if (x == reg)
8869 return 0;
8870 return 1;
8872 case SET:
8873 /* If this sets the BIV, it is not a problem. */
8874 if (SET_DEST (x) == reg)
8875 return 1;
8877 /* If this is an insn that defines a giv, it is also ok because
8878 it will go away when the giv is reduced. */
8879 for (v = bl->giv; v; v = v->next_iv)
8880 if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8881 return 1;
8883 #ifdef HAVE_cc0
8884 if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8886 /* Can replace with any giv that was reduced and
8887 that has (MULT_VAL != 0) and (ADD_VAL == 0).
8888 Require a constant for MULT_VAL, so we know it's nonzero.
8889 ??? We disable this optimization to avoid potential
8890 overflows. */
8892 for (v = bl->giv; v; v = v->next_iv)
8893 if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
8894 && v->add_val == const0_rtx
8895 && ! v->ignore && ! v->maybe_dead && v->always_computable
8896 && v->mode == mode
8897 && 0)
8899 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8900 continue;
8902 if (! eliminate_p)
8903 return 1;
8905 /* If the giv has the opposite direction of change,
8906 then reverse the comparison. */
8907 if (INTVAL (v->mult_val) < 0)
8908 new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8909 const0_rtx, v->new_reg);
8910 else
8911 new = v->new_reg;
8913 /* We can probably test that giv's reduced reg. */
8914 if (validate_change (insn, &SET_SRC (x), new, 0))
8915 return 1;
8918 /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8919 replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8920 Require a constant for MULT_VAL, so we know it's nonzero.
8921 ??? Do this only if ADD_VAL is a pointer to avoid a potential
8922 overflow problem. */
8924 for (v = bl->giv; v; v = v->next_iv)
8925 if (GET_CODE (v->mult_val) == CONST_INT
8926 && v->mult_val != const0_rtx
8927 && ! v->ignore && ! v->maybe_dead && v->always_computable
8928 && v->mode == mode
8929 && (GET_CODE (v->add_val) == SYMBOL_REF
8930 || GET_CODE (v->add_val) == LABEL_REF
8931 || GET_CODE (v->add_val) == CONST
8932 || (GET_CODE (v->add_val) == REG
8933 && REG_POINTER (v->add_val))))
8935 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8936 continue;
8938 if (! eliminate_p)
8939 return 1;
8941 /* If the giv has the opposite direction of change,
8942 then reverse the comparison. */
8943 if (INTVAL (v->mult_val) < 0)
8944 new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8945 v->new_reg);
8946 else
8947 new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8948 copy_rtx (v->add_val));
8950 /* Replace biv with the giv's reduced register. */
8951 update_reg_last_use (v->add_val, insn);
8952 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8953 return 1;
8955 /* Insn doesn't support that constant or invariant. Copy it
8956 into a register (it will be a loop invariant.) */
8957 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8959 loop_insn_emit_before (loop, 0, where_insn,
8960 gen_move_insn (tem,
8961 copy_rtx (v->add_val)));
8963 /* Substitute the new register for its invariant value in
8964 the compare expression. */
8965 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8966 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8967 return 1;
8970 #endif
8971 break;
8973 case COMPARE:
8974 case EQ: case NE:
8975 case GT: case GE: case GTU: case GEU:
8976 case LT: case LE: case LTU: case LEU:
8977 /* See if either argument is the biv. */
8978 if (XEXP (x, 0) == reg)
8979 arg = XEXP (x, 1), arg_operand = 1;
8980 else if (XEXP (x, 1) == reg)
8981 arg = XEXP (x, 0), arg_operand = 0;
8982 else
8983 break;
8985 if (CONSTANT_P (arg))
8987 /* First try to replace with any giv that has constant positive
8988 mult_val and constant add_val. We might be able to support
8989 negative mult_val, but it seems complex to do it in general. */
8991 for (v = bl->giv; v; v = v->next_iv)
8992 if (GET_CODE (v->mult_val) == CONST_INT
8993 && INTVAL (v->mult_val) > 0
8994 && (GET_CODE (v->add_val) == SYMBOL_REF
8995 || GET_CODE (v->add_val) == LABEL_REF
8996 || GET_CODE (v->add_val) == CONST
8997 || (GET_CODE (v->add_val) == REG
8998 && REG_POINTER (v->add_val)))
8999 && ! v->ignore && ! v->maybe_dead && v->always_computable
9000 && v->mode == mode)
9002 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9003 continue;
9005 /* Don't eliminate if the linear combination that makes up
9006 the giv overflows when it is applied to ARG. */
9007 if (GET_CODE (arg) == CONST_INT)
9009 rtx add_val;
9011 if (GET_CODE (v->add_val) == CONST_INT)
9012 add_val = v->add_val;
9013 else
9014 add_val = const0_rtx;
9016 if (const_mult_add_overflow_p (arg, v->mult_val,
9017 add_val, mode, 1))
9018 continue;
9021 if (! eliminate_p)
9022 return 1;
9024 /* Replace biv with the giv's reduced reg. */
9025 validate_change (insn, &XEXP (x, 1 - arg_operand), v->new_reg, 1);
9027 /* If all constants are actually constant integers and
9028 the derived constant can be directly placed in the COMPARE,
9029 do so. */
9030 if (GET_CODE (arg) == CONST_INT
9031 && GET_CODE (v->add_val) == CONST_INT)
9033 tem = expand_mult_add (arg, NULL_RTX, v->mult_val,
9034 v->add_val, mode, 1);
9036 else
9038 /* Otherwise, load it into a register. */
9039 tem = gen_reg_rtx (mode);
9040 loop_iv_add_mult_emit_before (loop, arg,
9041 v->mult_val, v->add_val,
9042 tem, where_bb, where_insn);
9045 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9047 if (apply_change_group ())
9048 return 1;
9051 /* Look for giv with positive constant mult_val and nonconst add_val.
9052 Insert insns to calculate new compare value.
9053 ??? Turn this off due to possible overflow. */
9055 for (v = bl->giv; v; v = v->next_iv)
9056 if (GET_CODE (v->mult_val) == CONST_INT
9057 && INTVAL (v->mult_val) > 0
9058 && ! v->ignore && ! v->maybe_dead && v->always_computable
9059 && v->mode == mode
9060 && 0)
9062 rtx tem;
9064 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9065 continue;
9067 if (! eliminate_p)
9068 return 1;
9070 tem = gen_reg_rtx (mode);
9072 /* Replace biv with giv's reduced register. */
9073 validate_change (insn, &XEXP (x, 1 - arg_operand),
9074 v->new_reg, 1);
9076 /* Compute value to compare against. */
9077 loop_iv_add_mult_emit_before (loop, arg,
9078 v->mult_val, v->add_val,
9079 tem, where_bb, where_insn);
9080 /* Use it in this insn. */
9081 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9082 if (apply_change_group ())
9083 return 1;
9086 else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
9088 if (loop_invariant_p (loop, arg) == 1)
9090 /* Look for giv with constant positive mult_val and nonconst
9091 add_val. Insert insns to compute new compare value.
9092 ??? Turn this off due to possible overflow. */
9094 for (v = bl->giv; v; v = v->next_iv)
9095 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
9096 && ! v->ignore && ! v->maybe_dead && v->always_computable
9097 && v->mode == mode
9098 && 0)
9100 rtx tem;
9102 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9103 continue;
9105 if (! eliminate_p)
9106 return 1;
9108 tem = gen_reg_rtx (mode);
9110 /* Replace biv with giv's reduced register. */
9111 validate_change (insn, &XEXP (x, 1 - arg_operand),
9112 v->new_reg, 1);
9114 /* Compute value to compare against. */
9115 loop_iv_add_mult_emit_before (loop, arg,
9116 v->mult_val, v->add_val,
9117 tem, where_bb, where_insn);
9118 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9119 if (apply_change_group ())
9120 return 1;
9124 /* This code has problems. Basically, you can't know when
9125 seeing if we will eliminate BL, whether a particular giv
9126 of ARG will be reduced. If it isn't going to be reduced,
9127 we can't eliminate BL. We can try forcing it to be reduced,
9128 but that can generate poor code.
9130 The problem is that the benefit of reducing TV, below should
9131 be increased if BL can actually be eliminated, but this means
9132 we might have to do a topological sort of the order in which
9133 we try to process biv. It doesn't seem worthwhile to do
9134 this sort of thing now. */
9136 #if 0
9137 /* Otherwise the reg compared with had better be a biv. */
9138 if (GET_CODE (arg) != REG
9139 || REG_IV_TYPE (ivs, REGNO (arg)) != BASIC_INDUCT)
9140 return 0;
9142 /* Look for a pair of givs, one for each biv,
9143 with identical coefficients. */
9144 for (v = bl->giv; v; v = v->next_iv)
9146 struct induction *tv;
9148 if (v->ignore || v->maybe_dead || v->mode != mode)
9149 continue;
9151 for (tv = REG_IV_CLASS (ivs, REGNO (arg))->giv; tv;
9152 tv = tv->next_iv)
9153 if (! tv->ignore && ! tv->maybe_dead
9154 && rtx_equal_p (tv->mult_val, v->mult_val)
9155 && rtx_equal_p (tv->add_val, v->add_val)
9156 && tv->mode == mode)
9158 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9159 continue;
9161 if (! eliminate_p)
9162 return 1;
9164 /* Replace biv with its giv's reduced reg. */
9165 XEXP (x, 1 - arg_operand) = v->new_reg;
9166 /* Replace other operand with the other giv's
9167 reduced reg. */
9168 XEXP (x, arg_operand) = tv->new_reg;
9169 return 1;
9172 #endif
9175 /* If we get here, the biv can't be eliminated. */
9176 return 0;
9178 case MEM:
9179 /* If this address is a DEST_ADDR giv, it doesn't matter if the
9180 biv is used in it, since it will be replaced. */
9181 for (v = bl->giv; v; v = v->next_iv)
9182 if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
9183 return 1;
9184 break;
9186 default:
9187 break;
9190 /* See if any subexpression fails elimination. */
9191 fmt = GET_RTX_FORMAT (code);
9192 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
9194 switch (fmt[i])
9196 case 'e':
9197 if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl,
9198 eliminate_p, where_bb, where_insn))
9199 return 0;
9200 break;
9202 case 'E':
9203 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9204 if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
9205 eliminate_p, where_bb, where_insn))
9206 return 0;
9207 break;
9211 return 1;
9214 /* Return nonzero if the last use of REG
9215 is in an insn following INSN in the same basic block. */
9217 static int
9218 last_use_this_basic_block (reg, insn)
9219 rtx reg;
9220 rtx insn;
9222 rtx n;
9223 for (n = insn;
9224 n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
9225 n = NEXT_INSN (n))
9227 if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
9228 return 1;
9230 return 0;
9233 /* Called via `note_stores' to record the initial value of a biv. Here we
9234 just record the location of the set and process it later. */
9236 static void
9237 record_initial (dest, set, data)
9238 rtx dest;
9239 rtx set;
9240 void *data ATTRIBUTE_UNUSED;
9242 struct loop_ivs *ivs = (struct loop_ivs *) data;
9243 struct iv_class *bl;
9245 if (GET_CODE (dest) != REG
9246 || REGNO (dest) >= ivs->n_regs
9247 || REG_IV_TYPE (ivs, REGNO (dest)) != BASIC_INDUCT)
9248 return;
9250 bl = REG_IV_CLASS (ivs, REGNO (dest));
9252 /* If this is the first set found, record it. */
9253 if (bl->init_insn == 0)
9255 bl->init_insn = note_insn;
9256 bl->init_set = set;
9260 /* If any of the registers in X are "old" and currently have a last use earlier
9261 than INSN, update them to have a last use of INSN. Their actual last use
9262 will be the previous insn but it will not have a valid uid_luid so we can't
9263 use it. X must be a source expression only. */
9265 static void
9266 update_reg_last_use (x, insn)
9267 rtx x;
9268 rtx insn;
9270 /* Check for the case where INSN does not have a valid luid. In this case,
9271 there is no need to modify the regno_last_uid, as this can only happen
9272 when code is inserted after the loop_end to set a pseudo's final value,
9273 and hence this insn will never be the last use of x.
9274 ???? This comment is not correct. See for example loop_givs_reduce.
9275 This may insert an insn before another new insn. */
9276 if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
9277 && INSN_UID (insn) < max_uid_for_loop
9278 && REGNO_LAST_LUID (REGNO (x)) < INSN_LUID (insn))
9280 REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
9282 else
9284 int i, j;
9285 const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
9286 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9288 if (fmt[i] == 'e')
9289 update_reg_last_use (XEXP (x, i), insn);
9290 else if (fmt[i] == 'E')
9291 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9292 update_reg_last_use (XVECEXP (x, i, j), insn);
9297 /* Given an insn INSN and condition COND, return the condition in a
9298 canonical form to simplify testing by callers. Specifically:
9300 (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
9301 (2) Both operands will be machine operands; (cc0) will have been replaced.
9302 (3) If an operand is a constant, it will be the second operand.
9303 (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
9304 for GE, GEU, and LEU.
9306 If the condition cannot be understood, or is an inequality floating-point
9307 comparison which needs to be reversed, 0 will be returned.
9309 If REVERSE is nonzero, then reverse the condition prior to canonizing it.
9311 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9312 insn used in locating the condition was found. If a replacement test
9313 of the condition is desired, it should be placed in front of that
9314 insn and we will be sure that the inputs are still valid.
9316 If WANT_REG is nonzero, we wish the condition to be relative to that
9317 register, if possible. Therefore, do not canonicalize the condition
9318 further. */
9321 canonicalize_condition (insn, cond, reverse, earliest, want_reg)
9322 rtx insn;
9323 rtx cond;
9324 int reverse;
9325 rtx *earliest;
9326 rtx want_reg;
9328 enum rtx_code code;
9329 rtx prev = insn;
9330 rtx set;
9331 rtx tem;
9332 rtx op0, op1;
9333 int reverse_code = 0;
9334 enum machine_mode mode;
9336 code = GET_CODE (cond);
9337 mode = GET_MODE (cond);
9338 op0 = XEXP (cond, 0);
9339 op1 = XEXP (cond, 1);
9341 if (reverse)
9342 code = reversed_comparison_code (cond, insn);
9343 if (code == UNKNOWN)
9344 return 0;
9346 if (earliest)
9347 *earliest = insn;
9349 /* If we are comparing a register with zero, see if the register is set
9350 in the previous insn to a COMPARE or a comparison operation. Perform
9351 the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
9352 in cse.c */
9354 while (GET_RTX_CLASS (code) == '<'
9355 && op1 == CONST0_RTX (GET_MODE (op0))
9356 && op0 != want_reg)
9358 /* Set nonzero when we find something of interest. */
9359 rtx x = 0;
9361 #ifdef HAVE_cc0
9362 /* If comparison with cc0, import actual comparison from compare
9363 insn. */
9364 if (op0 == cc0_rtx)
9366 if ((prev = prev_nonnote_insn (prev)) == 0
9367 || GET_CODE (prev) != INSN
9368 || (set = single_set (prev)) == 0
9369 || SET_DEST (set) != cc0_rtx)
9370 return 0;
9372 op0 = SET_SRC (set);
9373 op1 = CONST0_RTX (GET_MODE (op0));
9374 if (earliest)
9375 *earliest = prev;
9377 #endif
9379 /* If this is a COMPARE, pick up the two things being compared. */
9380 if (GET_CODE (op0) == COMPARE)
9382 op1 = XEXP (op0, 1);
9383 op0 = XEXP (op0, 0);
9384 continue;
9386 else if (GET_CODE (op0) != REG)
9387 break;
9389 /* Go back to the previous insn. Stop if it is not an INSN. We also
9390 stop if it isn't a single set or if it has a REG_INC note because
9391 we don't want to bother dealing with it. */
9393 if ((prev = prev_nonnote_insn (prev)) == 0
9394 || GET_CODE (prev) != INSN
9395 || FIND_REG_INC_NOTE (prev, NULL_RTX))
9396 break;
9398 set = set_of (op0, prev);
9400 if (set
9401 && (GET_CODE (set) != SET
9402 || !rtx_equal_p (SET_DEST (set), op0)))
9403 break;
9405 /* If this is setting OP0, get what it sets it to if it looks
9406 relevant. */
9407 if (set)
9409 enum machine_mode inner_mode = GET_MODE (SET_DEST (set));
9410 #ifdef FLOAT_STORE_FLAG_VALUE
9411 REAL_VALUE_TYPE fsfv;
9412 #endif
9414 /* ??? We may not combine comparisons done in a CCmode with
9415 comparisons not done in a CCmode. This is to aid targets
9416 like Alpha that have an IEEE compliant EQ instruction, and
9417 a non-IEEE compliant BEQ instruction. The use of CCmode is
9418 actually artificial, simply to prevent the combination, but
9419 should not affect other platforms.
9421 However, we must allow VOIDmode comparisons to match either
9422 CCmode or non-CCmode comparison, because some ports have
9423 modeless comparisons inside branch patterns.
9425 ??? This mode check should perhaps look more like the mode check
9426 in simplify_comparison in combine. */
9428 if ((GET_CODE (SET_SRC (set)) == COMPARE
9429 || (((code == NE
9430 || (code == LT
9431 && GET_MODE_CLASS (inner_mode) == MODE_INT
9432 && (GET_MODE_BITSIZE (inner_mode)
9433 <= HOST_BITS_PER_WIDE_INT)
9434 && (STORE_FLAG_VALUE
9435 & ((HOST_WIDE_INT) 1
9436 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9437 #ifdef FLOAT_STORE_FLAG_VALUE
9438 || (code == LT
9439 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9440 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9441 REAL_VALUE_NEGATIVE (fsfv)))
9442 #endif
9444 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
9445 && (((GET_MODE_CLASS (mode) == MODE_CC)
9446 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9447 || mode == VOIDmode || inner_mode == VOIDmode))
9448 x = SET_SRC (set);
9449 else if (((code == EQ
9450 || (code == GE
9451 && (GET_MODE_BITSIZE (inner_mode)
9452 <= HOST_BITS_PER_WIDE_INT)
9453 && GET_MODE_CLASS (inner_mode) == MODE_INT
9454 && (STORE_FLAG_VALUE
9455 & ((HOST_WIDE_INT) 1
9456 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9457 #ifdef FLOAT_STORE_FLAG_VALUE
9458 || (code == GE
9459 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9460 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9461 REAL_VALUE_NEGATIVE (fsfv)))
9462 #endif
9464 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
9465 && (((GET_MODE_CLASS (mode) == MODE_CC)
9466 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9467 || mode == VOIDmode || inner_mode == VOIDmode))
9470 reverse_code = 1;
9471 x = SET_SRC (set);
9473 else
9474 break;
9477 else if (reg_set_p (op0, prev))
9478 /* If this sets OP0, but not directly, we have to give up. */
9479 break;
9481 if (x)
9483 if (GET_RTX_CLASS (GET_CODE (x)) == '<')
9484 code = GET_CODE (x);
9485 if (reverse_code)
9487 code = reversed_comparison_code (x, prev);
9488 if (code == UNKNOWN)
9489 return 0;
9490 reverse_code = 0;
9493 op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9494 if (earliest)
9495 *earliest = prev;
9499 /* If constant is first, put it last. */
9500 if (CONSTANT_P (op0))
9501 code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9503 /* If OP0 is the result of a comparison, we weren't able to find what
9504 was really being compared, so fail. */
9505 if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9506 return 0;
9508 /* Canonicalize any ordered comparison with integers involving equality
9509 if we can do computations in the relevant mode and we do not
9510 overflow. */
9512 if (GET_CODE (op1) == CONST_INT
9513 && GET_MODE (op0) != VOIDmode
9514 && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9516 HOST_WIDE_INT const_val = INTVAL (op1);
9517 unsigned HOST_WIDE_INT uconst_val = const_val;
9518 unsigned HOST_WIDE_INT max_val
9519 = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9521 switch (code)
9523 case LE:
9524 if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9525 code = LT, op1 = gen_int_mode (const_val + 1, GET_MODE (op0));
9526 break;
9528 /* When cross-compiling, const_val might be sign-extended from
9529 BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9530 case GE:
9531 if ((HOST_WIDE_INT) (const_val & max_val)
9532 != (((HOST_WIDE_INT) 1
9533 << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9534 code = GT, op1 = gen_int_mode (const_val - 1, GET_MODE (op0));
9535 break;
9537 case LEU:
9538 if (uconst_val < max_val)
9539 code = LTU, op1 = gen_int_mode (uconst_val + 1, GET_MODE (op0));
9540 break;
9542 case GEU:
9543 if (uconst_val != 0)
9544 code = GTU, op1 = gen_int_mode (uconst_val - 1, GET_MODE (op0));
9545 break;
9547 default:
9548 break;
9552 /* Never return CC0; return zero instead. */
9553 if (CC0_P (op0))
9554 return 0;
9556 return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9559 /* Given a jump insn JUMP, return the condition that will cause it to branch
9560 to its JUMP_LABEL. If the condition cannot be understood, or is an
9561 inequality floating-point comparison which needs to be reversed, 0 will
9562 be returned.
9564 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9565 insn used in locating the condition was found. If a replacement test
9566 of the condition is desired, it should be placed in front of that
9567 insn and we will be sure that the inputs are still valid. */
9570 get_condition (jump, earliest)
9571 rtx jump;
9572 rtx *earliest;
9574 rtx cond;
9575 int reverse;
9576 rtx set;
9578 /* If this is not a standard conditional jump, we can't parse it. */
9579 if (GET_CODE (jump) != JUMP_INSN
9580 || ! any_condjump_p (jump))
9581 return 0;
9582 set = pc_set (jump);
9584 cond = XEXP (SET_SRC (set), 0);
9586 /* If this branches to JUMP_LABEL when the condition is false, reverse
9587 the condition. */
9588 reverse
9589 = GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
9590 && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (jump);
9592 return canonicalize_condition (jump, cond, reverse, earliest, NULL_RTX);
9595 /* Similar to above routine, except that we also put an invariant last
9596 unless both operands are invariants. */
9599 get_condition_for_loop (loop, x)
9600 const struct loop *loop;
9601 rtx x;
9603 rtx comparison = get_condition (x, (rtx*) 0);
9605 if (comparison == 0
9606 || ! loop_invariant_p (loop, XEXP (comparison, 0))
9607 || loop_invariant_p (loop, XEXP (comparison, 1)))
9608 return comparison;
9610 return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9611 XEXP (comparison, 1), XEXP (comparison, 0));
9614 /* Scan the function and determine whether it has indirect (computed) jumps.
9616 This is taken mostly from flow.c; similar code exists elsewhere
9617 in the compiler. It may be useful to put this into rtlanal.c. */
9618 static int
9619 indirect_jump_in_function_p (start)
9620 rtx start;
9622 rtx insn;
9624 for (insn = start; insn; insn = NEXT_INSN (insn))
9625 if (computed_jump_p (insn))
9626 return 1;
9628 return 0;
9631 /* Add MEM to the LOOP_MEMS array, if appropriate. See the
9632 documentation for LOOP_MEMS for the definition of `appropriate'.
9633 This function is called from prescan_loop via for_each_rtx. */
9635 static int
9636 insert_loop_mem (mem, data)
9637 rtx *mem;
9638 void *data ATTRIBUTE_UNUSED;
9640 struct loop_info *loop_info = data;
9641 int i;
9642 rtx m = *mem;
9644 if (m == NULL_RTX)
9645 return 0;
9647 switch (GET_CODE (m))
9649 case MEM:
9650 break;
9652 case CLOBBER:
9653 /* We're not interested in MEMs that are only clobbered. */
9654 return -1;
9656 case CONST_DOUBLE:
9657 /* We're not interested in the MEM associated with a
9658 CONST_DOUBLE, so there's no need to traverse into this. */
9659 return -1;
9661 case EXPR_LIST:
9662 /* We're not interested in any MEMs that only appear in notes. */
9663 return -1;
9665 default:
9666 /* This is not a MEM. */
9667 return 0;
9670 /* See if we've already seen this MEM. */
9671 for (i = 0; i < loop_info->mems_idx; ++i)
9672 if (rtx_equal_p (m, loop_info->mems[i].mem))
9674 if (GET_MODE (m) != GET_MODE (loop_info->mems[i].mem))
9675 /* The modes of the two memory accesses are different. If
9676 this happens, something tricky is going on, and we just
9677 don't optimize accesses to this MEM. */
9678 loop_info->mems[i].optimize = 0;
9680 return 0;
9683 /* Resize the array, if necessary. */
9684 if (loop_info->mems_idx == loop_info->mems_allocated)
9686 if (loop_info->mems_allocated != 0)
9687 loop_info->mems_allocated *= 2;
9688 else
9689 loop_info->mems_allocated = 32;
9691 loop_info->mems = (loop_mem_info *)
9692 xrealloc (loop_info->mems,
9693 loop_info->mems_allocated * sizeof (loop_mem_info));
9696 /* Actually insert the MEM. */
9697 loop_info->mems[loop_info->mems_idx].mem = m;
9698 /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9699 because we can't put it in a register. We still store it in the
9700 table, though, so that if we see the same address later, but in a
9701 non-BLK mode, we'll not think we can optimize it at that point. */
9702 loop_info->mems[loop_info->mems_idx].optimize = (GET_MODE (m) != BLKmode);
9703 loop_info->mems[loop_info->mems_idx].reg = NULL_RTX;
9704 ++loop_info->mems_idx;
9706 return 0;
9710 /* Allocate REGS->ARRAY or reallocate it if it is too small.
9712 Increment REGS->ARRAY[I].SET_IN_LOOP at the index I of each
9713 register that is modified by an insn between FROM and TO. If the
9714 value of an element of REGS->array[I].SET_IN_LOOP becomes 127 or
9715 more, stop incrementing it, to avoid overflow.
9717 Store in REGS->ARRAY[I].SINGLE_USAGE the single insn in which
9718 register I is used, if it is only used once. Otherwise, it is set
9719 to 0 (for no uses) or const0_rtx for more than one use. This
9720 parameter may be zero, in which case this processing is not done.
9722 Set REGS->ARRAY[I].MAY_NOT_OPTIMIZE nonzero if we should not
9723 optimize register I. */
9725 static void
9726 loop_regs_scan (loop, extra_size)
9727 const struct loop *loop;
9728 int extra_size;
9730 struct loop_regs *regs = LOOP_REGS (loop);
9731 int old_nregs;
9732 /* last_set[n] is nonzero iff reg n has been set in the current
9733 basic block. In that case, it is the insn that last set reg n. */
9734 rtx *last_set;
9735 rtx insn;
9736 int i;
9738 old_nregs = regs->num;
9739 regs->num = max_reg_num ();
9741 /* Grow the regs array if not allocated or too small. */
9742 if (regs->num >= regs->size)
9744 regs->size = regs->num + extra_size;
9746 regs->array = (struct loop_reg *)
9747 xrealloc (regs->array, regs->size * sizeof (*regs->array));
9749 /* Zero the new elements. */
9750 memset (regs->array + old_nregs, 0,
9751 (regs->size - old_nregs) * sizeof (*regs->array));
9754 /* Clear previously scanned fields but do not clear n_times_set. */
9755 for (i = 0; i < old_nregs; i++)
9757 regs->array[i].set_in_loop = 0;
9758 regs->array[i].may_not_optimize = 0;
9759 regs->array[i].single_usage = NULL_RTX;
9762 last_set = (rtx *) xcalloc (regs->num, sizeof (rtx));
9764 /* Scan the loop, recording register usage. */
9765 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9766 insn = NEXT_INSN (insn))
9768 if (INSN_P (insn))
9770 /* Record registers that have exactly one use. */
9771 find_single_use_in_loop (regs, insn, PATTERN (insn));
9773 /* Include uses in REG_EQUAL notes. */
9774 if (REG_NOTES (insn))
9775 find_single_use_in_loop (regs, insn, REG_NOTES (insn));
9777 if (GET_CODE (PATTERN (insn)) == SET
9778 || GET_CODE (PATTERN (insn)) == CLOBBER)
9779 count_one_set (regs, insn, PATTERN (insn), last_set);
9780 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
9782 int i;
9783 for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
9784 count_one_set (regs, insn, XVECEXP (PATTERN (insn), 0, i),
9785 last_set);
9789 if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
9790 memset (last_set, 0, regs->num * sizeof (rtx));
9792 /* Invalidate all registers used for function argument passing.
9793 We check rtx_varies_p for the same reason as below, to allow
9794 optimizing PIC calculations. */
9795 if (GET_CODE (insn) == CALL_INSN)
9797 rtx link;
9798 for (link = CALL_INSN_FUNCTION_USAGE (insn);
9799 link;
9800 link = XEXP (link, 1))
9802 rtx op, reg;
9804 if (GET_CODE (op = XEXP (link, 0)) == USE
9805 && GET_CODE (reg = XEXP (op, 0)) == REG
9806 && rtx_varies_p (reg, 1))
9807 regs->array[REGNO (reg)].may_not_optimize = 1;
9812 /* Invalidate all hard registers clobbered by calls. With one exception:
9813 a call-clobbered PIC register is still function-invariant for our
9814 purposes, since we can hoist any PIC calculations out of the loop.
9815 Thus the call to rtx_varies_p. */
9816 if (LOOP_INFO (loop)->has_call)
9817 for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9818 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i)
9819 && rtx_varies_p (regno_reg_rtx[i], 1))
9821 regs->array[i].may_not_optimize = 1;
9822 regs->array[i].set_in_loop = 1;
9825 #ifdef AVOID_CCMODE_COPIES
9826 /* Don't try to move insns which set CC registers if we should not
9827 create CCmode register copies. */
9828 for (i = regs->num - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9829 if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9830 regs->array[i].may_not_optimize = 1;
9831 #endif
9833 /* Set regs->array[I].n_times_set for the new registers. */
9834 for (i = old_nregs; i < regs->num; i++)
9835 regs->array[i].n_times_set = regs->array[i].set_in_loop;
9837 free (last_set);
9840 /* Returns the number of real INSNs in the LOOP. */
9842 static int
9843 count_insns_in_loop (loop)
9844 const struct loop *loop;
9846 int count = 0;
9847 rtx insn;
9849 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9850 insn = NEXT_INSN (insn))
9851 if (INSN_P (insn))
9852 ++count;
9854 return count;
9857 /* Move MEMs into registers for the duration of the loop. */
9859 static void
9860 load_mems (loop)
9861 const struct loop *loop;
9863 struct loop_info *loop_info = LOOP_INFO (loop);
9864 struct loop_regs *regs = LOOP_REGS (loop);
9865 int maybe_never = 0;
9866 int i;
9867 rtx p, prev_ebb_head;
9868 rtx label = NULL_RTX;
9869 rtx end_label;
9870 /* Nonzero if the next instruction may never be executed. */
9871 int next_maybe_never = 0;
9872 unsigned int last_max_reg = max_reg_num ();
9874 if (loop_info->mems_idx == 0)
9875 return;
9877 /* We cannot use next_label here because it skips over normal insns. */
9878 end_label = next_nonnote_insn (loop->end);
9879 if (end_label && GET_CODE (end_label) != CODE_LABEL)
9880 end_label = NULL_RTX;
9882 /* Check to see if it's possible that some instructions in the loop are
9883 never executed. Also check if there is a goto out of the loop other
9884 than right after the end of the loop. */
9885 for (p = next_insn_in_loop (loop, loop->scan_start);
9886 p != NULL_RTX;
9887 p = next_insn_in_loop (loop, p))
9889 if (GET_CODE (p) == CODE_LABEL)
9890 maybe_never = 1;
9891 else if (GET_CODE (p) == JUMP_INSN
9892 /* If we enter the loop in the middle, and scan
9893 around to the beginning, don't set maybe_never
9894 for that. This must be an unconditional jump,
9895 otherwise the code at the top of the loop might
9896 never be executed. Unconditional jumps are
9897 followed a by barrier then loop end. */
9898 && ! (GET_CODE (p) == JUMP_INSN
9899 && JUMP_LABEL (p) == loop->top
9900 && NEXT_INSN (NEXT_INSN (p)) == loop->end
9901 && any_uncondjump_p (p)))
9903 /* If this is a jump outside of the loop but not right
9904 after the end of the loop, we would have to emit new fixup
9905 sequences for each such label. */
9906 if (/* If we can't tell where control might go when this
9907 JUMP_INSN is executed, we must be conservative. */
9908 !JUMP_LABEL (p)
9909 || (JUMP_LABEL (p) != end_label
9910 && (INSN_UID (JUMP_LABEL (p)) >= max_uid_for_loop
9911 || INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop->start)
9912 || INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop->end))))
9913 return;
9915 if (!any_condjump_p (p))
9916 /* Something complicated. */
9917 maybe_never = 1;
9918 else
9919 /* If there are any more instructions in the loop, they
9920 might not be reached. */
9921 next_maybe_never = 1;
9923 else if (next_maybe_never)
9924 maybe_never = 1;
9927 /* Find start of the extended basic block that enters the loop. */
9928 for (p = loop->start;
9929 PREV_INSN (p) && GET_CODE (p) != CODE_LABEL;
9930 p = PREV_INSN (p))
9932 prev_ebb_head = p;
9934 cselib_init ();
9936 /* Build table of mems that get set to constant values before the
9937 loop. */
9938 for (; p != loop->start; p = NEXT_INSN (p))
9939 cselib_process_insn (p);
9941 /* Actually move the MEMs. */
9942 for (i = 0; i < loop_info->mems_idx; ++i)
9944 regset_head load_copies;
9945 regset_head store_copies;
9946 int written = 0;
9947 rtx reg;
9948 rtx mem = loop_info->mems[i].mem;
9949 rtx mem_list_entry;
9951 if (MEM_VOLATILE_P (mem)
9952 || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
9953 /* There's no telling whether or not MEM is modified. */
9954 loop_info->mems[i].optimize = 0;
9956 /* Go through the MEMs written to in the loop to see if this
9957 one is aliased by one of them. */
9958 mem_list_entry = loop_info->store_mems;
9959 while (mem_list_entry)
9961 if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9962 written = 1;
9963 else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9964 mem, rtx_varies_p))
9966 /* MEM is indeed aliased by this store. */
9967 loop_info->mems[i].optimize = 0;
9968 break;
9970 mem_list_entry = XEXP (mem_list_entry, 1);
9973 if (flag_float_store && written
9974 && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
9975 loop_info->mems[i].optimize = 0;
9977 /* If this MEM is written to, we must be sure that there
9978 are no reads from another MEM that aliases this one. */
9979 if (loop_info->mems[i].optimize && written)
9981 int j;
9983 for (j = 0; j < loop_info->mems_idx; ++j)
9985 if (j == i)
9986 continue;
9987 else if (true_dependence (mem,
9988 VOIDmode,
9989 loop_info->mems[j].mem,
9990 rtx_varies_p))
9992 /* It's not safe to hoist loop_info->mems[i] out of
9993 the loop because writes to it might not be
9994 seen by reads from loop_info->mems[j]. */
9995 loop_info->mems[i].optimize = 0;
9996 break;
10001 if (maybe_never && may_trap_p (mem))
10002 /* We can't access the MEM outside the loop; it might
10003 cause a trap that wouldn't have happened otherwise. */
10004 loop_info->mems[i].optimize = 0;
10006 if (!loop_info->mems[i].optimize)
10007 /* We thought we were going to lift this MEM out of the
10008 loop, but later discovered that we could not. */
10009 continue;
10011 INIT_REG_SET (&load_copies);
10012 INIT_REG_SET (&store_copies);
10014 /* Allocate a pseudo for this MEM. We set REG_USERVAR_P in
10015 order to keep scan_loop from moving stores to this MEM
10016 out of the loop just because this REG is neither a
10017 user-variable nor used in the loop test. */
10018 reg = gen_reg_rtx (GET_MODE (mem));
10019 REG_USERVAR_P (reg) = 1;
10020 loop_info->mems[i].reg = reg;
10022 /* Now, replace all references to the MEM with the
10023 corresponding pseudos. */
10024 maybe_never = 0;
10025 for (p = next_insn_in_loop (loop, loop->scan_start);
10026 p != NULL_RTX;
10027 p = next_insn_in_loop (loop, p))
10029 if (INSN_P (p))
10031 rtx set;
10033 set = single_set (p);
10035 /* See if this copies the mem into a register that isn't
10036 modified afterwards. We'll try to do copy propagation
10037 a little further on. */
10038 if (set
10039 /* @@@ This test is _way_ too conservative. */
10040 && ! maybe_never
10041 && GET_CODE (SET_DEST (set)) == REG
10042 && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
10043 && REGNO (SET_DEST (set)) < last_max_reg
10044 && regs->array[REGNO (SET_DEST (set))].n_times_set == 1
10045 && rtx_equal_p (SET_SRC (set), mem))
10046 SET_REGNO_REG_SET (&load_copies, REGNO (SET_DEST (set)));
10048 /* See if this copies the mem from a register that isn't
10049 modified afterwards. We'll try to remove the
10050 redundant copy later on by doing a little register
10051 renaming and copy propagation. This will help
10052 to untangle things for the BIV detection code. */
10053 if (set
10054 && ! maybe_never
10055 && GET_CODE (SET_SRC (set)) == REG
10056 && REGNO (SET_SRC (set)) >= FIRST_PSEUDO_REGISTER
10057 && REGNO (SET_SRC (set)) < last_max_reg
10058 && regs->array[REGNO (SET_SRC (set))].n_times_set == 1
10059 && rtx_equal_p (SET_DEST (set), mem))
10060 SET_REGNO_REG_SET (&store_copies, REGNO (SET_SRC (set)));
10062 /* If this is a call which uses / clobbers this memory
10063 location, we must not change the interface here. */
10064 if (GET_CODE (p) == CALL_INSN
10065 && reg_mentioned_p (loop_info->mems[i].mem,
10066 CALL_INSN_FUNCTION_USAGE (p)))
10068 cancel_changes (0);
10069 loop_info->mems[i].optimize = 0;
10070 break;
10072 else
10073 /* Replace the memory reference with the shadow register. */
10074 replace_loop_mems (p, loop_info->mems[i].mem,
10075 loop_info->mems[i].reg, written);
10078 if (GET_CODE (p) == CODE_LABEL
10079 || GET_CODE (p) == JUMP_INSN)
10080 maybe_never = 1;
10083 if (! loop_info->mems[i].optimize)
10084 ; /* We found we couldn't do the replacement, so do nothing. */
10085 else if (! apply_change_group ())
10086 /* We couldn't replace all occurrences of the MEM. */
10087 loop_info->mems[i].optimize = 0;
10088 else
10090 /* Load the memory immediately before LOOP->START, which is
10091 the NOTE_LOOP_BEG. */
10092 cselib_val *e = cselib_lookup (mem, VOIDmode, 0);
10093 rtx set;
10094 rtx best = mem;
10095 int j;
10096 struct elt_loc_list *const_equiv = 0;
10098 if (e)
10100 struct elt_loc_list *equiv;
10101 struct elt_loc_list *best_equiv = 0;
10102 for (equiv = e->locs; equiv; equiv = equiv->next)
10104 if (CONSTANT_P (equiv->loc))
10105 const_equiv = equiv;
10106 else if (GET_CODE (equiv->loc) == REG
10107 /* Extending hard register lifetimes causes crash
10108 on SRC targets. Doing so on non-SRC is
10109 probably also not good idea, since we most
10110 probably have pseudoregister equivalence as
10111 well. */
10112 && REGNO (equiv->loc) >= FIRST_PSEUDO_REGISTER)
10113 best_equiv = equiv;
10115 /* Use the constant equivalence if that is cheap enough. */
10116 if (! best_equiv)
10117 best_equiv = const_equiv;
10118 else if (const_equiv
10119 && (rtx_cost (const_equiv->loc, SET)
10120 <= rtx_cost (best_equiv->loc, SET)))
10122 best_equiv = const_equiv;
10123 const_equiv = 0;
10126 /* If best_equiv is nonzero, we know that MEM is set to a
10127 constant or register before the loop. We will use this
10128 knowledge to initialize the shadow register with that
10129 constant or reg rather than by loading from MEM. */
10130 if (best_equiv)
10131 best = copy_rtx (best_equiv->loc);
10134 set = gen_move_insn (reg, best);
10135 set = loop_insn_hoist (loop, set);
10136 if (REG_P (best))
10138 for (p = prev_ebb_head; p != loop->start; p = NEXT_INSN (p))
10139 if (REGNO_LAST_UID (REGNO (best)) == INSN_UID (p))
10141 REGNO_LAST_UID (REGNO (best)) = INSN_UID (set);
10142 break;
10146 if (const_equiv)
10147 set_unique_reg_note (set, REG_EQUAL, copy_rtx (const_equiv->loc));
10149 if (written)
10151 if (label == NULL_RTX)
10153 label = gen_label_rtx ();
10154 emit_label_after (label, loop->end);
10157 /* Store the memory immediately after END, which is
10158 the NOTE_LOOP_END. */
10159 set = gen_move_insn (copy_rtx (mem), reg);
10160 loop_insn_emit_after (loop, 0, label, set);
10163 if (loop_dump_stream)
10165 fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
10166 REGNO (reg), (written ? "r/w" : "r/o"));
10167 print_rtl (loop_dump_stream, mem);
10168 fputc ('\n', loop_dump_stream);
10171 /* Attempt a bit of copy propagation. This helps untangle the
10172 data flow, and enables {basic,general}_induction_var to find
10173 more bivs/givs. */
10174 EXECUTE_IF_SET_IN_REG_SET
10175 (&load_copies, FIRST_PSEUDO_REGISTER, j,
10177 try_copy_prop (loop, reg, j);
10179 CLEAR_REG_SET (&load_copies);
10181 EXECUTE_IF_SET_IN_REG_SET
10182 (&store_copies, FIRST_PSEUDO_REGISTER, j,
10184 try_swap_copy_prop (loop, reg, j);
10186 CLEAR_REG_SET (&store_copies);
10190 if (label != NULL_RTX && end_label != NULL_RTX)
10192 /* Now, we need to replace all references to the previous exit
10193 label with the new one. */
10194 replace_label_data rr;
10195 rr.r1 = end_label;
10196 rr.r2 = label;
10197 rr.update_label_nuses = true;
10199 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
10201 for_each_rtx (&p, replace_label, &rr);
10205 cselib_finish ();
10208 /* For communication between note_reg_stored and its caller. */
10209 struct note_reg_stored_arg
10211 int set_seen;
10212 rtx reg;
10215 /* Called via note_stores, record in SET_SEEN whether X, which is written,
10216 is equal to ARG. */
10217 static void
10218 note_reg_stored (x, setter, arg)
10219 rtx x, setter ATTRIBUTE_UNUSED;
10220 void *arg;
10222 struct note_reg_stored_arg *t = (struct note_reg_stored_arg *) arg;
10223 if (t->reg == x)
10224 t->set_seen = 1;
10227 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
10228 There must be exactly one insn that sets this pseudo; it will be
10229 deleted if all replacements succeed and we can prove that the register
10230 is not used after the loop. */
10232 static void
10233 try_copy_prop (loop, replacement, regno)
10234 const struct loop *loop;
10235 rtx replacement;
10236 unsigned int regno;
10238 /* This is the reg that we are copying from. */
10239 rtx reg_rtx = regno_reg_rtx[regno];
10240 rtx init_insn = 0;
10241 rtx insn;
10242 /* These help keep track of whether we replaced all uses of the reg. */
10243 int replaced_last = 0;
10244 int store_is_first = 0;
10246 for (insn = next_insn_in_loop (loop, loop->scan_start);
10247 insn != NULL_RTX;
10248 insn = next_insn_in_loop (loop, insn))
10250 rtx set;
10252 /* Only substitute within one extended basic block from the initializing
10253 insn. */
10254 if (GET_CODE (insn) == CODE_LABEL && init_insn)
10255 break;
10257 if (! INSN_P (insn))
10258 continue;
10260 /* Is this the initializing insn? */
10261 set = single_set (insn);
10262 if (set
10263 && GET_CODE (SET_DEST (set)) == REG
10264 && REGNO (SET_DEST (set)) == regno)
10266 if (init_insn)
10267 abort ();
10269 init_insn = insn;
10270 if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
10271 store_is_first = 1;
10274 /* Only substitute after seeing the initializing insn. */
10275 if (init_insn && insn != init_insn)
10277 struct note_reg_stored_arg arg;
10279 replace_loop_regs (insn, reg_rtx, replacement);
10280 if (REGNO_LAST_UID (regno) == INSN_UID (insn))
10281 replaced_last = 1;
10283 /* Stop replacing when REPLACEMENT is modified. */
10284 arg.reg = replacement;
10285 arg.set_seen = 0;
10286 note_stores (PATTERN (insn), note_reg_stored, &arg);
10287 if (arg.set_seen)
10289 rtx note = find_reg_note (insn, REG_EQUAL, NULL);
10291 /* It is possible that we've turned previously valid REG_EQUAL to
10292 invalid, as we change the REGNO to REPLACEMENT and unlike REGNO,
10293 REPLACEMENT is modified, we get different meaning. */
10294 if (note && reg_mentioned_p (replacement, XEXP (note, 0)))
10295 remove_note (insn, note);
10296 break;
10300 if (! init_insn)
10301 abort ();
10302 if (apply_change_group ())
10304 if (loop_dump_stream)
10305 fprintf (loop_dump_stream, " Replaced reg %d", regno);
10306 if (store_is_first && replaced_last)
10308 rtx first;
10309 rtx retval_note;
10311 /* Assume we're just deleting INIT_INSN. */
10312 first = init_insn;
10313 /* Look for REG_RETVAL note. If we're deleting the end of
10314 the libcall sequence, the whole sequence can go. */
10315 retval_note = find_reg_note (init_insn, REG_RETVAL, NULL_RTX);
10316 /* If we found a REG_RETVAL note, find the first instruction
10317 in the sequence. */
10318 if (retval_note)
10319 first = XEXP (retval_note, 0);
10321 /* Delete the instructions. */
10322 loop_delete_insns (first, init_insn);
10324 if (loop_dump_stream)
10325 fprintf (loop_dump_stream, ".\n");
10329 /* Replace all the instructions from FIRST up to and including LAST
10330 with NOTE_INSN_DELETED notes. */
10332 static void
10333 loop_delete_insns (first, last)
10334 rtx first;
10335 rtx last;
10337 while (1)
10339 if (loop_dump_stream)
10340 fprintf (loop_dump_stream, ", deleting init_insn (%d)",
10341 INSN_UID (first));
10342 delete_insn (first);
10344 /* If this was the LAST instructions we're supposed to delete,
10345 we're done. */
10346 if (first == last)
10347 break;
10349 first = NEXT_INSN (first);
10353 /* Try to replace occurrences of pseudo REGNO with REPLACEMENT within
10354 loop LOOP if the order of the sets of these registers can be
10355 swapped. There must be exactly one insn within the loop that sets
10356 this pseudo followed immediately by a move insn that sets
10357 REPLACEMENT with REGNO. */
10358 static void
10359 try_swap_copy_prop (loop, replacement, regno)
10360 const struct loop *loop;
10361 rtx replacement;
10362 unsigned int regno;
10364 rtx insn;
10365 rtx set = NULL_RTX;
10366 unsigned int new_regno;
10368 new_regno = REGNO (replacement);
10370 for (insn = next_insn_in_loop (loop, loop->scan_start);
10371 insn != NULL_RTX;
10372 insn = next_insn_in_loop (loop, insn))
10374 /* Search for the insn that copies REGNO to NEW_REGNO? */
10375 if (INSN_P (insn)
10376 && (set = single_set (insn))
10377 && GET_CODE (SET_DEST (set)) == REG
10378 && REGNO (SET_DEST (set)) == new_regno
10379 && GET_CODE (SET_SRC (set)) == REG
10380 && REGNO (SET_SRC (set)) == regno)
10381 break;
10384 if (insn != NULL_RTX)
10386 rtx prev_insn;
10387 rtx prev_set;
10389 /* Some DEF-USE info would come in handy here to make this
10390 function more general. For now, just check the previous insn
10391 which is the most likely candidate for setting REGNO. */
10393 prev_insn = PREV_INSN (insn);
10395 if (INSN_P (insn)
10396 && (prev_set = single_set (prev_insn))
10397 && GET_CODE (SET_DEST (prev_set)) == REG
10398 && REGNO (SET_DEST (prev_set)) == regno)
10400 /* We have:
10401 (set (reg regno) (expr))
10402 (set (reg new_regno) (reg regno))
10404 so try converting this to:
10405 (set (reg new_regno) (expr))
10406 (set (reg regno) (reg new_regno))
10408 The former construct is often generated when a global
10409 variable used for an induction variable is shadowed by a
10410 register (NEW_REGNO). The latter construct improves the
10411 chances of GIV replacement and BIV elimination. */
10413 validate_change (prev_insn, &SET_DEST (prev_set),
10414 replacement, 1);
10415 validate_change (insn, &SET_DEST (set),
10416 SET_SRC (set), 1);
10417 validate_change (insn, &SET_SRC (set),
10418 replacement, 1);
10420 if (apply_change_group ())
10422 if (loop_dump_stream)
10423 fprintf (loop_dump_stream,
10424 " Swapped set of reg %d at %d with reg %d at %d.\n",
10425 regno, INSN_UID (insn),
10426 new_regno, INSN_UID (prev_insn));
10428 /* Update first use of REGNO. */
10429 if (REGNO_FIRST_UID (regno) == INSN_UID (prev_insn))
10430 REGNO_FIRST_UID (regno) = INSN_UID (insn);
10432 /* Now perform copy propagation to hopefully
10433 remove all uses of REGNO within the loop. */
10434 try_copy_prop (loop, replacement, regno);
10440 /* Worker function for find_mem_in_note, called via for_each_rtx. */
10442 static int
10443 find_mem_in_note_1 (x, data)
10444 rtx *x;
10445 void *data;
10447 if (*x != NULL_RTX && GET_CODE (*x) == MEM)
10449 rtx *res = (rtx *) data;
10450 *res = *x;
10451 return 1;
10453 return 0;
10456 /* Returns the first MEM found in NOTE by depth-first search. */
10458 static rtx
10459 find_mem_in_note (note)
10460 rtx note;
10462 if (note && for_each_rtx (&note, find_mem_in_note_1, &note))
10463 return note;
10464 return NULL_RTX;
10467 /* Replace MEM with its associated pseudo register. This function is
10468 called from load_mems via for_each_rtx. DATA is actually a pointer
10469 to a structure describing the instruction currently being scanned
10470 and the MEM we are currently replacing. */
10472 static int
10473 replace_loop_mem (mem, data)
10474 rtx *mem;
10475 void *data;
10477 loop_replace_args *args = (loop_replace_args *) data;
10478 rtx m = *mem;
10480 if (m == NULL_RTX)
10481 return 0;
10483 switch (GET_CODE (m))
10485 case MEM:
10486 break;
10488 case CONST_DOUBLE:
10489 /* We're not interested in the MEM associated with a
10490 CONST_DOUBLE, so there's no need to traverse into one. */
10491 return -1;
10493 default:
10494 /* This is not a MEM. */
10495 return 0;
10498 if (!rtx_equal_p (args->match, m))
10499 /* This is not the MEM we are currently replacing. */
10500 return 0;
10502 /* Actually replace the MEM. */
10503 validate_change (args->insn, mem, args->replacement, 1);
10505 return 0;
10508 static void
10509 replace_loop_mems (insn, mem, reg, written)
10510 rtx insn;
10511 rtx mem;
10512 rtx reg;
10513 int written;
10515 loop_replace_args args;
10517 args.insn = insn;
10518 args.match = mem;
10519 args.replacement = reg;
10521 for_each_rtx (&insn, replace_loop_mem, &args);
10523 /* If we hoist a mem write out of the loop, then REG_EQUAL
10524 notes referring to the mem are no longer valid. */
10525 if (written)
10527 rtx note, sub;
10528 rtx *link;
10530 for (link = &REG_NOTES (insn); (note = *link); link = &XEXP (note, 1))
10532 if (REG_NOTE_KIND (note) == REG_EQUAL
10533 && (sub = find_mem_in_note (note))
10534 && true_dependence (mem, VOIDmode, sub, rtx_varies_p))
10536 /* Remove the note. */
10537 validate_change (NULL_RTX, link, XEXP (note, 1), 1);
10538 break;
10544 /* Replace one register with another. Called through for_each_rtx; PX points
10545 to the rtx being scanned. DATA is actually a pointer to
10546 a structure of arguments. */
10548 static int
10549 replace_loop_reg (px, data)
10550 rtx *px;
10551 void *data;
10553 rtx x = *px;
10554 loop_replace_args *args = (loop_replace_args *) data;
10556 if (x == NULL_RTX)
10557 return 0;
10559 if (x == args->match)
10560 validate_change (args->insn, px, args->replacement, 1);
10562 return 0;
10565 static void
10566 replace_loop_regs (insn, reg, replacement)
10567 rtx insn;
10568 rtx reg;
10569 rtx replacement;
10571 loop_replace_args args;
10573 args.insn = insn;
10574 args.match = reg;
10575 args.replacement = replacement;
10577 for_each_rtx (&insn, replace_loop_reg, &args);
10580 /* Emit insn for PATTERN after WHERE_INSN in basic block WHERE_BB
10581 (ignored in the interim). */
10583 static rtx
10584 loop_insn_emit_after (loop, where_bb, where_insn, pattern)
10585 const struct loop *loop ATTRIBUTE_UNUSED;
10586 basic_block where_bb ATTRIBUTE_UNUSED;
10587 rtx where_insn;
10588 rtx pattern;
10590 return emit_insn_after (pattern, where_insn);
10594 /* If WHERE_INSN is nonzero emit insn for PATTERN before WHERE_INSN
10595 in basic block WHERE_BB (ignored in the interim) within the loop
10596 otherwise hoist PATTERN into the loop pre-header. */
10599 loop_insn_emit_before (loop, where_bb, where_insn, pattern)
10600 const struct loop *loop;
10601 basic_block where_bb ATTRIBUTE_UNUSED;
10602 rtx where_insn;
10603 rtx pattern;
10605 if (! where_insn)
10606 return loop_insn_hoist (loop, pattern);
10607 return emit_insn_before (pattern, where_insn);
10611 /* Emit call insn for PATTERN before WHERE_INSN in basic block
10612 WHERE_BB (ignored in the interim) within the loop. */
10614 static rtx
10615 loop_call_insn_emit_before (loop, where_bb, where_insn, pattern)
10616 const struct loop *loop ATTRIBUTE_UNUSED;
10617 basic_block where_bb ATTRIBUTE_UNUSED;
10618 rtx where_insn;
10619 rtx pattern;
10621 return emit_call_insn_before (pattern, where_insn);
10625 /* Hoist insn for PATTERN into the loop pre-header. */
10628 loop_insn_hoist (loop, pattern)
10629 const struct loop *loop;
10630 rtx pattern;
10632 return loop_insn_emit_before (loop, 0, loop->start, pattern);
10636 /* Hoist call insn for PATTERN into the loop pre-header. */
10638 static rtx
10639 loop_call_insn_hoist (loop, pattern)
10640 const struct loop *loop;
10641 rtx pattern;
10643 return loop_call_insn_emit_before (loop, 0, loop->start, pattern);
10647 /* Sink insn for PATTERN after the loop end. */
10650 loop_insn_sink (loop, pattern)
10651 const struct loop *loop;
10652 rtx pattern;
10654 return loop_insn_emit_before (loop, 0, loop->sink, pattern);
10657 /* bl->final_value can be eighter general_operand or PLUS of general_operand
10658 and constant. Emit sequence of instructions to load it into REG. */
10659 static rtx
10660 gen_load_of_final_value (reg, final_value)
10661 rtx reg, final_value;
10663 rtx seq;
10664 start_sequence ();
10665 final_value = force_operand (final_value, reg);
10666 if (final_value != reg)
10667 emit_move_insn (reg, final_value);
10668 seq = get_insns ();
10669 end_sequence ();
10670 return seq;
10673 /* If the loop has multiple exits, emit insn for PATTERN before the
10674 loop to ensure that it will always be executed no matter how the
10675 loop exits. Otherwise, emit the insn for PATTERN after the loop,
10676 since this is slightly more efficient. */
10678 static rtx
10679 loop_insn_sink_or_swim (loop, pattern)
10680 const struct loop *loop;
10681 rtx pattern;
10683 if (loop->exit_count)
10684 return loop_insn_hoist (loop, pattern);
10685 else
10686 return loop_insn_sink (loop, pattern);
10689 static void
10690 loop_ivs_dump (loop, file, verbose)
10691 const struct loop *loop;
10692 FILE *file;
10693 int verbose;
10695 struct iv_class *bl;
10696 int iv_num = 0;
10698 if (! loop || ! file)
10699 return;
10701 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10702 iv_num++;
10704 fprintf (file, "Loop %d: %d IV classes\n", loop->num, iv_num);
10706 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10708 loop_iv_class_dump (bl, file, verbose);
10709 fputc ('\n', file);
10714 static void
10715 loop_iv_class_dump (bl, file, verbose)
10716 const struct iv_class *bl;
10717 FILE *file;
10718 int verbose ATTRIBUTE_UNUSED;
10720 struct induction *v;
10721 rtx incr;
10722 int i;
10724 if (! bl || ! file)
10725 return;
10727 fprintf (file, "IV class for reg %d, benefit %d\n",
10728 bl->regno, bl->total_benefit);
10730 fprintf (file, " Init insn %d", INSN_UID (bl->init_insn));
10731 if (bl->initial_value)
10733 fprintf (file, ", init val: ");
10734 print_simple_rtl (file, bl->initial_value);
10736 if (bl->initial_test)
10738 fprintf (file, ", init test: ");
10739 print_simple_rtl (file, bl->initial_test);
10741 fputc ('\n', file);
10743 if (bl->final_value)
10745 fprintf (file, " Final val: ");
10746 print_simple_rtl (file, bl->final_value);
10747 fputc ('\n', file);
10750 if ((incr = biv_total_increment (bl)))
10752 fprintf (file, " Total increment: ");
10753 print_simple_rtl (file, incr);
10754 fputc ('\n', file);
10757 /* List the increments. */
10758 for (i = 0, v = bl->biv; v; v = v->next_iv, i++)
10760 fprintf (file, " Inc%d: insn %d, incr: ", i, INSN_UID (v->insn));
10761 print_simple_rtl (file, v->add_val);
10762 fputc ('\n', file);
10765 /* List the givs. */
10766 for (i = 0, v = bl->giv; v; v = v->next_iv, i++)
10768 fprintf (file, " Giv%d: insn %d, benefit %d, ",
10769 i, INSN_UID (v->insn), v->benefit);
10770 if (v->giv_type == DEST_ADDR)
10771 print_simple_rtl (file, v->mem);
10772 else
10773 print_simple_rtl (file, single_set (v->insn));
10774 fputc ('\n', file);
10779 static void
10780 loop_biv_dump (v, file, verbose)
10781 const struct induction *v;
10782 FILE *file;
10783 int verbose;
10785 if (! v || ! file)
10786 return;
10788 fprintf (file,
10789 "Biv %d: insn %d",
10790 REGNO (v->dest_reg), INSN_UID (v->insn));
10791 fprintf (file, " const ");
10792 print_simple_rtl (file, v->add_val);
10794 if (verbose && v->final_value)
10796 fputc ('\n', file);
10797 fprintf (file, " final ");
10798 print_simple_rtl (file, v->final_value);
10801 fputc ('\n', file);
10805 static void
10806 loop_giv_dump (v, file, verbose)
10807 const struct induction *v;
10808 FILE *file;
10809 int verbose;
10811 if (! v || ! file)
10812 return;
10814 if (v->giv_type == DEST_REG)
10815 fprintf (file, "Giv %d: insn %d",
10816 REGNO (v->dest_reg), INSN_UID (v->insn));
10817 else
10818 fprintf (file, "Dest address: insn %d",
10819 INSN_UID (v->insn));
10821 fprintf (file, " src reg %d benefit %d",
10822 REGNO (v->src_reg), v->benefit);
10823 fprintf (file, " lifetime %d",
10824 v->lifetime);
10826 if (v->replaceable)
10827 fprintf (file, " replaceable");
10829 if (v->no_const_addval)
10830 fprintf (file, " ncav");
10832 if (v->ext_dependent)
10834 switch (GET_CODE (v->ext_dependent))
10836 case SIGN_EXTEND:
10837 fprintf (file, " ext se");
10838 break;
10839 case ZERO_EXTEND:
10840 fprintf (file, " ext ze");
10841 break;
10842 case TRUNCATE:
10843 fprintf (file, " ext tr");
10844 break;
10845 default:
10846 abort ();
10850 fputc ('\n', file);
10851 fprintf (file, " mult ");
10852 print_simple_rtl (file, v->mult_val);
10854 fputc ('\n', file);
10855 fprintf (file, " add ");
10856 print_simple_rtl (file, v->add_val);
10858 if (verbose && v->final_value)
10860 fputc ('\n', file);
10861 fprintf (file, " final ");
10862 print_simple_rtl (file, v->final_value);
10865 fputc ('\n', file);
10869 void
10870 debug_ivs (loop)
10871 const struct loop *loop;
10873 loop_ivs_dump (loop, stderr, 1);
10877 void
10878 debug_iv_class (bl)
10879 const struct iv_class *bl;
10881 loop_iv_class_dump (bl, stderr, 1);
10885 void
10886 debug_biv (v)
10887 const struct induction *v;
10889 loop_biv_dump (v, stderr, 1);
10893 void
10894 debug_giv (v)
10895 const struct induction *v;
10897 loop_giv_dump (v, stderr, 1);
10901 #define LOOP_BLOCK_NUM_1(INSN) \
10902 ((INSN) ? (BLOCK_FOR_INSN (INSN) ? BLOCK_NUM (INSN) : - 1) : -1)
10904 /* The notes do not have an assigned block, so look at the next insn. */
10905 #define LOOP_BLOCK_NUM(INSN) \
10906 ((INSN) ? (GET_CODE (INSN) == NOTE \
10907 ? LOOP_BLOCK_NUM_1 (next_nonnote_insn (INSN)) \
10908 : LOOP_BLOCK_NUM_1 (INSN)) \
10909 : -1)
10911 #define LOOP_INSN_UID(INSN) ((INSN) ? INSN_UID (INSN) : -1)
10913 static void
10914 loop_dump_aux (loop, file, verbose)
10915 const struct loop *loop;
10916 FILE *file;
10917 int verbose ATTRIBUTE_UNUSED;
10919 rtx label;
10921 if (! loop || ! file)
10922 return;
10924 /* Print diagnostics to compare our concept of a loop with
10925 what the loop notes say. */
10926 if (! PREV_INSN (loop->first->head)
10927 || GET_CODE (PREV_INSN (loop->first->head)) != NOTE
10928 || NOTE_LINE_NUMBER (PREV_INSN (loop->first->head))
10929 != NOTE_INSN_LOOP_BEG)
10930 fprintf (file, ";; No NOTE_INSN_LOOP_BEG at %d\n",
10931 INSN_UID (PREV_INSN (loop->first->head)));
10932 if (! NEXT_INSN (loop->last->end)
10933 || GET_CODE (NEXT_INSN (loop->last->end)) != NOTE
10934 || NOTE_LINE_NUMBER (NEXT_INSN (loop->last->end))
10935 != NOTE_INSN_LOOP_END)
10936 fprintf (file, ";; No NOTE_INSN_LOOP_END at %d\n",
10937 INSN_UID (NEXT_INSN (loop->last->end)));
10939 if (loop->start)
10941 fprintf (file,
10942 ";; start %d (%d), cont dom %d (%d), cont %d (%d), vtop %d (%d), end %d (%d)\n",
10943 LOOP_BLOCK_NUM (loop->start),
10944 LOOP_INSN_UID (loop->start),
10945 LOOP_BLOCK_NUM (loop->cont),
10946 LOOP_INSN_UID (loop->cont),
10947 LOOP_BLOCK_NUM (loop->cont),
10948 LOOP_INSN_UID (loop->cont),
10949 LOOP_BLOCK_NUM (loop->vtop),
10950 LOOP_INSN_UID (loop->vtop),
10951 LOOP_BLOCK_NUM (loop->end),
10952 LOOP_INSN_UID (loop->end));
10953 fprintf (file, ";; top %d (%d), scan start %d (%d)\n",
10954 LOOP_BLOCK_NUM (loop->top),
10955 LOOP_INSN_UID (loop->top),
10956 LOOP_BLOCK_NUM (loop->scan_start),
10957 LOOP_INSN_UID (loop->scan_start));
10958 fprintf (file, ";; exit_count %d", loop->exit_count);
10959 if (loop->exit_count)
10961 fputs (", labels:", file);
10962 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
10964 fprintf (file, " %d ",
10965 LOOP_INSN_UID (XEXP (label, 0)));
10968 fputs ("\n", file);
10970 /* This can happen when a marked loop appears as two nested loops,
10971 say from while (a || b) {}. The inner loop won't match
10972 the loop markers but the outer one will. */
10973 if (LOOP_BLOCK_NUM (loop->cont) != loop->latch->index)
10974 fprintf (file, ";; NOTE_INSN_LOOP_CONT not in loop latch\n");
10978 /* Call this function from the debugger to dump LOOP. */
10980 void
10981 debug_loop (loop)
10982 const struct loop *loop;
10984 flow_loop_dump (loop, stderr, loop_dump_aux, 1);
10987 /* Call this function from the debugger to dump LOOPS. */
10989 void
10990 debug_loops (loops)
10991 const struct loops *loops;
10993 flow_loops_dump (loops, stderr, loop_dump_aux, 1);