* configure.in (arm-*-netbsdelf*): Enable building java libraries.
[official-gcc.git] / gcc / loop.c
blobd7ae3ea582361a20447f6fdb623c209c9484939f
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 register that was made
837 by loop-optimization for an inner loop.
838 We don't know its life-span, so we can't compute
839 the benefit. */
840 if (REGNO (SET_DEST (set)) >= max_reg_before_loop)
842 /* Don't move the source and add a reg-to-reg copy:
843 - with -Os (this certainly increases size),
844 - if the mode doesn't support copy operations (obviously),
845 - if the source is already a reg (the motion will gain nothing),
846 - if the source is a legitimate constant (likewise). */
847 else if (insert_temp
848 && (optimize_size
849 || ! can_copy_p (GET_MODE (SET_SRC (set)))
850 || GET_CODE (SET_SRC (set)) == REG
851 || (CONSTANT_P (SET_SRC (set))
852 && LEGITIMATE_CONSTANT_P (SET_SRC (set)))))
854 else if ((tem = loop_invariant_p (loop, src))
855 && (dependencies == 0
856 || (tem2
857 = loop_invariant_p (loop, dependencies)) != 0)
858 && (regs->array[REGNO (SET_DEST (set))].set_in_loop == 1
859 || (tem1
860 = consec_sets_invariant_p
861 (loop, SET_DEST (set),
862 regs->array[REGNO (SET_DEST (set))].set_in_loop,
863 p)))
864 /* If the insn can cause a trap (such as divide by zero),
865 can't move it unless it's guaranteed to be executed
866 once loop is entered. Even a function call might
867 prevent the trap insn from being reached
868 (since it might exit!) */
869 && ! ((maybe_never || call_passed)
870 && may_trap_p (src)))
872 struct movable *m;
873 int regno = REGNO (SET_DEST (set));
875 /* A potential lossage is where we have a case where two insns
876 can be combined as long as they are both in the loop, but
877 we move one of them outside the loop. For large loops,
878 this can lose. The most common case of this is the address
879 of a function being called.
881 Therefore, if this register is marked as being used
882 exactly once if we are in a loop with calls
883 (a "large loop"), see if we can replace the usage of
884 this register with the source of this SET. If we can,
885 delete this insn.
887 Don't do this if P has a REG_RETVAL note or if we have
888 SMALL_REGISTER_CLASSES and SET_SRC is a hard register. */
890 if (loop_info->has_call
891 && regs->array[regno].single_usage != 0
892 && regs->array[regno].single_usage != const0_rtx
893 && REGNO_FIRST_UID (regno) == INSN_UID (p)
894 && (REGNO_LAST_UID (regno)
895 == INSN_UID (regs->array[regno].single_usage))
896 && regs->array[regno].set_in_loop == 1
897 && GET_CODE (SET_SRC (set)) != ASM_OPERANDS
898 && ! side_effects_p (SET_SRC (set))
899 && ! find_reg_note (p, REG_RETVAL, NULL_RTX)
900 && (! SMALL_REGISTER_CLASSES
901 || (! (GET_CODE (SET_SRC (set)) == REG
902 && (REGNO (SET_SRC (set))
903 < FIRST_PSEUDO_REGISTER))))
904 /* This test is not redundant; SET_SRC (set) might be
905 a call-clobbered register and the life of REGNO
906 might span a call. */
907 && ! modified_between_p (SET_SRC (set), p,
908 regs->array[regno].single_usage)
909 && no_labels_between_p (p,
910 regs->array[regno].single_usage)
911 && validate_replace_rtx (SET_DEST (set), SET_SRC (set),
912 regs->array[regno].single_usage))
914 /* Replace any usage in a REG_EQUAL note. Must copy
915 the new source, so that we don't get rtx sharing
916 between the SET_SOURCE and REG_NOTES of insn p. */
917 REG_NOTES (regs->array[regno].single_usage)
918 = (replace_rtx
919 (REG_NOTES (regs->array[regno].single_usage),
920 SET_DEST (set), copy_rtx (SET_SRC (set))));
922 delete_insn (p);
923 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
924 i++)
925 regs->array[regno+i].set_in_loop = 0;
926 continue;
929 m = (struct movable *) xmalloc (sizeof (struct movable));
930 m->next = 0;
931 m->insn = p;
932 m->set_src = src;
933 m->dependencies = dependencies;
934 m->set_dest = SET_DEST (set);
935 m->force = 0;
936 m->consec
937 = regs->array[REGNO (SET_DEST (set))].set_in_loop - 1;
938 m->done = 0;
939 m->forces = 0;
940 m->partial = 0;
941 m->move_insn = move_insn;
942 m->move_insn_first = 0;
943 m->insert_temp = insert_temp;
944 m->is_equiv = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
945 m->savemode = VOIDmode;
946 m->regno = regno;
947 /* Set M->cond if either loop_invariant_p
948 or consec_sets_invariant_p returned 2
949 (only conditionally invariant). */
950 m->cond = ((tem | tem1 | tem2) > 1);
951 m->global = LOOP_REG_GLOBAL_P (loop, regno);
952 m->match = 0;
953 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
954 m->savings = regs->array[regno].n_times_set;
955 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
956 m->savings += libcall_benefit (p);
957 for (i = 0; i < LOOP_REGNO_NREGS (regno, SET_DEST (set)); i++)
958 regs->array[regno+i].set_in_loop = move_insn ? -2 : -1;
959 /* Add M to the end of the chain MOVABLES. */
960 loop_movables_add (movables, m);
962 if (m->consec > 0)
964 /* It is possible for the first instruction to have a
965 REG_EQUAL note but a non-invariant SET_SRC, so we must
966 remember the status of the first instruction in case
967 the last instruction doesn't have a REG_EQUAL note. */
968 m->move_insn_first = m->move_insn;
970 /* Skip this insn, not checking REG_LIBCALL notes. */
971 p = next_nonnote_insn (p);
972 /* Skip the consecutive insns, if there are any. */
973 p = skip_consec_insns (p, m->consec);
974 /* Back up to the last insn of the consecutive group. */
975 p = prev_nonnote_insn (p);
977 /* We must now reset m->move_insn, m->is_equiv, and
978 possibly m->set_src to correspond to the effects of
979 all the insns. */
980 temp = find_reg_note (p, REG_EQUIV, NULL_RTX);
981 if (temp)
982 m->set_src = XEXP (temp, 0), m->move_insn = 1;
983 else
985 temp = find_reg_note (p, REG_EQUAL, NULL_RTX);
986 if (temp && CONSTANT_P (XEXP (temp, 0)))
987 m->set_src = XEXP (temp, 0), m->move_insn = 1;
988 else
989 m->move_insn = 0;
992 m->is_equiv
993 = (find_reg_note (p, REG_EQUIV, NULL_RTX) != 0);
996 /* If this register is always set within a STRICT_LOW_PART
997 or set to zero, then its high bytes are constant.
998 So clear them outside the loop and within the loop
999 just load the low bytes.
1000 We must check that the machine has an instruction to do so.
1001 Also, if the value loaded into the register
1002 depends on the same register, this cannot be done. */
1003 else if (SET_SRC (set) == const0_rtx
1004 && GET_CODE (NEXT_INSN (p)) == INSN
1005 && (set1 = single_set (NEXT_INSN (p)))
1006 && GET_CODE (set1) == SET
1007 && (GET_CODE (SET_DEST (set1)) == STRICT_LOW_PART)
1008 && (GET_CODE (XEXP (SET_DEST (set1), 0)) == SUBREG)
1009 && (SUBREG_REG (XEXP (SET_DEST (set1), 0))
1010 == SET_DEST (set))
1011 && !reg_mentioned_p (SET_DEST (set), SET_SRC (set1)))
1013 int regno = REGNO (SET_DEST (set));
1014 if (regs->array[regno].set_in_loop == 2)
1016 struct movable *m;
1017 m = (struct movable *) xmalloc (sizeof (struct movable));
1018 m->next = 0;
1019 m->insn = p;
1020 m->set_dest = SET_DEST (set);
1021 m->dependencies = 0;
1022 m->force = 0;
1023 m->consec = 0;
1024 m->done = 0;
1025 m->forces = 0;
1026 m->move_insn = 0;
1027 m->move_insn_first = 0;
1028 m->insert_temp = insert_temp;
1029 m->partial = 1;
1030 /* If the insn may not be executed on some cycles,
1031 we can't clear the whole reg; clear just high part.
1032 Not even if the reg is used only within this loop.
1033 Consider this:
1034 while (1)
1035 while (s != t) {
1036 if (foo ()) x = *s;
1037 use (x);
1039 Clearing x before the inner loop could clobber a value
1040 being saved from the last time around the outer loop.
1041 However, if the reg is not used outside this loop
1042 and all uses of the register are in the same
1043 basic block as the store, there is no problem.
1045 If this insn was made by loop, we don't know its
1046 INSN_LUID and hence must make a conservative
1047 assumption. */
1048 m->global = (INSN_UID (p) >= max_uid_for_loop
1049 || LOOP_REG_GLOBAL_P (loop, regno)
1050 || (labels_in_range_p
1051 (p, REGNO_FIRST_LUID (regno))));
1052 if (maybe_never && m->global)
1053 m->savemode = GET_MODE (SET_SRC (set1));
1054 else
1055 m->savemode = VOIDmode;
1056 m->regno = regno;
1057 m->cond = 0;
1058 m->match = 0;
1059 m->lifetime = LOOP_REG_LIFETIME (loop, regno);
1060 m->savings = 1;
1061 for (i = 0;
1062 i < LOOP_REGNO_NREGS (regno, SET_DEST (set));
1063 i++)
1064 regs->array[regno+i].set_in_loop = -1;
1065 /* Add M to the end of the chain MOVABLES. */
1066 loop_movables_add (movables, m);
1071 /* Past a call insn, we get to insns which might not be executed
1072 because the call might exit. This matters for insns that trap.
1073 Constant and pure call insns always return, so they don't count. */
1074 else if (GET_CODE (p) == CALL_INSN && ! CONST_OR_PURE_CALL_P (p))
1075 call_passed = 1;
1076 /* Past a label or a jump, we get to insns for which we
1077 can't count on whether or how many times they will be
1078 executed during each iteration. Therefore, we can
1079 only move out sets of trivial variables
1080 (those not used after the loop). */
1081 /* Similar code appears twice in strength_reduce. */
1082 else if ((GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN)
1083 /* If we enter the loop in the middle, and scan around to the
1084 beginning, don't set maybe_never for that. This must be an
1085 unconditional jump, otherwise the code at the top of the
1086 loop might never be executed. Unconditional jumps are
1087 followed by a barrier then the loop_end. */
1088 && ! (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p) == loop->top
1089 && NEXT_INSN (NEXT_INSN (p)) == loop_end
1090 && any_uncondjump_p (p)))
1091 maybe_never = 1;
1092 else if (GET_CODE (p) == NOTE)
1094 /* At the virtual top of a converted loop, insns are again known to
1095 be executed: logically, the loop begins here even though the exit
1096 code has been duplicated. */
1097 if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP && loop_depth == 0)
1098 maybe_never = call_passed = 0;
1099 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
1100 loop_depth++;
1101 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
1102 loop_depth--;
1106 /* If one movable subsumes another, ignore that other. */
1108 ignore_some_movables (movables);
1110 /* For each movable insn, see if the reg that it loads
1111 leads when it dies right into another conditionally movable insn.
1112 If so, record that the second insn "forces" the first one,
1113 since the second can be moved only if the first is. */
1115 force_movables (movables);
1117 /* See if there are multiple movable insns that load the same value.
1118 If there are, make all but the first point at the first one
1119 through the `match' field, and add the priorities of them
1120 all together as the priority of the first. */
1122 combine_movables (movables, regs);
1124 /* Now consider each movable insn to decide whether it is worth moving.
1125 Store 0 in regs->array[I].set_in_loop for each reg I that is moved.
1127 For machines with few registers this increases code size, so do not
1128 move moveables when optimizing for code size on such machines.
1129 (The 18 below is the value for i386.) */
1131 if (!optimize_size
1132 || (reg_class_size[GENERAL_REGS] > 18 && !loop_info->has_call))
1134 move_movables (loop, movables, threshold, insn_count);
1136 /* Recalculate regs->array if move_movables has created new
1137 registers. */
1138 if (max_reg_num () > regs->num)
1140 loop_regs_scan (loop, 0);
1141 for (update_start = loop_start;
1142 PREV_INSN (update_start)
1143 && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1144 update_start = PREV_INSN (update_start))
1146 update_end = NEXT_INSN (loop_end);
1148 reg_scan_update (update_start, update_end, loop_max_reg);
1149 loop_max_reg = max_reg_num ();
1153 /* Now candidates that still are negative are those not moved.
1154 Change regs->array[I].set_in_loop to indicate that those are not actually
1155 invariant. */
1156 for (i = 0; i < regs->num; i++)
1157 if (regs->array[i].set_in_loop < 0)
1158 regs->array[i].set_in_loop = regs->array[i].n_times_set;
1160 /* Now that we've moved some things out of the loop, we might be able to
1161 hoist even more memory references. */
1162 load_mems (loop);
1164 /* Recalculate regs->array if load_mems has created new registers. */
1165 if (max_reg_num () > regs->num)
1166 loop_regs_scan (loop, 0);
1168 for (update_start = loop_start;
1169 PREV_INSN (update_start)
1170 && GET_CODE (PREV_INSN (update_start)) != CODE_LABEL;
1171 update_start = PREV_INSN (update_start))
1173 update_end = NEXT_INSN (loop_end);
1175 reg_scan_update (update_start, update_end, loop_max_reg);
1176 loop_max_reg = max_reg_num ();
1178 if (flag_strength_reduce)
1180 if (update_end && GET_CODE (update_end) == CODE_LABEL)
1181 /* Ensure our label doesn't go away. */
1182 LABEL_NUSES (update_end)++;
1184 strength_reduce (loop, flags);
1186 reg_scan_update (update_start, update_end, loop_max_reg);
1187 loop_max_reg = max_reg_num ();
1189 if (update_end && GET_CODE (update_end) == CODE_LABEL
1190 && --LABEL_NUSES (update_end) == 0)
1191 delete_related_insns (update_end);
1195 /* The movable information is required for strength reduction. */
1196 loop_movables_free (movables);
1198 free (regs->array);
1199 regs->array = 0;
1200 regs->num = 0;
1203 /* Add elements to *OUTPUT to record all the pseudo-regs
1204 mentioned in IN_THIS but not mentioned in NOT_IN_THIS. */
1206 void
1207 record_excess_regs (in_this, not_in_this, output)
1208 rtx in_this, not_in_this;
1209 rtx *output;
1211 enum rtx_code code;
1212 const char *fmt;
1213 int i;
1215 code = GET_CODE (in_this);
1217 switch (code)
1219 case PC:
1220 case CC0:
1221 case CONST_INT:
1222 case CONST_DOUBLE:
1223 case CONST:
1224 case SYMBOL_REF:
1225 case LABEL_REF:
1226 return;
1228 case REG:
1229 if (REGNO (in_this) >= FIRST_PSEUDO_REGISTER
1230 && ! reg_mentioned_p (in_this, not_in_this))
1231 *output = gen_rtx_EXPR_LIST (VOIDmode, in_this, *output);
1232 return;
1234 default:
1235 break;
1238 fmt = GET_RTX_FORMAT (code);
1239 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1241 int j;
1243 switch (fmt[i])
1245 case 'E':
1246 for (j = 0; j < XVECLEN (in_this, i); j++)
1247 record_excess_regs (XVECEXP (in_this, i, j), not_in_this, output);
1248 break;
1250 case 'e':
1251 record_excess_regs (XEXP (in_this, i), not_in_this, output);
1252 break;
1257 /* Check what regs are referred to in the libcall block ending with INSN,
1258 aside from those mentioned in the equivalent value.
1259 If there are none, return 0.
1260 If there are one or more, return an EXPR_LIST containing all of them. */
1263 libcall_other_reg (insn, equiv)
1264 rtx insn, equiv;
1266 rtx note = find_reg_note (insn, REG_RETVAL, NULL_RTX);
1267 rtx p = XEXP (note, 0);
1268 rtx output = 0;
1270 /* First, find all the regs used in the libcall block
1271 that are not mentioned as inputs to the result. */
1273 while (p != insn)
1275 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
1276 || GET_CODE (p) == CALL_INSN)
1277 record_excess_regs (PATTERN (p), equiv, &output);
1278 p = NEXT_INSN (p);
1281 return output;
1284 /* Return 1 if all uses of REG
1285 are between INSN and the end of the basic block. */
1287 static int
1288 reg_in_basic_block_p (insn, reg)
1289 rtx insn, reg;
1291 int regno = REGNO (reg);
1292 rtx p;
1294 if (REGNO_FIRST_UID (regno) != INSN_UID (insn))
1295 return 0;
1297 /* Search this basic block for the already recorded last use of the reg. */
1298 for (p = insn; p; p = NEXT_INSN (p))
1300 switch (GET_CODE (p))
1302 case NOTE:
1303 break;
1305 case INSN:
1306 case CALL_INSN:
1307 /* Ordinary insn: if this is the last use, we win. */
1308 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1309 return 1;
1310 break;
1312 case JUMP_INSN:
1313 /* Jump insn: if this is the last use, we win. */
1314 if (REGNO_LAST_UID (regno) == INSN_UID (p))
1315 return 1;
1316 /* Otherwise, it's the end of the basic block, so we lose. */
1317 return 0;
1319 case CODE_LABEL:
1320 case BARRIER:
1321 /* It's the end of the basic block, so we lose. */
1322 return 0;
1324 default:
1325 break;
1329 /* The "last use" that was recorded can't be found after the first
1330 use. This can happen when the last use was deleted while
1331 processing an inner loop, this inner loop was then completely
1332 unrolled, and the outer loop is always exited after the inner loop,
1333 so that everything after the first use becomes a single basic block. */
1334 return 1;
1337 /* Compute the benefit of eliminating the insns in the block whose
1338 last insn is LAST. This may be a group of insns used to compute a
1339 value directly or can contain a library call. */
1341 static int
1342 libcall_benefit (last)
1343 rtx last;
1345 rtx insn;
1346 int benefit = 0;
1348 for (insn = XEXP (find_reg_note (last, REG_RETVAL, NULL_RTX), 0);
1349 insn != last; insn = NEXT_INSN (insn))
1351 if (GET_CODE (insn) == CALL_INSN)
1352 benefit += 10; /* Assume at least this many insns in a library
1353 routine. */
1354 else if (GET_CODE (insn) == INSN
1355 && GET_CODE (PATTERN (insn)) != USE
1356 && GET_CODE (PATTERN (insn)) != CLOBBER)
1357 benefit++;
1360 return benefit;
1363 /* Skip COUNT insns from INSN, counting library calls as 1 insn. */
1365 static rtx
1366 skip_consec_insns (insn, count)
1367 rtx insn;
1368 int count;
1370 for (; count > 0; count--)
1372 rtx temp;
1374 /* If first insn of libcall sequence, skip to end. */
1375 /* Do this at start of loop, since INSN is guaranteed to
1376 be an insn here. */
1377 if (GET_CODE (insn) != NOTE
1378 && (temp = find_reg_note (insn, REG_LIBCALL, NULL_RTX)))
1379 insn = XEXP (temp, 0);
1382 insn = NEXT_INSN (insn);
1383 while (GET_CODE (insn) == NOTE);
1386 return insn;
1389 /* Ignore any movable whose insn falls within a libcall
1390 which is part of another movable.
1391 We make use of the fact that the movable for the libcall value
1392 was made later and so appears later on the chain. */
1394 static void
1395 ignore_some_movables (movables)
1396 struct loop_movables *movables;
1398 struct movable *m, *m1;
1400 for (m = movables->head; m; m = m->next)
1402 /* Is this a movable for the value of a libcall? */
1403 rtx note = find_reg_note (m->insn, REG_RETVAL, NULL_RTX);
1404 if (note)
1406 rtx insn;
1407 /* Check for earlier movables inside that range,
1408 and mark them invalid. We cannot use LUIDs here because
1409 insns created by loop.c for prior loops don't have LUIDs.
1410 Rather than reject all such insns from movables, we just
1411 explicitly check each insn in the libcall (since invariant
1412 libcalls aren't that common). */
1413 for (insn = XEXP (note, 0); insn != m->insn; insn = NEXT_INSN (insn))
1414 for (m1 = movables->head; m1 != m; m1 = m1->next)
1415 if (m1->insn == insn)
1416 m1->done = 1;
1421 /* For each movable insn, see if the reg that it loads
1422 leads when it dies right into another conditionally movable insn.
1423 If so, record that the second insn "forces" the first one,
1424 since the second can be moved only if the first is. */
1426 static void
1427 force_movables (movables)
1428 struct loop_movables *movables;
1430 struct movable *m, *m1;
1432 for (m1 = movables->head; m1; m1 = m1->next)
1433 /* Omit this if moving just the (SET (REG) 0) of a zero-extend. */
1434 if (!m1->partial && !m1->done)
1436 int regno = m1->regno;
1437 for (m = m1->next; m; m = m->next)
1438 /* ??? Could this be a bug? What if CSE caused the
1439 register of M1 to be used after this insn?
1440 Since CSE does not update regno_last_uid,
1441 this insn M->insn might not be where it dies.
1442 But very likely this doesn't matter; what matters is
1443 that M's reg is computed from M1's reg. */
1444 if (INSN_UID (m->insn) == REGNO_LAST_UID (regno)
1445 && !m->done)
1446 break;
1447 if (m != 0 && m->set_src == m1->set_dest
1448 /* If m->consec, m->set_src isn't valid. */
1449 && m->consec == 0)
1450 m = 0;
1452 /* Increase the priority of the moving the first insn
1453 since it permits the second to be moved as well. */
1454 if (m != 0)
1456 m->forces = m1;
1457 m1->lifetime += m->lifetime;
1458 m1->savings += m->savings;
1463 /* Find invariant expressions that are equal and can be combined into
1464 one register. */
1466 static void
1467 combine_movables (movables, regs)
1468 struct loop_movables *movables;
1469 struct loop_regs *regs;
1471 struct movable *m;
1472 char *matched_regs = (char *) xmalloc (regs->num);
1473 enum machine_mode mode;
1475 /* Regs that are set more than once are not allowed to match
1476 or be matched. I'm no longer sure why not. */
1477 /* Only pseudo registers are allowed to match or be matched,
1478 since move_movables does not validate the change. */
1479 /* Perhaps testing m->consec_sets would be more appropriate here? */
1481 for (m = movables->head; m; m = m->next)
1482 if (m->match == 0 && regs->array[m->regno].n_times_set == 1
1483 && m->regno >= FIRST_PSEUDO_REGISTER
1484 && !m->insert_temp
1485 && !m->partial)
1487 struct movable *m1;
1488 int regno = m->regno;
1490 memset (matched_regs, 0, regs->num);
1491 matched_regs[regno] = 1;
1493 /* We want later insns to match the first one. Don't make the first
1494 one match any later ones. So start this loop at m->next. */
1495 for (m1 = m->next; m1; m1 = m1->next)
1496 if (m != m1 && m1->match == 0
1497 && !m1->insert_temp
1498 && regs->array[m1->regno].n_times_set == 1
1499 && m1->regno >= FIRST_PSEUDO_REGISTER
1500 /* A reg used outside the loop mustn't be eliminated. */
1501 && !m1->global
1502 /* A reg used for zero-extending mustn't be eliminated. */
1503 && !m1->partial
1504 && (matched_regs[m1->regno]
1507 /* Can combine regs with different modes loaded from the
1508 same constant only if the modes are the same or
1509 if both are integer modes with M wider or the same
1510 width as M1. The check for integer is redundant, but
1511 safe, since the only case of differing destination
1512 modes with equal sources is when both sources are
1513 VOIDmode, i.e., CONST_INT. */
1514 (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest)
1515 || (GET_MODE_CLASS (GET_MODE (m->set_dest)) == MODE_INT
1516 && GET_MODE_CLASS (GET_MODE (m1->set_dest)) == MODE_INT
1517 && (GET_MODE_BITSIZE (GET_MODE (m->set_dest))
1518 >= GET_MODE_BITSIZE (GET_MODE (m1->set_dest)))))
1519 /* See if the source of M1 says it matches M. */
1520 && ((GET_CODE (m1->set_src) == REG
1521 && matched_regs[REGNO (m1->set_src)])
1522 || rtx_equal_for_loop_p (m->set_src, m1->set_src,
1523 movables, regs))))
1524 && ((m->dependencies == m1->dependencies)
1525 || rtx_equal_p (m->dependencies, m1->dependencies)))
1527 m->lifetime += m1->lifetime;
1528 m->savings += m1->savings;
1529 m1->done = 1;
1530 m1->match = m;
1531 matched_regs[m1->regno] = 1;
1535 /* Now combine the regs used for zero-extension.
1536 This can be done for those not marked `global'
1537 provided their lives don't overlap. */
1539 for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1540 mode = GET_MODE_WIDER_MODE (mode))
1542 struct movable *m0 = 0;
1544 /* Combine all the registers for extension from mode MODE.
1545 Don't combine any that are used outside this loop. */
1546 for (m = movables->head; m; m = m->next)
1547 if (m->partial && ! m->global
1548 && mode == GET_MODE (SET_SRC (PATTERN (NEXT_INSN (m->insn)))))
1550 struct movable *m1;
1552 int first = REGNO_FIRST_LUID (m->regno);
1553 int last = REGNO_LAST_LUID (m->regno);
1555 if (m0 == 0)
1557 /* First one: don't check for overlap, just record it. */
1558 m0 = m;
1559 continue;
1562 /* Make sure they extend to the same mode.
1563 (Almost always true.) */
1564 if (GET_MODE (m->set_dest) != GET_MODE (m0->set_dest))
1565 continue;
1567 /* We already have one: check for overlap with those
1568 already combined together. */
1569 for (m1 = movables->head; m1 != m; m1 = m1->next)
1570 if (m1 == m0 || (m1->partial && m1->match == m0))
1571 if (! (REGNO_FIRST_LUID (m1->regno) > last
1572 || REGNO_LAST_LUID (m1->regno) < first))
1573 goto overlap;
1575 /* No overlap: we can combine this with the others. */
1576 m0->lifetime += m->lifetime;
1577 m0->savings += m->savings;
1578 m->done = 1;
1579 m->match = m0;
1581 overlap:
1586 /* Clean up. */
1587 free (matched_regs);
1590 /* Returns the number of movable instructions in LOOP that were not
1591 moved outside the loop. */
1593 static int
1594 num_unmoved_movables (loop)
1595 const struct loop *loop;
1597 int num = 0;
1598 struct movable *m;
1600 for (m = LOOP_MOVABLES (loop)->head; m; m = m->next)
1601 if (!m->done)
1602 ++num;
1604 return num;
1608 /* Return 1 if regs X and Y will become the same if moved. */
1610 static int
1611 regs_match_p (x, y, movables)
1612 rtx x, y;
1613 struct loop_movables *movables;
1615 unsigned int xn = REGNO (x);
1616 unsigned int yn = REGNO (y);
1617 struct movable *mx, *my;
1619 for (mx = movables->head; mx; mx = mx->next)
1620 if (mx->regno == xn)
1621 break;
1623 for (my = movables->head; my; my = my->next)
1624 if (my->regno == yn)
1625 break;
1627 return (mx && my
1628 && ((mx->match == my->match && mx->match != 0)
1629 || mx->match == my
1630 || mx == my->match));
1633 /* Return 1 if X and Y are identical-looking rtx's.
1634 This is the Lisp function EQUAL for rtx arguments.
1636 If two registers are matching movables or a movable register and an
1637 equivalent constant, consider them equal. */
1639 static int
1640 rtx_equal_for_loop_p (x, y, movables, regs)
1641 rtx x, y;
1642 struct loop_movables *movables;
1643 struct loop_regs *regs;
1645 int i;
1646 int j;
1647 struct movable *m;
1648 enum rtx_code code;
1649 const char *fmt;
1651 if (x == y)
1652 return 1;
1653 if (x == 0 || y == 0)
1654 return 0;
1656 code = GET_CODE (x);
1658 /* If we have a register and a constant, they may sometimes be
1659 equal. */
1660 if (GET_CODE (x) == REG && regs->array[REGNO (x)].set_in_loop == -2
1661 && CONSTANT_P (y))
1663 for (m = movables->head; m; m = m->next)
1664 if (m->move_insn && m->regno == REGNO (x)
1665 && rtx_equal_p (m->set_src, y))
1666 return 1;
1668 else if (GET_CODE (y) == REG && regs->array[REGNO (y)].set_in_loop == -2
1669 && CONSTANT_P (x))
1671 for (m = movables->head; m; m = m->next)
1672 if (m->move_insn && m->regno == REGNO (y)
1673 && rtx_equal_p (m->set_src, x))
1674 return 1;
1677 /* Otherwise, rtx's of different codes cannot be equal. */
1678 if (code != GET_CODE (y))
1679 return 0;
1681 /* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent.
1682 (REG:SI x) and (REG:HI x) are NOT equivalent. */
1684 if (GET_MODE (x) != GET_MODE (y))
1685 return 0;
1687 /* These three types of rtx's can be compared nonrecursively. */
1688 if (code == REG)
1689 return (REGNO (x) == REGNO (y) || regs_match_p (x, y, movables));
1691 if (code == LABEL_REF)
1692 return XEXP (x, 0) == XEXP (y, 0);
1693 if (code == SYMBOL_REF)
1694 return XSTR (x, 0) == XSTR (y, 0);
1696 /* Compare the elements. If any pair of corresponding elements
1697 fail to match, return 0 for the whole things. */
1699 fmt = GET_RTX_FORMAT (code);
1700 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1702 switch (fmt[i])
1704 case 'w':
1705 if (XWINT (x, i) != XWINT (y, i))
1706 return 0;
1707 break;
1709 case 'i':
1710 if (XINT (x, i) != XINT (y, i))
1711 return 0;
1712 break;
1714 case 'E':
1715 /* Two vectors must have the same length. */
1716 if (XVECLEN (x, i) != XVECLEN (y, i))
1717 return 0;
1719 /* And the corresponding elements must match. */
1720 for (j = 0; j < XVECLEN (x, i); j++)
1721 if (rtx_equal_for_loop_p (XVECEXP (x, i, j), XVECEXP (y, i, j),
1722 movables, regs) == 0)
1723 return 0;
1724 break;
1726 case 'e':
1727 if (rtx_equal_for_loop_p (XEXP (x, i), XEXP (y, i), movables, regs)
1728 == 0)
1729 return 0;
1730 break;
1732 case 's':
1733 if (strcmp (XSTR (x, i), XSTR (y, i)))
1734 return 0;
1735 break;
1737 case 'u':
1738 /* These are just backpointers, so they don't matter. */
1739 break;
1741 case '0':
1742 break;
1744 /* It is believed that rtx's at this level will never
1745 contain anything but integers and other rtx's,
1746 except for within LABEL_REFs and SYMBOL_REFs. */
1747 default:
1748 abort ();
1751 return 1;
1754 /* If X contains any LABEL_REF's, add REG_LABEL notes for them to all
1755 insns in INSNS which use the reference. LABEL_NUSES for CODE_LABEL
1756 references is incremented once for each added note. */
1758 static void
1759 add_label_notes (x, insns)
1760 rtx x;
1761 rtx insns;
1763 enum rtx_code code = GET_CODE (x);
1764 int i, j;
1765 const char *fmt;
1766 rtx insn;
1768 if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
1770 /* This code used to ignore labels that referred to dispatch tables to
1771 avoid flow generating (slighly) worse code.
1773 We no longer ignore such label references (see LABEL_REF handling in
1774 mark_jump_label for additional information). */
1775 for (insn = insns; insn; insn = NEXT_INSN (insn))
1776 if (reg_mentioned_p (XEXP (x, 0), insn))
1778 REG_NOTES (insn) = gen_rtx_INSN_LIST (REG_LABEL, XEXP (x, 0),
1779 REG_NOTES (insn));
1780 if (LABEL_P (XEXP (x, 0)))
1781 LABEL_NUSES (XEXP (x, 0))++;
1785 fmt = GET_RTX_FORMAT (code);
1786 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
1788 if (fmt[i] == 'e')
1789 add_label_notes (XEXP (x, i), insns);
1790 else if (fmt[i] == 'E')
1791 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
1792 add_label_notes (XVECEXP (x, i, j), insns);
1796 /* Scan MOVABLES, and move the insns that deserve to be moved.
1797 If two matching movables are combined, replace one reg with the
1798 other throughout. */
1800 static void
1801 move_movables (loop, movables, threshold, insn_count)
1802 struct loop *loop;
1803 struct loop_movables *movables;
1804 int threshold;
1805 int insn_count;
1807 struct loop_regs *regs = LOOP_REGS (loop);
1808 int nregs = regs->num;
1809 rtx new_start = 0;
1810 struct movable *m;
1811 rtx p;
1812 rtx loop_start = loop->start;
1813 rtx loop_end = loop->end;
1814 /* Map of pseudo-register replacements to handle combining
1815 when we move several insns that load the same value
1816 into different pseudo-registers. */
1817 rtx *reg_map = (rtx *) xcalloc (nregs, sizeof (rtx));
1818 char *already_moved = (char *) xcalloc (nregs, sizeof (char));
1820 for (m = movables->head; m; m = m->next)
1822 /* Describe this movable insn. */
1824 if (loop_dump_stream)
1826 fprintf (loop_dump_stream, "Insn %d: regno %d (life %d), ",
1827 INSN_UID (m->insn), m->regno, m->lifetime);
1828 if (m->consec > 0)
1829 fprintf (loop_dump_stream, "consec %d, ", m->consec);
1830 if (m->cond)
1831 fprintf (loop_dump_stream, "cond ");
1832 if (m->force)
1833 fprintf (loop_dump_stream, "force ");
1834 if (m->global)
1835 fprintf (loop_dump_stream, "global ");
1836 if (m->done)
1837 fprintf (loop_dump_stream, "done ");
1838 if (m->move_insn)
1839 fprintf (loop_dump_stream, "move-insn ");
1840 if (m->match)
1841 fprintf (loop_dump_stream, "matches %d ",
1842 INSN_UID (m->match->insn));
1843 if (m->forces)
1844 fprintf (loop_dump_stream, "forces %d ",
1845 INSN_UID (m->forces->insn));
1848 /* Ignore the insn if it's already done (it matched something else).
1849 Otherwise, see if it is now safe to move. */
1851 if (!m->done
1852 && (! m->cond
1853 || (1 == loop_invariant_p (loop, m->set_src)
1854 && (m->dependencies == 0
1855 || 1 == loop_invariant_p (loop, m->dependencies))
1856 && (m->consec == 0
1857 || 1 == consec_sets_invariant_p (loop, m->set_dest,
1858 m->consec + 1,
1859 m->insn))))
1860 && (! m->forces || m->forces->done))
1862 int regno;
1863 rtx p;
1864 int savings = m->savings;
1866 /* We have an insn that is safe to move.
1867 Compute its desirability. */
1869 p = m->insn;
1870 regno = m->regno;
1872 if (loop_dump_stream)
1873 fprintf (loop_dump_stream, "savings %d ", savings);
1875 if (regs->array[regno].moved_once && loop_dump_stream)
1876 fprintf (loop_dump_stream, "halved since already moved ");
1878 /* An insn MUST be moved if we already moved something else
1879 which is safe only if this one is moved too: that is,
1880 if already_moved[REGNO] is nonzero. */
1882 /* An insn is desirable to move if the new lifetime of the
1883 register is no more than THRESHOLD times the old lifetime.
1884 If it's not desirable, it means the loop is so big
1885 that moving won't speed things up much,
1886 and it is liable to make register usage worse. */
1888 /* It is also desirable to move if it can be moved at no
1889 extra cost because something else was already moved. */
1891 if (already_moved[regno]
1892 || flag_move_all_movables
1893 || (threshold * savings * m->lifetime) >=
1894 (regs->array[regno].moved_once ? insn_count * 2 : insn_count)
1895 || (m->forces && m->forces->done
1896 && regs->array[m->forces->regno].n_times_set == 1))
1898 int count;
1899 struct movable *m1;
1900 rtx first = NULL_RTX;
1901 rtx newreg = NULL_RTX;
1903 if (m->insert_temp)
1904 newreg = gen_reg_rtx (GET_MODE (m->set_dest));
1906 /* Now move the insns that set the reg. */
1908 if (m->partial && m->match)
1910 rtx newpat, i1;
1911 rtx r1, r2;
1912 /* Find the end of this chain of matching regs.
1913 Thus, we load each reg in the chain from that one reg.
1914 And that reg is loaded with 0 directly,
1915 since it has ->match == 0. */
1916 for (m1 = m; m1->match; m1 = m1->match);
1917 newpat = gen_move_insn (SET_DEST (PATTERN (m->insn)),
1918 SET_DEST (PATTERN (m1->insn)));
1919 i1 = loop_insn_hoist (loop, newpat);
1921 /* Mark the moved, invariant reg as being allowed to
1922 share a hard reg with the other matching invariant. */
1923 REG_NOTES (i1) = REG_NOTES (m->insn);
1924 r1 = SET_DEST (PATTERN (m->insn));
1925 r2 = SET_DEST (PATTERN (m1->insn));
1926 regs_may_share
1927 = gen_rtx_EXPR_LIST (VOIDmode, r1,
1928 gen_rtx_EXPR_LIST (VOIDmode, r2,
1929 regs_may_share));
1930 delete_insn (m->insn);
1932 if (new_start == 0)
1933 new_start = i1;
1935 if (loop_dump_stream)
1936 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
1938 /* If we are to re-generate the item being moved with a
1939 new move insn, first delete what we have and then emit
1940 the move insn before the loop. */
1941 else if (m->move_insn)
1943 rtx i1, temp, seq;
1945 for (count = m->consec; count >= 0; count--)
1947 /* If this is the first insn of a library call sequence,
1948 something is very wrong. */
1949 if (GET_CODE (p) != NOTE
1950 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
1951 abort ();
1953 /* If this is the last insn of a libcall sequence, then
1954 delete every insn in the sequence except the last.
1955 The last insn is handled in the normal manner. */
1956 if (GET_CODE (p) != NOTE
1957 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
1959 temp = XEXP (temp, 0);
1960 while (temp != p)
1961 temp = delete_insn (temp);
1964 temp = p;
1965 p = delete_insn (p);
1967 /* simplify_giv_expr expects that it can walk the insns
1968 at m->insn forwards and see this old sequence we are
1969 tossing here. delete_insn does preserve the next
1970 pointers, but when we skip over a NOTE we must fix
1971 it up. Otherwise that code walks into the non-deleted
1972 insn stream. */
1973 while (p && GET_CODE (p) == NOTE)
1974 p = NEXT_INSN (temp) = NEXT_INSN (p);
1976 if (m->insert_temp)
1978 /* Replace the original insn with a move from
1979 our newly created temp. */
1980 start_sequence ();
1981 emit_move_insn (m->set_dest, newreg);
1982 seq = get_insns ();
1983 end_sequence ();
1984 emit_insn_before (seq, p);
1988 start_sequence ();
1989 emit_move_insn (m->insert_temp ? newreg : m->set_dest,
1990 m->set_src);
1991 seq = get_insns ();
1992 end_sequence ();
1994 add_label_notes (m->set_src, seq);
1996 i1 = loop_insn_hoist (loop, seq);
1997 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
1998 set_unique_reg_note (i1,
1999 m->is_equiv ? REG_EQUIV : REG_EQUAL,
2000 m->set_src);
2002 if (loop_dump_stream)
2003 fprintf (loop_dump_stream, " moved to %d", INSN_UID (i1));
2005 /* The more regs we move, the less we like moving them. */
2006 threshold -= 3;
2008 else
2010 for (count = m->consec; count >= 0; count--)
2012 rtx i1, temp;
2014 /* If first insn of libcall sequence, skip to end. */
2015 /* Do this at start of loop, since p is guaranteed to
2016 be an insn here. */
2017 if (GET_CODE (p) != NOTE
2018 && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
2019 p = XEXP (temp, 0);
2021 /* If last insn of libcall sequence, move all
2022 insns except the last before the loop. The last
2023 insn is handled in the normal manner. */
2024 if (GET_CODE (p) != NOTE
2025 && (temp = find_reg_note (p, REG_RETVAL, NULL_RTX)))
2027 rtx fn_address = 0;
2028 rtx fn_reg = 0;
2029 rtx fn_address_insn = 0;
2031 first = 0;
2032 for (temp = XEXP (temp, 0); temp != p;
2033 temp = NEXT_INSN (temp))
2035 rtx body;
2036 rtx n;
2037 rtx next;
2039 if (GET_CODE (temp) == NOTE)
2040 continue;
2042 body = PATTERN (temp);
2044 /* Find the next insn after TEMP,
2045 not counting USE or NOTE insns. */
2046 for (next = NEXT_INSN (temp); next != p;
2047 next = NEXT_INSN (next))
2048 if (! (GET_CODE (next) == INSN
2049 && GET_CODE (PATTERN (next)) == USE)
2050 && GET_CODE (next) != NOTE)
2051 break;
2053 /* If that is the call, this may be the insn
2054 that loads the function address.
2056 Extract the function address from the insn
2057 that loads it into a register.
2058 If this insn was cse'd, we get incorrect code.
2060 So emit a new move insn that copies the
2061 function address into the register that the
2062 call insn will use. flow.c will delete any
2063 redundant stores that we have created. */
2064 if (GET_CODE (next) == CALL_INSN
2065 && GET_CODE (body) == SET
2066 && GET_CODE (SET_DEST (body)) == REG
2067 && (n = find_reg_note (temp, REG_EQUAL,
2068 NULL_RTX)))
2070 fn_reg = SET_SRC (body);
2071 if (GET_CODE (fn_reg) != REG)
2072 fn_reg = SET_DEST (body);
2073 fn_address = XEXP (n, 0);
2074 fn_address_insn = temp;
2076 /* We have the call insn.
2077 If it uses the register we suspect it might,
2078 load it with the correct address directly. */
2079 if (GET_CODE (temp) == CALL_INSN
2080 && fn_address != 0
2081 && reg_referenced_p (fn_reg, body))
2082 loop_insn_emit_after (loop, 0, fn_address_insn,
2083 gen_move_insn
2084 (fn_reg, fn_address));
2086 if (GET_CODE (temp) == CALL_INSN)
2088 i1 = loop_call_insn_hoist (loop, body);
2089 /* Because the USAGE information potentially
2090 contains objects other than hard registers
2091 we need to copy it. */
2092 if (CALL_INSN_FUNCTION_USAGE (temp))
2093 CALL_INSN_FUNCTION_USAGE (i1)
2094 = copy_rtx (CALL_INSN_FUNCTION_USAGE (temp));
2096 else
2097 i1 = loop_insn_hoist (loop, body);
2098 if (first == 0)
2099 first = i1;
2100 if (temp == fn_address_insn)
2101 fn_address_insn = i1;
2102 REG_NOTES (i1) = REG_NOTES (temp);
2103 REG_NOTES (temp) = NULL;
2104 delete_insn (temp);
2106 if (new_start == 0)
2107 new_start = first;
2109 if (m->savemode != VOIDmode)
2111 /* P sets REG to zero; but we should clear only
2112 the bits that are not covered by the mode
2113 m->savemode. */
2114 rtx reg = m->set_dest;
2115 rtx sequence;
2116 rtx tem;
2118 start_sequence ();
2119 tem = expand_simple_binop
2120 (GET_MODE (reg), AND, reg,
2121 GEN_INT ((((HOST_WIDE_INT) 1
2122 << GET_MODE_BITSIZE (m->savemode)))
2123 - 1),
2124 reg, 1, OPTAB_LIB_WIDEN);
2125 if (tem == 0)
2126 abort ();
2127 if (tem != reg)
2128 emit_move_insn (reg, tem);
2129 sequence = get_insns ();
2130 end_sequence ();
2131 i1 = loop_insn_hoist (loop, sequence);
2133 else if (GET_CODE (p) == CALL_INSN)
2135 i1 = loop_call_insn_hoist (loop, PATTERN (p));
2136 /* Because the USAGE information potentially
2137 contains objects other than hard registers
2138 we need to copy it. */
2139 if (CALL_INSN_FUNCTION_USAGE (p))
2140 CALL_INSN_FUNCTION_USAGE (i1)
2141 = copy_rtx (CALL_INSN_FUNCTION_USAGE (p));
2143 else if (count == m->consec && m->move_insn_first)
2145 rtx seq;
2146 /* The SET_SRC might not be invariant, so we must
2147 use the REG_EQUAL note. */
2148 start_sequence ();
2149 emit_move_insn (m->set_dest, m->set_src);
2150 seq = get_insns ();
2151 end_sequence ();
2153 add_label_notes (m->set_src, seq);
2155 i1 = loop_insn_hoist (loop, seq);
2156 if (! find_reg_note (i1, REG_EQUAL, NULL_RTX))
2157 set_unique_reg_note (i1, m->is_equiv ? REG_EQUIV
2158 : REG_EQUAL, m->set_src);
2160 else if (m->insert_temp)
2162 rtx *reg_map2 = (rtx *) xcalloc (REGNO (newreg),
2163 sizeof(rtx));
2164 reg_map2 [m->regno] = newreg;
2166 i1 = loop_insn_hoist (loop, copy_rtx (PATTERN (p)));
2167 replace_regs (i1, reg_map2, REGNO (newreg), 1);
2168 free (reg_map2);
2170 else
2171 i1 = loop_insn_hoist (loop, PATTERN (p));
2173 if (REG_NOTES (i1) == 0)
2175 REG_NOTES (i1) = REG_NOTES (p);
2176 REG_NOTES (p) = NULL;
2178 /* If there is a REG_EQUAL note present whose value
2179 is not loop invariant, then delete it, since it
2180 may cause problems with later optimization passes.
2181 It is possible for cse to create such notes
2182 like this as a result of record_jump_cond. */
2184 if ((temp = find_reg_note (i1, REG_EQUAL, NULL_RTX))
2185 && ! loop_invariant_p (loop, XEXP (temp, 0)))
2186 remove_note (i1, temp);
2189 if (new_start == 0)
2190 new_start = i1;
2192 if (loop_dump_stream)
2193 fprintf (loop_dump_stream, " moved to %d",
2194 INSN_UID (i1));
2196 /* If library call, now fix the REG_NOTES that contain
2197 insn pointers, namely REG_LIBCALL on FIRST
2198 and REG_RETVAL on I1. */
2199 if ((temp = find_reg_note (i1, REG_RETVAL, NULL_RTX)))
2201 XEXP (temp, 0) = first;
2202 temp = find_reg_note (first, REG_LIBCALL, NULL_RTX);
2203 XEXP (temp, 0) = i1;
2206 temp = p;
2207 delete_insn (p);
2208 p = NEXT_INSN (p);
2210 /* simplify_giv_expr expects that it can walk the insns
2211 at m->insn forwards and see this old sequence we are
2212 tossing here. delete_insn does preserve the next
2213 pointers, but when we skip over a NOTE we must fix
2214 it up. Otherwise that code walks into the non-deleted
2215 insn stream. */
2216 while (p && GET_CODE (p) == NOTE)
2217 p = NEXT_INSN (temp) = NEXT_INSN (p);
2219 if (m->insert_temp)
2221 rtx seq;
2222 /* Replace the original insn with a move from
2223 our newly created temp. */
2224 start_sequence ();
2225 emit_move_insn (m->set_dest, newreg);
2226 seq = get_insns ();
2227 end_sequence ();
2228 emit_insn_before (seq, p);
2232 /* The more regs we move, the less we like moving them. */
2233 threshold -= 3;
2236 m->done = 1;
2238 if (!m->insert_temp)
2240 /* Any other movable that loads the same register
2241 MUST be moved. */
2242 already_moved[regno] = 1;
2244 /* This reg has been moved out of one loop. */
2245 regs->array[regno].moved_once = 1;
2247 /* The reg set here is now invariant. */
2248 if (! m->partial)
2250 int i;
2251 for (i = 0; i < LOOP_REGNO_NREGS (regno, m->set_dest); i++)
2252 regs->array[regno+i].set_in_loop = 0;
2255 /* Change the length-of-life info for the register
2256 to say it lives at least the full length of this loop.
2257 This will help guide optimizations in outer loops. */
2259 if (REGNO_FIRST_LUID (regno) > INSN_LUID (loop_start))
2260 /* This is the old insn before all the moved insns.
2261 We can't use the moved insn because it is out of range
2262 in uid_luid. Only the old insns have luids. */
2263 REGNO_FIRST_UID (regno) = INSN_UID (loop_start);
2264 if (REGNO_LAST_LUID (regno) < INSN_LUID (loop_end))
2265 REGNO_LAST_UID (regno) = INSN_UID (loop_end);
2268 /* Combine with this moved insn any other matching movables. */
2270 if (! m->partial)
2271 for (m1 = movables->head; m1; m1 = m1->next)
2272 if (m1->match == m)
2274 rtx temp;
2276 /* Schedule the reg loaded by M1
2277 for replacement so that shares the reg of M.
2278 If the modes differ (only possible in restricted
2279 circumstances, make a SUBREG.
2281 Note this assumes that the target dependent files
2282 treat REG and SUBREG equally, including within
2283 GO_IF_LEGITIMATE_ADDRESS and in all the
2284 predicates since we never verify that replacing the
2285 original register with a SUBREG results in a
2286 recognizable insn. */
2287 if (GET_MODE (m->set_dest) == GET_MODE (m1->set_dest))
2288 reg_map[m1->regno] = m->set_dest;
2289 else
2290 reg_map[m1->regno]
2291 = gen_lowpart_common (GET_MODE (m1->set_dest),
2292 m->set_dest);
2294 /* Get rid of the matching insn
2295 and prevent further processing of it. */
2296 m1->done = 1;
2298 /* if library call, delete all insns. */
2299 if ((temp = find_reg_note (m1->insn, REG_RETVAL,
2300 NULL_RTX)))
2301 delete_insn_chain (XEXP (temp, 0), m1->insn);
2302 else
2303 delete_insn (m1->insn);
2305 /* Any other movable that loads the same register
2306 MUST be moved. */
2307 already_moved[m1->regno] = 1;
2309 /* The reg merged here is now invariant,
2310 if the reg it matches is invariant. */
2311 if (! m->partial)
2313 int i;
2314 for (i = 0;
2315 i < LOOP_REGNO_NREGS (regno, m1->set_dest);
2316 i++)
2317 regs->array[m1->regno+i].set_in_loop = 0;
2321 else if (loop_dump_stream)
2322 fprintf (loop_dump_stream, "not desirable");
2324 else if (loop_dump_stream && !m->match)
2325 fprintf (loop_dump_stream, "not safe");
2327 if (loop_dump_stream)
2328 fprintf (loop_dump_stream, "\n");
2331 if (new_start == 0)
2332 new_start = loop_start;
2334 /* Go through all the instructions in the loop, making
2335 all the register substitutions scheduled in REG_MAP. */
2336 for (p = new_start; p != loop_end; p = NEXT_INSN (p))
2337 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
2338 || GET_CODE (p) == CALL_INSN)
2340 replace_regs (PATTERN (p), reg_map, nregs, 0);
2341 replace_regs (REG_NOTES (p), reg_map, nregs, 0);
2342 INSN_CODE (p) = -1;
2345 /* Clean up. */
2346 free (reg_map);
2347 free (already_moved);
2351 static void
2352 loop_movables_add (movables, m)
2353 struct loop_movables *movables;
2354 struct movable *m;
2356 if (movables->head == 0)
2357 movables->head = m;
2358 else
2359 movables->last->next = m;
2360 movables->last = m;
2364 static void
2365 loop_movables_free (movables)
2366 struct loop_movables *movables;
2368 struct movable *m;
2369 struct movable *m_next;
2371 for (m = movables->head; m; m = m_next)
2373 m_next = m->next;
2374 free (m);
2378 #if 0
2379 /* Scan X and replace the address of any MEM in it with ADDR.
2380 REG is the address that MEM should have before the replacement. */
2382 static void
2383 replace_call_address (x, reg, addr)
2384 rtx x, reg, addr;
2386 enum rtx_code code;
2387 int i;
2388 const char *fmt;
2390 if (x == 0)
2391 return;
2392 code = GET_CODE (x);
2393 switch (code)
2395 case PC:
2396 case CC0:
2397 case CONST_INT:
2398 case CONST_DOUBLE:
2399 case CONST:
2400 case SYMBOL_REF:
2401 case LABEL_REF:
2402 case REG:
2403 return;
2405 case SET:
2406 /* Short cut for very common case. */
2407 replace_call_address (XEXP (x, 1), reg, addr);
2408 return;
2410 case CALL:
2411 /* Short cut for very common case. */
2412 replace_call_address (XEXP (x, 0), reg, addr);
2413 return;
2415 case MEM:
2416 /* If this MEM uses a reg other than the one we expected,
2417 something is wrong. */
2418 if (XEXP (x, 0) != reg)
2419 abort ();
2420 XEXP (x, 0) = addr;
2421 return;
2423 default:
2424 break;
2427 fmt = GET_RTX_FORMAT (code);
2428 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2430 if (fmt[i] == 'e')
2431 replace_call_address (XEXP (x, i), reg, addr);
2432 else if (fmt[i] == 'E')
2434 int j;
2435 for (j = 0; j < XVECLEN (x, i); j++)
2436 replace_call_address (XVECEXP (x, i, j), reg, addr);
2440 #endif
2442 /* Return the number of memory refs to addresses that vary
2443 in the rtx X. */
2445 static int
2446 count_nonfixed_reads (loop, x)
2447 const struct loop *loop;
2448 rtx x;
2450 enum rtx_code code;
2451 int i;
2452 const char *fmt;
2453 int value;
2455 if (x == 0)
2456 return 0;
2458 code = GET_CODE (x);
2459 switch (code)
2461 case PC:
2462 case CC0:
2463 case CONST_INT:
2464 case CONST_DOUBLE:
2465 case CONST:
2466 case SYMBOL_REF:
2467 case LABEL_REF:
2468 case REG:
2469 return 0;
2471 case MEM:
2472 return ((loop_invariant_p (loop, XEXP (x, 0)) != 1)
2473 + count_nonfixed_reads (loop, XEXP (x, 0)));
2475 default:
2476 break;
2479 value = 0;
2480 fmt = GET_RTX_FORMAT (code);
2481 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
2483 if (fmt[i] == 'e')
2484 value += count_nonfixed_reads (loop, XEXP (x, i));
2485 if (fmt[i] == 'E')
2487 int j;
2488 for (j = 0; j < XVECLEN (x, i); j++)
2489 value += count_nonfixed_reads (loop, XVECEXP (x, i, j));
2492 return value;
2495 /* Scan a loop setting the elements `cont', `vtop', `loops_enclosed',
2496 `has_call', `has_nonconst_call', `has_volatile', `has_tablejump',
2497 `unknown_address_altered', `unknown_constant_address_altered', and
2498 `num_mem_sets' in LOOP. Also, fill in the array `mems' and the
2499 list `store_mems' in LOOP. */
2501 static void
2502 prescan_loop (loop)
2503 struct loop *loop;
2505 int level = 1;
2506 rtx insn;
2507 struct loop_info *loop_info = LOOP_INFO (loop);
2508 rtx start = loop->start;
2509 rtx end = loop->end;
2510 /* The label after END. Jumping here is just like falling off the
2511 end of the loop. We use next_nonnote_insn instead of next_label
2512 as a hedge against the (pathological) case where some actual insn
2513 might end up between the two. */
2514 rtx exit_target = next_nonnote_insn (end);
2516 loop_info->has_indirect_jump = indirect_jump_in_function;
2517 loop_info->pre_header_has_call = 0;
2518 loop_info->has_call = 0;
2519 loop_info->has_nonconst_call = 0;
2520 loop_info->has_prefetch = 0;
2521 loop_info->has_volatile = 0;
2522 loop_info->has_tablejump = 0;
2523 loop_info->has_multiple_exit_targets = 0;
2524 loop->level = 1;
2526 loop_info->unknown_address_altered = 0;
2527 loop_info->unknown_constant_address_altered = 0;
2528 loop_info->store_mems = NULL_RTX;
2529 loop_info->first_loop_store_insn = NULL_RTX;
2530 loop_info->mems_idx = 0;
2531 loop_info->num_mem_sets = 0;
2532 /* If loop opts run twice, this was set on 1st pass for 2nd. */
2533 loop_info->preconditioned = NOTE_PRECONDITIONED (end);
2535 for (insn = start; insn && GET_CODE (insn) != CODE_LABEL;
2536 insn = PREV_INSN (insn))
2538 if (GET_CODE (insn) == CALL_INSN)
2540 loop_info->pre_header_has_call = 1;
2541 break;
2545 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2546 insn = NEXT_INSN (insn))
2548 switch (GET_CODE (insn))
2550 case NOTE:
2551 if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_BEG)
2553 ++level;
2554 /* Count number of loops contained in this one. */
2555 loop->level++;
2557 else if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_LOOP_END)
2558 --level;
2559 break;
2561 case CALL_INSN:
2562 if (! CONST_OR_PURE_CALL_P (insn))
2564 loop_info->unknown_address_altered = 1;
2565 loop_info->has_nonconst_call = 1;
2567 else if (pure_call_p (insn))
2568 loop_info->has_nonconst_call = 1;
2569 loop_info->has_call = 1;
2570 if (can_throw_internal (insn))
2571 loop_info->has_multiple_exit_targets = 1;
2572 break;
2574 case JUMP_INSN:
2575 if (! loop_info->has_multiple_exit_targets)
2577 rtx set = pc_set (insn);
2579 if (set)
2581 rtx src = SET_SRC (set);
2582 rtx label1, label2;
2584 if (GET_CODE (src) == IF_THEN_ELSE)
2586 label1 = XEXP (src, 1);
2587 label2 = XEXP (src, 2);
2589 else
2591 label1 = src;
2592 label2 = NULL_RTX;
2597 if (label1 && label1 != pc_rtx)
2599 if (GET_CODE (label1) != LABEL_REF)
2601 /* Something tricky. */
2602 loop_info->has_multiple_exit_targets = 1;
2603 break;
2605 else if (XEXP (label1, 0) != exit_target
2606 && LABEL_OUTSIDE_LOOP_P (label1))
2608 /* A jump outside the current loop. */
2609 loop_info->has_multiple_exit_targets = 1;
2610 break;
2614 label1 = label2;
2615 label2 = NULL_RTX;
2617 while (label1);
2619 else
2621 /* A return, or something tricky. */
2622 loop_info->has_multiple_exit_targets = 1;
2625 /* FALLTHRU */
2627 case INSN:
2628 if (volatile_refs_p (PATTERN (insn)))
2629 loop_info->has_volatile = 1;
2631 if (GET_CODE (insn) == JUMP_INSN
2632 && (GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC
2633 || GET_CODE (PATTERN (insn)) == ADDR_VEC))
2634 loop_info->has_tablejump = 1;
2636 note_stores (PATTERN (insn), note_addr_stored, loop_info);
2637 if (! loop_info->first_loop_store_insn && loop_info->store_mems)
2638 loop_info->first_loop_store_insn = insn;
2640 if (flag_non_call_exceptions && can_throw_internal (insn))
2641 loop_info->has_multiple_exit_targets = 1;
2642 break;
2644 default:
2645 break;
2649 /* Now, rescan the loop, setting up the LOOP_MEMS array. */
2650 if (/* An exception thrown by a called function might land us
2651 anywhere. */
2652 ! loop_info->has_nonconst_call
2653 /* We don't want loads for MEMs moved to a location before the
2654 one at which their stack memory becomes allocated. (Note
2655 that this is not a problem for malloc, etc., since those
2656 require actual function calls. */
2657 && ! current_function_calls_alloca
2658 /* There are ways to leave the loop other than falling off the
2659 end. */
2660 && ! loop_info->has_multiple_exit_targets)
2661 for (insn = NEXT_INSN (start); insn != NEXT_INSN (end);
2662 insn = NEXT_INSN (insn))
2663 for_each_rtx (&insn, insert_loop_mem, loop_info);
2665 /* BLKmode MEMs are added to LOOP_STORE_MEM as necessary so
2666 that loop_invariant_p and load_mems can use true_dependence
2667 to determine what is really clobbered. */
2668 if (loop_info->unknown_address_altered)
2670 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2672 loop_info->store_mems
2673 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2675 if (loop_info->unknown_constant_address_altered)
2677 rtx mem = gen_rtx_MEM (BLKmode, const0_rtx);
2679 RTX_UNCHANGING_P (mem) = 1;
2680 loop_info->store_mems
2681 = gen_rtx_EXPR_LIST (VOIDmode, mem, loop_info->store_mems);
2685 /* Invalidate all loops containing LABEL. */
2687 static void
2688 invalidate_loops_containing_label (label)
2689 rtx label;
2691 struct loop *loop;
2692 for (loop = uid_loop[INSN_UID (label)]; loop; loop = loop->outer)
2693 loop->invalid = 1;
2696 /* Scan the function looking for loops. Record the start and end of each loop.
2697 Also mark as invalid loops any loops that contain a setjmp or are branched
2698 to from outside the loop. */
2700 static void
2701 find_and_verify_loops (f, loops)
2702 rtx f;
2703 struct loops *loops;
2705 rtx insn;
2706 rtx label;
2707 int num_loops;
2708 struct loop *current_loop;
2709 struct loop *next_loop;
2710 struct loop *loop;
2712 num_loops = loops->num;
2714 compute_luids (f, NULL_RTX, 0);
2716 /* If there are jumps to undefined labels,
2717 treat them as jumps out of any/all loops.
2718 This also avoids writing past end of tables when there are no loops. */
2719 uid_loop[0] = NULL;
2721 /* Find boundaries of loops, mark which loops are contained within
2722 loops, and invalidate loops that have setjmp. */
2724 num_loops = 0;
2725 current_loop = NULL;
2726 for (insn = f; insn; insn = NEXT_INSN (insn))
2728 if (GET_CODE (insn) == NOTE)
2729 switch (NOTE_LINE_NUMBER (insn))
2731 case NOTE_INSN_LOOP_BEG:
2732 next_loop = loops->array + num_loops;
2733 next_loop->num = num_loops;
2734 num_loops++;
2735 next_loop->start = insn;
2736 next_loop->outer = current_loop;
2737 current_loop = next_loop;
2738 break;
2740 case NOTE_INSN_LOOP_CONT:
2741 current_loop->cont = insn;
2742 break;
2744 case NOTE_INSN_LOOP_VTOP:
2745 current_loop->vtop = insn;
2746 break;
2748 case NOTE_INSN_LOOP_END:
2749 if (! current_loop)
2750 abort ();
2752 current_loop->end = insn;
2753 current_loop = current_loop->outer;
2754 break;
2756 default:
2757 break;
2760 if (GET_CODE (insn) == CALL_INSN
2761 && find_reg_note (insn, REG_SETJMP, NULL))
2763 /* In this case, we must invalidate our current loop and any
2764 enclosing loop. */
2765 for (loop = current_loop; loop; loop = loop->outer)
2767 loop->invalid = 1;
2768 if (loop_dump_stream)
2769 fprintf (loop_dump_stream,
2770 "\nLoop at %d ignored due to setjmp.\n",
2771 INSN_UID (loop->start));
2775 /* Note that this will mark the NOTE_INSN_LOOP_END note as being in the
2776 enclosing loop, but this doesn't matter. */
2777 uid_loop[INSN_UID (insn)] = current_loop;
2780 /* Any loop containing a label used in an initializer must be invalidated,
2781 because it can be jumped into from anywhere. */
2782 for (label = forced_labels; label; label = XEXP (label, 1))
2783 invalidate_loops_containing_label (XEXP (label, 0));
2785 /* Any loop containing a label used for an exception handler must be
2786 invalidated, because it can be jumped into from anywhere. */
2787 for_each_eh_label (invalidate_loops_containing_label);
2789 /* Now scan all insn's in the function. If any JUMP_INSN branches into a
2790 loop that it is not contained within, that loop is marked invalid.
2791 If any INSN or CALL_INSN uses a label's address, then the loop containing
2792 that label is marked invalid, because it could be jumped into from
2793 anywhere.
2795 Also look for blocks of code ending in an unconditional branch that
2796 exits the loop. If such a block is surrounded by a conditional
2797 branch around the block, move the block elsewhere (see below) and
2798 invert the jump to point to the code block. This may eliminate a
2799 label in our loop and will simplify processing by both us and a
2800 possible second cse pass. */
2802 for (insn = f; insn; insn = NEXT_INSN (insn))
2803 if (INSN_P (insn))
2805 struct loop *this_loop = uid_loop[INSN_UID (insn)];
2807 if (GET_CODE (insn) == INSN || GET_CODE (insn) == CALL_INSN)
2809 rtx note = find_reg_note (insn, REG_LABEL, NULL_RTX);
2810 if (note)
2811 invalidate_loops_containing_label (XEXP (note, 0));
2814 if (GET_CODE (insn) != JUMP_INSN)
2815 continue;
2817 mark_loop_jump (PATTERN (insn), this_loop);
2819 /* See if this is an unconditional branch outside the loop. */
2820 if (this_loop
2821 && (GET_CODE (PATTERN (insn)) == RETURN
2822 || (any_uncondjump_p (insn)
2823 && onlyjump_p (insn)
2824 && (uid_loop[INSN_UID (JUMP_LABEL (insn))]
2825 != this_loop)))
2826 && get_max_uid () < max_uid_for_loop)
2828 rtx p;
2829 rtx our_next = next_real_insn (insn);
2830 rtx last_insn_to_move = NEXT_INSN (insn);
2831 struct loop *dest_loop;
2832 struct loop *outer_loop = NULL;
2834 /* Go backwards until we reach the start of the loop, a label,
2835 or a JUMP_INSN. */
2836 for (p = PREV_INSN (insn);
2837 GET_CODE (p) != CODE_LABEL
2838 && ! (GET_CODE (p) == NOTE
2839 && NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
2840 && GET_CODE (p) != JUMP_INSN;
2841 p = PREV_INSN (p))
2844 /* Check for the case where we have a jump to an inner nested
2845 loop, and do not perform the optimization in that case. */
2847 if (JUMP_LABEL (insn))
2849 dest_loop = uid_loop[INSN_UID (JUMP_LABEL (insn))];
2850 if (dest_loop)
2852 for (outer_loop = dest_loop; outer_loop;
2853 outer_loop = outer_loop->outer)
2854 if (outer_loop == this_loop)
2855 break;
2859 /* Make sure that the target of P is within the current loop. */
2861 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
2862 && uid_loop[INSN_UID (JUMP_LABEL (p))] != this_loop)
2863 outer_loop = this_loop;
2865 /* If we stopped on a JUMP_INSN to the next insn after INSN,
2866 we have a block of code to try to move.
2868 We look backward and then forward from the target of INSN
2869 to find a BARRIER at the same loop depth as the target.
2870 If we find such a BARRIER, we make a new label for the start
2871 of the block, invert the jump in P and point it to that label,
2872 and move the block of code to the spot we found. */
2874 if (! outer_loop
2875 && GET_CODE (p) == JUMP_INSN
2876 && JUMP_LABEL (p) != 0
2877 /* Just ignore jumps to labels that were never emitted.
2878 These always indicate compilation errors. */
2879 && INSN_UID (JUMP_LABEL (p)) != 0
2880 && any_condjump_p (p) && onlyjump_p (p)
2881 && next_real_insn (JUMP_LABEL (p)) == our_next
2882 /* If it's not safe to move the sequence, then we
2883 mustn't try. */
2884 && insns_safe_to_move_p (p, NEXT_INSN (insn),
2885 &last_insn_to_move))
2887 rtx target
2888 = JUMP_LABEL (insn) ? JUMP_LABEL (insn) : get_last_insn ();
2889 struct loop *target_loop = uid_loop[INSN_UID (target)];
2890 rtx loc, loc2;
2891 rtx tmp;
2893 /* Search for possible garbage past the conditional jumps
2894 and look for the last barrier. */
2895 for (tmp = last_insn_to_move;
2896 tmp && GET_CODE (tmp) != CODE_LABEL; tmp = NEXT_INSN (tmp))
2897 if (GET_CODE (tmp) == BARRIER)
2898 last_insn_to_move = tmp;
2900 for (loc = target; loc; loc = PREV_INSN (loc))
2901 if (GET_CODE (loc) == BARRIER
2902 /* Don't move things inside a tablejump. */
2903 && ((loc2 = next_nonnote_insn (loc)) == 0
2904 || GET_CODE (loc2) != CODE_LABEL
2905 || (loc2 = next_nonnote_insn (loc2)) == 0
2906 || GET_CODE (loc2) != JUMP_INSN
2907 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2908 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2909 && uid_loop[INSN_UID (loc)] == target_loop)
2910 break;
2912 if (loc == 0)
2913 for (loc = target; loc; loc = NEXT_INSN (loc))
2914 if (GET_CODE (loc) == BARRIER
2915 /* Don't move things inside a tablejump. */
2916 && ((loc2 = next_nonnote_insn (loc)) == 0
2917 || GET_CODE (loc2) != CODE_LABEL
2918 || (loc2 = next_nonnote_insn (loc2)) == 0
2919 || GET_CODE (loc2) != JUMP_INSN
2920 || (GET_CODE (PATTERN (loc2)) != ADDR_VEC
2921 && GET_CODE (PATTERN (loc2)) != ADDR_DIFF_VEC))
2922 && uid_loop[INSN_UID (loc)] == target_loop)
2923 break;
2925 if (loc)
2927 rtx cond_label = JUMP_LABEL (p);
2928 rtx new_label = get_label_after (p);
2930 /* Ensure our label doesn't go away. */
2931 LABEL_NUSES (cond_label)++;
2933 /* Verify that uid_loop is large enough and that
2934 we can invert P. */
2935 if (invert_jump (p, new_label, 1))
2937 rtx q, r;
2939 /* If no suitable BARRIER was found, create a suitable
2940 one before TARGET. Since TARGET is a fall through
2941 path, we'll need to insert a jump around our block
2942 and add a BARRIER before TARGET.
2944 This creates an extra unconditional jump outside
2945 the loop. However, the benefits of removing rarely
2946 executed instructions from inside the loop usually
2947 outweighs the cost of the extra unconditional jump
2948 outside the loop. */
2949 if (loc == 0)
2951 rtx temp;
2953 temp = gen_jump (JUMP_LABEL (insn));
2954 temp = emit_jump_insn_before (temp, target);
2955 JUMP_LABEL (temp) = JUMP_LABEL (insn);
2956 LABEL_NUSES (JUMP_LABEL (insn))++;
2957 loc = emit_barrier_before (target);
2960 /* Include the BARRIER after INSN and copy the
2961 block after LOC. */
2962 if (squeeze_notes (&new_label, &last_insn_to_move))
2963 abort ();
2964 reorder_insns (new_label, last_insn_to_move, loc);
2966 /* All those insns are now in TARGET_LOOP. */
2967 for (q = new_label;
2968 q != NEXT_INSN (last_insn_to_move);
2969 q = NEXT_INSN (q))
2970 uid_loop[INSN_UID (q)] = target_loop;
2972 /* The label jumped to by INSN is no longer a loop
2973 exit. Unless INSN does not have a label (e.g.,
2974 it is a RETURN insn), search loop->exit_labels
2975 to find its label_ref, and remove it. Also turn
2976 off LABEL_OUTSIDE_LOOP_P bit. */
2977 if (JUMP_LABEL (insn))
2979 for (q = 0, r = this_loop->exit_labels;
2981 q = r, r = LABEL_NEXTREF (r))
2982 if (XEXP (r, 0) == JUMP_LABEL (insn))
2984 LABEL_OUTSIDE_LOOP_P (r) = 0;
2985 if (q)
2986 LABEL_NEXTREF (q) = LABEL_NEXTREF (r);
2987 else
2988 this_loop->exit_labels = LABEL_NEXTREF (r);
2989 break;
2992 for (loop = this_loop; loop && loop != target_loop;
2993 loop = loop->outer)
2994 loop->exit_count--;
2996 /* If we didn't find it, then something is
2997 wrong. */
2998 if (! r)
2999 abort ();
3002 /* P is now a jump outside the loop, so it must be put
3003 in loop->exit_labels, and marked as such.
3004 The easiest way to do this is to just call
3005 mark_loop_jump again for P. */
3006 mark_loop_jump (PATTERN (p), this_loop);
3008 /* If INSN now jumps to the insn after it,
3009 delete INSN. */
3010 if (JUMP_LABEL (insn) != 0
3011 && (next_real_insn (JUMP_LABEL (insn))
3012 == next_real_insn (insn)))
3013 delete_related_insns (insn);
3016 /* Continue the loop after where the conditional
3017 branch used to jump, since the only branch insn
3018 in the block (if it still remains) is an inter-loop
3019 branch and hence needs no processing. */
3020 insn = NEXT_INSN (cond_label);
3022 if (--LABEL_NUSES (cond_label) == 0)
3023 delete_related_insns (cond_label);
3025 /* This loop will be continued with NEXT_INSN (insn). */
3026 insn = PREV_INSN (insn);
3033 /* If any label in X jumps to a loop different from LOOP_NUM and any of the
3034 loops it is contained in, mark the target loop invalid.
3036 For speed, we assume that X is part of a pattern of a JUMP_INSN. */
3038 static void
3039 mark_loop_jump (x, loop)
3040 rtx x;
3041 struct loop *loop;
3043 struct loop *dest_loop;
3044 struct loop *outer_loop;
3045 int i;
3047 switch (GET_CODE (x))
3049 case PC:
3050 case USE:
3051 case CLOBBER:
3052 case REG:
3053 case MEM:
3054 case CONST_INT:
3055 case CONST_DOUBLE:
3056 case RETURN:
3057 return;
3059 case CONST:
3060 /* There could be a label reference in here. */
3061 mark_loop_jump (XEXP (x, 0), loop);
3062 return;
3064 case PLUS:
3065 case MINUS:
3066 case MULT:
3067 mark_loop_jump (XEXP (x, 0), loop);
3068 mark_loop_jump (XEXP (x, 1), loop);
3069 return;
3071 case LO_SUM:
3072 /* This may refer to a LABEL_REF or SYMBOL_REF. */
3073 mark_loop_jump (XEXP (x, 1), loop);
3074 return;
3076 case SIGN_EXTEND:
3077 case ZERO_EXTEND:
3078 mark_loop_jump (XEXP (x, 0), loop);
3079 return;
3081 case LABEL_REF:
3082 dest_loop = uid_loop[INSN_UID (XEXP (x, 0))];
3084 /* Link together all labels that branch outside the loop. This
3085 is used by final_[bg]iv_value and the loop unrolling code. Also
3086 mark this LABEL_REF so we know that this branch should predict
3087 false. */
3089 /* A check to make sure the label is not in an inner nested loop,
3090 since this does not count as a loop exit. */
3091 if (dest_loop)
3093 for (outer_loop = dest_loop; outer_loop;
3094 outer_loop = outer_loop->outer)
3095 if (outer_loop == loop)
3096 break;
3098 else
3099 outer_loop = NULL;
3101 if (loop && ! outer_loop)
3103 LABEL_OUTSIDE_LOOP_P (x) = 1;
3104 LABEL_NEXTREF (x) = loop->exit_labels;
3105 loop->exit_labels = x;
3107 for (outer_loop = loop;
3108 outer_loop && outer_loop != dest_loop;
3109 outer_loop = outer_loop->outer)
3110 outer_loop->exit_count++;
3113 /* If this is inside a loop, but not in the current loop or one enclosed
3114 by it, it invalidates at least one loop. */
3116 if (! dest_loop)
3117 return;
3119 /* We must invalidate every nested loop containing the target of this
3120 label, except those that also contain the jump insn. */
3122 for (; dest_loop; dest_loop = dest_loop->outer)
3124 /* Stop when we reach a loop that also contains the jump insn. */
3125 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3126 if (dest_loop == outer_loop)
3127 return;
3129 /* If we get here, we know we need to invalidate a loop. */
3130 if (loop_dump_stream && ! dest_loop->invalid)
3131 fprintf (loop_dump_stream,
3132 "\nLoop at %d ignored due to multiple entry points.\n",
3133 INSN_UID (dest_loop->start));
3135 dest_loop->invalid = 1;
3137 return;
3139 case SET:
3140 /* If this is not setting pc, ignore. */
3141 if (SET_DEST (x) == pc_rtx)
3142 mark_loop_jump (SET_SRC (x), loop);
3143 return;
3145 case IF_THEN_ELSE:
3146 mark_loop_jump (XEXP (x, 1), loop);
3147 mark_loop_jump (XEXP (x, 2), loop);
3148 return;
3150 case PARALLEL:
3151 case ADDR_VEC:
3152 for (i = 0; i < XVECLEN (x, 0); i++)
3153 mark_loop_jump (XVECEXP (x, 0, i), loop);
3154 return;
3156 case ADDR_DIFF_VEC:
3157 for (i = 0; i < XVECLEN (x, 1); i++)
3158 mark_loop_jump (XVECEXP (x, 1, i), loop);
3159 return;
3161 default:
3162 /* Strictly speaking this is not a jump into the loop, only a possible
3163 jump out of the loop. However, we have no way to link the destination
3164 of this jump onto the list of exit labels. To be safe we mark this
3165 loop and any containing loops as invalid. */
3166 if (loop)
3168 for (outer_loop = loop; outer_loop; outer_loop = outer_loop->outer)
3170 if (loop_dump_stream && ! outer_loop->invalid)
3171 fprintf (loop_dump_stream,
3172 "\nLoop at %d ignored due to unknown exit jump.\n",
3173 INSN_UID (outer_loop->start));
3174 outer_loop->invalid = 1;
3177 return;
3181 /* Return nonzero if there is a label in the range from
3182 insn INSN to and including the insn whose luid is END
3183 INSN must have an assigned luid (i.e., it must not have
3184 been previously created by loop.c). */
3186 static int
3187 labels_in_range_p (insn, end)
3188 rtx insn;
3189 int end;
3191 while (insn && INSN_LUID (insn) <= end)
3193 if (GET_CODE (insn) == CODE_LABEL)
3194 return 1;
3195 insn = NEXT_INSN (insn);
3198 return 0;
3201 /* Record that a memory reference X is being set. */
3203 static void
3204 note_addr_stored (x, y, data)
3205 rtx x;
3206 rtx y ATTRIBUTE_UNUSED;
3207 void *data ATTRIBUTE_UNUSED;
3209 struct loop_info *loop_info = data;
3211 if (x == 0 || GET_CODE (x) != MEM)
3212 return;
3214 /* Count number of memory writes.
3215 This affects heuristics in strength_reduce. */
3216 loop_info->num_mem_sets++;
3218 /* BLKmode MEM means all memory is clobbered. */
3219 if (GET_MODE (x) == BLKmode)
3221 if (RTX_UNCHANGING_P (x))
3222 loop_info->unknown_constant_address_altered = 1;
3223 else
3224 loop_info->unknown_address_altered = 1;
3226 return;
3229 loop_info->store_mems = gen_rtx_EXPR_LIST (VOIDmode, x,
3230 loop_info->store_mems);
3233 /* X is a value modified by an INSN that references a biv inside a loop
3234 exit test (ie, X is somehow related to the value of the biv). If X
3235 is a pseudo that is used more than once, then the biv is (effectively)
3236 used more than once. DATA is a pointer to a loop_regs structure. */
3238 static void
3239 note_set_pseudo_multiple_uses (x, y, data)
3240 rtx x;
3241 rtx y ATTRIBUTE_UNUSED;
3242 void *data;
3244 struct loop_regs *regs = (struct loop_regs *) data;
3246 if (x == 0)
3247 return;
3249 while (GET_CODE (x) == STRICT_LOW_PART
3250 || GET_CODE (x) == SIGN_EXTRACT
3251 || GET_CODE (x) == ZERO_EXTRACT
3252 || GET_CODE (x) == SUBREG)
3253 x = XEXP (x, 0);
3255 if (GET_CODE (x) != REG || REGNO (x) < FIRST_PSEUDO_REGISTER)
3256 return;
3258 /* If we do not have usage information, or if we know the register
3259 is used more than once, note that fact for check_dbra_loop. */
3260 if (REGNO (x) >= max_reg_before_loop
3261 || ! regs->array[REGNO (x)].single_usage
3262 || regs->array[REGNO (x)].single_usage == const0_rtx)
3263 regs->multiple_uses = 1;
3266 /* Return nonzero if the rtx X is invariant over the current loop.
3268 The value is 2 if we refer to something only conditionally invariant.
3270 A memory ref is invariant if it is not volatile and does not conflict
3271 with anything stored in `loop_info->store_mems'. */
3274 loop_invariant_p (loop, x)
3275 const struct loop *loop;
3276 rtx x;
3278 struct loop_info *loop_info = LOOP_INFO (loop);
3279 struct loop_regs *regs = LOOP_REGS (loop);
3280 int i;
3281 enum rtx_code code;
3282 const char *fmt;
3283 int conditional = 0;
3284 rtx mem_list_entry;
3286 if (x == 0)
3287 return 1;
3288 code = GET_CODE (x);
3289 switch (code)
3291 case CONST_INT:
3292 case CONST_DOUBLE:
3293 case SYMBOL_REF:
3294 case CONST:
3295 return 1;
3297 case LABEL_REF:
3298 /* A LABEL_REF is normally invariant, however, if we are unrolling
3299 loops, and this label is inside the loop, then it isn't invariant.
3300 This is because each unrolled copy of the loop body will have
3301 a copy of this label. If this was invariant, then an insn loading
3302 the address of this label into a register might get moved outside
3303 the loop, and then each loop body would end up using the same label.
3305 We don't know the loop bounds here though, so just fail for all
3306 labels. */
3307 if (flag_old_unroll_loops)
3308 return 0;
3309 else
3310 return 1;
3312 case PC:
3313 case CC0:
3314 case UNSPEC_VOLATILE:
3315 return 0;
3317 case REG:
3318 /* We used to check RTX_UNCHANGING_P (x) here, but that is invalid
3319 since the reg might be set by initialization within the loop. */
3321 if ((x == frame_pointer_rtx || x == hard_frame_pointer_rtx
3322 || x == arg_pointer_rtx || x == pic_offset_table_rtx)
3323 && ! current_function_has_nonlocal_goto)
3324 return 1;
3326 if (LOOP_INFO (loop)->has_call
3327 && REGNO (x) < FIRST_PSEUDO_REGISTER && call_used_regs[REGNO (x)])
3328 return 0;
3330 /* Out-of-range regs can occur when we are called from unrolling.
3331 These have always been created by the unroller and are set in
3332 the loop, hence are never invariant. */
3334 if (REGNO (x) >= (unsigned) regs->num)
3335 return 0;
3337 if (regs->array[REGNO (x)].set_in_loop < 0)
3338 return 2;
3340 return regs->array[REGNO (x)].set_in_loop == 0;
3342 case MEM:
3343 /* Volatile memory references must be rejected. Do this before
3344 checking for read-only items, so that volatile read-only items
3345 will be rejected also. */
3346 if (MEM_VOLATILE_P (x))
3347 return 0;
3349 /* See if there is any dependence between a store and this load. */
3350 mem_list_entry = loop_info->store_mems;
3351 while (mem_list_entry)
3353 if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
3354 x, rtx_varies_p))
3355 return 0;
3357 mem_list_entry = XEXP (mem_list_entry, 1);
3360 /* It's not invalidated by a store in memory
3361 but we must still verify the address is invariant. */
3362 break;
3364 case ASM_OPERANDS:
3365 /* Don't mess with insns declared volatile. */
3366 if (MEM_VOLATILE_P (x))
3367 return 0;
3368 break;
3370 default:
3371 break;
3374 fmt = GET_RTX_FORMAT (code);
3375 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3377 if (fmt[i] == 'e')
3379 int tem = loop_invariant_p (loop, XEXP (x, i));
3380 if (tem == 0)
3381 return 0;
3382 if (tem == 2)
3383 conditional = 1;
3385 else if (fmt[i] == 'E')
3387 int j;
3388 for (j = 0; j < XVECLEN (x, i); j++)
3390 int tem = loop_invariant_p (loop, XVECEXP (x, i, j));
3391 if (tem == 0)
3392 return 0;
3393 if (tem == 2)
3394 conditional = 1;
3400 return 1 + conditional;
3403 /* Return nonzero if all the insns in the loop that set REG
3404 are INSN and the immediately following insns,
3405 and if each of those insns sets REG in an invariant way
3406 (not counting uses of REG in them).
3408 The value is 2 if some of these insns are only conditionally invariant.
3410 We assume that INSN itself is the first set of REG
3411 and that its source is invariant. */
3413 static int
3414 consec_sets_invariant_p (loop, reg, n_sets, insn)
3415 const struct loop *loop;
3416 int n_sets;
3417 rtx reg, insn;
3419 struct loop_regs *regs = LOOP_REGS (loop);
3420 rtx p = insn;
3421 unsigned int regno = REGNO (reg);
3422 rtx temp;
3423 /* Number of sets we have to insist on finding after INSN. */
3424 int count = n_sets - 1;
3425 int old = regs->array[regno].set_in_loop;
3426 int value = 0;
3427 int this;
3429 /* If N_SETS hit the limit, we can't rely on its value. */
3430 if (n_sets == 127)
3431 return 0;
3433 regs->array[regno].set_in_loop = 0;
3435 while (count > 0)
3437 enum rtx_code code;
3438 rtx set;
3440 p = NEXT_INSN (p);
3441 code = GET_CODE (p);
3443 /* If library call, skip to end of it. */
3444 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
3445 p = XEXP (temp, 0);
3447 this = 0;
3448 if (code == INSN
3449 && (set = single_set (p))
3450 && GET_CODE (SET_DEST (set)) == REG
3451 && REGNO (SET_DEST (set)) == regno)
3453 this = loop_invariant_p (loop, SET_SRC (set));
3454 if (this != 0)
3455 value |= this;
3456 else if ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX)))
3458 /* If this is a libcall, then any invariant REG_EQUAL note is OK.
3459 If this is an ordinary insn, then only CONSTANT_P REG_EQUAL
3460 notes are OK. */
3461 this = (CONSTANT_P (XEXP (temp, 0))
3462 || (find_reg_note (p, REG_RETVAL, NULL_RTX)
3463 && loop_invariant_p (loop, XEXP (temp, 0))));
3464 if (this != 0)
3465 value |= this;
3468 if (this != 0)
3469 count--;
3470 else if (code != NOTE)
3472 regs->array[regno].set_in_loop = old;
3473 return 0;
3477 regs->array[regno].set_in_loop = old;
3478 /* If loop_invariant_p ever returned 2, we return 2. */
3479 return 1 + (value & 2);
3482 #if 0
3483 /* I don't think this condition is sufficient to allow INSN
3484 to be moved, so we no longer test it. */
3486 /* Return 1 if all insns in the basic block of INSN and following INSN
3487 that set REG are invariant according to TABLE. */
3489 static int
3490 all_sets_invariant_p (reg, insn, table)
3491 rtx reg, insn;
3492 short *table;
3494 rtx p = insn;
3495 int regno = REGNO (reg);
3497 while (1)
3499 enum rtx_code code;
3500 p = NEXT_INSN (p);
3501 code = GET_CODE (p);
3502 if (code == CODE_LABEL || code == JUMP_INSN)
3503 return 1;
3504 if (code == INSN && GET_CODE (PATTERN (p)) == SET
3505 && GET_CODE (SET_DEST (PATTERN (p))) == REG
3506 && REGNO (SET_DEST (PATTERN (p))) == regno)
3508 if (! loop_invariant_p (loop, SET_SRC (PATTERN (p)), table))
3509 return 0;
3513 #endif /* 0 */
3515 /* Look at all uses (not sets) of registers in X. For each, if it is
3516 the single use, set USAGE[REGNO] to INSN; if there was a previous use in
3517 a different insn, set USAGE[REGNO] to const0_rtx. */
3519 static void
3520 find_single_use_in_loop (regs, insn, x)
3521 struct loop_regs *regs;
3522 rtx insn;
3523 rtx x;
3525 enum rtx_code code = GET_CODE (x);
3526 const char *fmt = GET_RTX_FORMAT (code);
3527 int i, j;
3529 if (code == REG)
3530 regs->array[REGNO (x)].single_usage
3531 = (regs->array[REGNO (x)].single_usage != 0
3532 && regs->array[REGNO (x)].single_usage != insn)
3533 ? const0_rtx : insn;
3535 else if (code == SET)
3537 /* Don't count SET_DEST if it is a REG; otherwise count things
3538 in SET_DEST because if a register is partially modified, it won't
3539 show up as a potential movable so we don't care how USAGE is set
3540 for it. */
3541 if (GET_CODE (SET_DEST (x)) != REG)
3542 find_single_use_in_loop (regs, insn, SET_DEST (x));
3543 find_single_use_in_loop (regs, insn, SET_SRC (x));
3545 else
3546 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3548 if (fmt[i] == 'e' && XEXP (x, i) != 0)
3549 find_single_use_in_loop (regs, insn, XEXP (x, i));
3550 else if (fmt[i] == 'E')
3551 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
3552 find_single_use_in_loop (regs, insn, XVECEXP (x, i, j));
3556 /* Count and record any set in X which is contained in INSN. Update
3557 REGS->array[I].MAY_NOT_OPTIMIZE and LAST_SET for any register I set
3558 in X. */
3560 static void
3561 count_one_set (regs, insn, x, last_set)
3562 struct loop_regs *regs;
3563 rtx insn, x;
3564 rtx *last_set;
3566 if (GET_CODE (x) == CLOBBER && GET_CODE (XEXP (x, 0)) == REG)
3567 /* Don't move a reg that has an explicit clobber.
3568 It's not worth the pain to try to do it correctly. */
3569 regs->array[REGNO (XEXP (x, 0))].may_not_optimize = 1;
3571 if (GET_CODE (x) == SET || GET_CODE (x) == CLOBBER)
3573 rtx dest = SET_DEST (x);
3574 while (GET_CODE (dest) == SUBREG
3575 || GET_CODE (dest) == ZERO_EXTRACT
3576 || GET_CODE (dest) == SIGN_EXTRACT
3577 || GET_CODE (dest) == STRICT_LOW_PART)
3578 dest = XEXP (dest, 0);
3579 if (GET_CODE (dest) == REG)
3581 int i;
3582 int regno = REGNO (dest);
3583 for (i = 0; i < LOOP_REGNO_NREGS (regno, dest); i++)
3585 /* If this is the first setting of this reg
3586 in current basic block, and it was set before,
3587 it must be set in two basic blocks, so it cannot
3588 be moved out of the loop. */
3589 if (regs->array[regno].set_in_loop > 0
3590 && last_set == 0)
3591 regs->array[regno+i].may_not_optimize = 1;
3592 /* If this is not first setting in current basic block,
3593 see if reg was used in between previous one and this.
3594 If so, neither one can be moved. */
3595 if (last_set[regno] != 0
3596 && reg_used_between_p (dest, last_set[regno], insn))
3597 regs->array[regno+i].may_not_optimize = 1;
3598 if (regs->array[regno+i].set_in_loop < 127)
3599 ++regs->array[regno+i].set_in_loop;
3600 last_set[regno+i] = insn;
3606 /* Given a loop that is bounded by LOOP->START and LOOP->END and that
3607 is entered at LOOP->SCAN_START, return 1 if the register set in SET
3608 contained in insn INSN is used by any insn that precedes INSN in
3609 cyclic order starting from the loop entry point.
3611 We don't want to use INSN_LUID here because if we restrict INSN to those
3612 that have a valid INSN_LUID, it means we cannot move an invariant out
3613 from an inner loop past two loops. */
3615 static int
3616 loop_reg_used_before_p (loop, set, insn)
3617 const struct loop *loop;
3618 rtx set, insn;
3620 rtx reg = SET_DEST (set);
3621 rtx p;
3623 /* Scan forward checking for register usage. If we hit INSN, we
3624 are done. Otherwise, if we hit LOOP->END, wrap around to LOOP->START. */
3625 for (p = loop->scan_start; p != insn; p = NEXT_INSN (p))
3627 if (INSN_P (p) && reg_overlap_mentioned_p (reg, PATTERN (p)))
3628 return 1;
3630 if (p == loop->end)
3631 p = loop->start;
3634 return 0;
3638 /* Information we collect about arrays that we might want to prefetch. */
3639 struct prefetch_info
3641 struct iv_class *class; /* Class this prefetch is based on. */
3642 struct induction *giv; /* GIV this prefetch is based on. */
3643 rtx base_address; /* Start prefetching from this address plus
3644 index. */
3645 HOST_WIDE_INT index;
3646 HOST_WIDE_INT stride; /* Prefetch stride in bytes in each
3647 iteration. */
3648 unsigned int bytes_accessed; /* Sum of sizes of all accesses to this
3649 prefetch area in one iteration. */
3650 unsigned int total_bytes; /* Total bytes loop will access in this block.
3651 This is set only for loops with known
3652 iteration counts and is 0xffffffff
3653 otherwise. */
3654 int prefetch_in_loop; /* Number of prefetch insns in loop. */
3655 int prefetch_before_loop; /* Number of prefetch insns before loop. */
3656 unsigned int write : 1; /* 1 for read/write prefetches. */
3659 /* Data used by check_store function. */
3660 struct check_store_data
3662 rtx mem_address;
3663 int mem_write;
3666 static void check_store PARAMS ((rtx, rtx, void *));
3667 static void emit_prefetch_instructions PARAMS ((struct loop *));
3668 static int rtx_equal_for_prefetch_p PARAMS ((rtx, rtx));
3670 /* Set mem_write when mem_address is found. Used as callback to
3671 note_stores. */
3672 static void
3673 check_store (x, pat, data)
3674 rtx x, pat ATTRIBUTE_UNUSED;
3675 void *data;
3677 struct check_store_data *d = (struct check_store_data *) data;
3679 if ((GET_CODE (x) == MEM) && rtx_equal_p (d->mem_address, XEXP (x, 0)))
3680 d->mem_write = 1;
3683 /* Like rtx_equal_p, but attempts to swap commutative operands. This is
3684 important to get some addresses combined. Later more sophisticated
3685 transformations can be added when necessary.
3687 ??? Same trick with swapping operand is done at several other places.
3688 It can be nice to develop some common way to handle this. */
3690 static int
3691 rtx_equal_for_prefetch_p (x, y)
3692 rtx x, y;
3694 int i;
3695 int j;
3696 enum rtx_code code = GET_CODE (x);
3697 const char *fmt;
3699 if (x == y)
3700 return 1;
3701 if (code != GET_CODE (y))
3702 return 0;
3704 code = GET_CODE (x);
3706 if (GET_RTX_CLASS (code) == 'c')
3708 return ((rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 0))
3709 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 1)))
3710 || (rtx_equal_for_prefetch_p (XEXP (x, 0), XEXP (y, 1))
3711 && rtx_equal_for_prefetch_p (XEXP (x, 1), XEXP (y, 0))));
3713 /* Compare the elements. If any pair of corresponding elements fails to
3714 match, return 0 for the whole thing. */
3716 fmt = GET_RTX_FORMAT (code);
3717 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
3719 switch (fmt[i])
3721 case 'w':
3722 if (XWINT (x, i) != XWINT (y, i))
3723 return 0;
3724 break;
3726 case 'i':
3727 if (XINT (x, i) != XINT (y, i))
3728 return 0;
3729 break;
3731 case 'E':
3732 /* Two vectors must have the same length. */
3733 if (XVECLEN (x, i) != XVECLEN (y, i))
3734 return 0;
3736 /* And the corresponding elements must match. */
3737 for (j = 0; j < XVECLEN (x, i); j++)
3738 if (rtx_equal_for_prefetch_p (XVECEXP (x, i, j),
3739 XVECEXP (y, i, j)) == 0)
3740 return 0;
3741 break;
3743 case 'e':
3744 if (rtx_equal_for_prefetch_p (XEXP (x, i), XEXP (y, i)) == 0)
3745 return 0;
3746 break;
3748 case 's':
3749 if (strcmp (XSTR (x, i), XSTR (y, i)))
3750 return 0;
3751 break;
3753 case 'u':
3754 /* These are just backpointers, so they don't matter. */
3755 break;
3757 case '0':
3758 break;
3760 /* It is believed that rtx's at this level will never
3761 contain anything but integers and other rtx's,
3762 except for within LABEL_REFs and SYMBOL_REFs. */
3763 default:
3764 abort ();
3767 return 1;
3770 /* Remove constant addition value from the expression X (when present)
3771 and return it. */
3773 static HOST_WIDE_INT
3774 remove_constant_addition (x)
3775 rtx *x;
3777 HOST_WIDE_INT addval = 0;
3778 rtx exp = *x;
3780 /* Avoid clobbering a shared CONST expression. */
3781 if (GET_CODE (exp) == CONST)
3783 if (GET_CODE (XEXP (exp, 0)) == PLUS
3784 && GET_CODE (XEXP (XEXP (exp, 0), 0)) == SYMBOL_REF
3785 && GET_CODE (XEXP (XEXP (exp, 0), 1)) == CONST_INT)
3787 *x = XEXP (XEXP (exp, 0), 0);
3788 return INTVAL (XEXP (XEXP (exp, 0), 1));
3790 return 0;
3793 if (GET_CODE (exp) == CONST_INT)
3795 addval = INTVAL (exp);
3796 *x = const0_rtx;
3799 /* For plus expression recurse on ourself. */
3800 else if (GET_CODE (exp) == PLUS)
3802 addval += remove_constant_addition (&XEXP (exp, 0));
3803 addval += remove_constant_addition (&XEXP (exp, 1));
3805 /* In case our parameter was constant, remove extra zero from the
3806 expression. */
3807 if (XEXP (exp, 0) == const0_rtx)
3808 *x = XEXP (exp, 1);
3809 else if (XEXP (exp, 1) == const0_rtx)
3810 *x = XEXP (exp, 0);
3813 return addval;
3816 /* Attempt to identify accesses to arrays that are most likely to cause cache
3817 misses, and emit prefetch instructions a few prefetch blocks forward.
3819 To detect the arrays we use the GIV information that was collected by the
3820 strength reduction pass.
3822 The prefetch instructions are generated after the GIV information is done
3823 and before the strength reduction process. The new GIVs are injected into
3824 the strength reduction tables, so the prefetch addresses are optimized as
3825 well.
3827 GIVs are split into base address, stride, and constant addition values.
3828 GIVs with the same address, stride and close addition values are combined
3829 into a single prefetch. Also writes to GIVs are detected, so that prefetch
3830 for write instructions can be used for the block we write to, on machines
3831 that support write prefetches.
3833 Several heuristics are used to determine when to prefetch. They are
3834 controlled by defined symbols that can be overridden for each target. */
3836 static void
3837 emit_prefetch_instructions (loop)
3838 struct loop *loop;
3840 int num_prefetches = 0;
3841 int num_real_prefetches = 0;
3842 int num_real_write_prefetches = 0;
3843 int num_prefetches_before = 0;
3844 int num_write_prefetches_before = 0;
3845 int ahead = 0;
3846 int i;
3847 struct iv_class *bl;
3848 struct induction *iv;
3849 struct prefetch_info info[MAX_PREFETCHES];
3850 struct loop_ivs *ivs = LOOP_IVS (loop);
3852 if (!HAVE_prefetch)
3853 return;
3855 /* Consider only loops w/o calls. When a call is done, the loop is probably
3856 slow enough to read the memory. */
3857 if (PREFETCH_NO_CALL && LOOP_INFO (loop)->has_call)
3859 if (loop_dump_stream)
3860 fprintf (loop_dump_stream, "Prefetch: ignoring loop: has call.\n");
3862 return;
3865 /* Don't prefetch in loops known to have few iterations. */
3866 if (PREFETCH_NO_LOW_LOOPCNT
3867 && LOOP_INFO (loop)->n_iterations
3868 && LOOP_INFO (loop)->n_iterations <= PREFETCH_LOW_LOOPCNT)
3870 if (loop_dump_stream)
3871 fprintf (loop_dump_stream,
3872 "Prefetch: ignoring loop: not enough iterations.\n");
3873 return;
3876 /* Search all induction variables and pick those interesting for the prefetch
3877 machinery. */
3878 for (bl = ivs->list; bl; bl = bl->next)
3880 struct induction *biv = bl->biv, *biv1;
3881 int basestride = 0;
3883 biv1 = biv;
3885 /* Expect all BIVs to be executed in each iteration. This makes our
3886 analysis more conservative. */
3887 while (biv1)
3889 /* Discard non-constant additions that we can't handle well yet, and
3890 BIVs that are executed multiple times; such BIVs ought to be
3891 handled in the nested loop. We accept not_every_iteration BIVs,
3892 since these only result in larger strides and make our
3893 heuristics more conservative. */
3894 if (GET_CODE (biv->add_val) != CONST_INT)
3896 if (loop_dump_stream)
3898 fprintf (loop_dump_stream,
3899 "Prefetch: ignoring biv %d: non-constant addition at insn %d:",
3900 REGNO (biv->src_reg), INSN_UID (biv->insn));
3901 print_rtl (loop_dump_stream, biv->add_val);
3902 fprintf (loop_dump_stream, "\n");
3904 break;
3907 if (biv->maybe_multiple)
3909 if (loop_dump_stream)
3911 fprintf (loop_dump_stream,
3912 "Prefetch: ignoring biv %d: maybe_multiple at insn %i:",
3913 REGNO (biv->src_reg), INSN_UID (biv->insn));
3914 print_rtl (loop_dump_stream, biv->add_val);
3915 fprintf (loop_dump_stream, "\n");
3917 break;
3920 basestride += INTVAL (biv1->add_val);
3921 biv1 = biv1->next_iv;
3924 if (biv1 || !basestride)
3925 continue;
3927 for (iv = bl->giv; iv; iv = iv->next_iv)
3929 rtx address;
3930 rtx temp;
3931 HOST_WIDE_INT index = 0;
3932 int add = 1;
3933 HOST_WIDE_INT stride = 0;
3934 int stride_sign = 1;
3935 struct check_store_data d;
3936 const char *ignore_reason = NULL;
3937 int size = GET_MODE_SIZE (GET_MODE (iv));
3939 /* See whether an induction variable is interesting to us and if
3940 not, report the reason. */
3941 if (iv->giv_type != DEST_ADDR)
3942 ignore_reason = "giv is not a destination address";
3944 /* We are interested only in constant stride memory references
3945 in order to be able to compute density easily. */
3946 else if (GET_CODE (iv->mult_val) != CONST_INT)
3947 ignore_reason = "stride is not constant";
3949 else
3951 stride = INTVAL (iv->mult_val) * basestride;
3952 if (stride < 0)
3954 stride = -stride;
3955 stride_sign = -1;
3958 /* On some targets, reversed order prefetches are not
3959 worthwhile. */
3960 if (PREFETCH_NO_REVERSE_ORDER && stride_sign < 0)
3961 ignore_reason = "reversed order stride";
3963 /* Prefetch of accesses with an extreme stride might not be
3964 worthwhile, either. */
3965 else if (PREFETCH_NO_EXTREME_STRIDE
3966 && stride > PREFETCH_EXTREME_STRIDE)
3967 ignore_reason = "extreme stride";
3969 /* Ignore GIVs with varying add values; we can't predict the
3970 value for the next iteration. */
3971 else if (!loop_invariant_p (loop, iv->add_val))
3972 ignore_reason = "giv has varying add value";
3974 /* Ignore GIVs in the nested loops; they ought to have been
3975 handled already. */
3976 else if (iv->maybe_multiple)
3977 ignore_reason = "giv is in nested loop";
3980 if (ignore_reason != NULL)
3982 if (loop_dump_stream)
3983 fprintf (loop_dump_stream,
3984 "Prefetch: ignoring giv at %d: %s.\n",
3985 INSN_UID (iv->insn), ignore_reason);
3986 continue;
3989 /* Determine the pointer to the basic array we are examining. It is
3990 the sum of the BIV's initial value and the GIV's add_val. */
3991 address = copy_rtx (iv->add_val);
3992 temp = copy_rtx (bl->initial_value);
3994 address = simplify_gen_binary (PLUS, Pmode, temp, address);
3995 index = remove_constant_addition (&address);
3997 d.mem_write = 0;
3998 d.mem_address = *iv->location;
4000 /* When the GIV is not always executed, we might be better off by
4001 not dirtying the cache pages. */
4002 if (PREFETCH_CONDITIONAL || iv->always_executed)
4003 note_stores (PATTERN (iv->insn), check_store, &d);
4004 else
4006 if (loop_dump_stream)
4007 fprintf (loop_dump_stream, "Prefetch: Ignoring giv at %d: %s\n",
4008 INSN_UID (iv->insn), "in conditional code.");
4009 continue;
4012 /* Attempt to find another prefetch to the same array and see if we
4013 can merge this one. */
4014 for (i = 0; i < num_prefetches; i++)
4015 if (rtx_equal_for_prefetch_p (address, info[i].base_address)
4016 && stride == info[i].stride)
4018 /* In case both access same array (same location
4019 just with small difference in constant indexes), merge
4020 the prefetches. Just do the later and the earlier will
4021 get prefetched from previous iteration.
4022 The artificial threshold should not be too small,
4023 but also not bigger than small portion of memory usually
4024 traversed by single loop. */
4025 if (index >= info[i].index
4026 && index - info[i].index < PREFETCH_EXTREME_DIFFERENCE)
4028 info[i].write |= d.mem_write;
4029 info[i].bytes_accessed += size;
4030 info[i].index = index;
4031 info[i].giv = iv;
4032 info[i].class = bl;
4033 info[num_prefetches].base_address = address;
4034 add = 0;
4035 break;
4038 if (index < info[i].index
4039 && info[i].index - index < PREFETCH_EXTREME_DIFFERENCE)
4041 info[i].write |= d.mem_write;
4042 info[i].bytes_accessed += size;
4043 add = 0;
4044 break;
4048 /* Merging failed. */
4049 if (add)
4051 info[num_prefetches].giv = iv;
4052 info[num_prefetches].class = bl;
4053 info[num_prefetches].index = index;
4054 info[num_prefetches].stride = stride;
4055 info[num_prefetches].base_address = address;
4056 info[num_prefetches].write = d.mem_write;
4057 info[num_prefetches].bytes_accessed = size;
4058 num_prefetches++;
4059 if (num_prefetches >= MAX_PREFETCHES)
4061 if (loop_dump_stream)
4062 fprintf (loop_dump_stream,
4063 "Maximal number of prefetches exceeded.\n");
4064 return;
4070 for (i = 0; i < num_prefetches; i++)
4072 int density;
4074 /* Attempt to calculate the total number of bytes fetched by all
4075 iterations of the loop. Avoid overflow. */
4076 if (LOOP_INFO (loop)->n_iterations
4077 && ((unsigned HOST_WIDE_INT) (0xffffffff / info[i].stride)
4078 >= LOOP_INFO (loop)->n_iterations))
4079 info[i].total_bytes = info[i].stride * LOOP_INFO (loop)->n_iterations;
4080 else
4081 info[i].total_bytes = 0xffffffff;
4083 density = info[i].bytes_accessed * 100 / info[i].stride;
4085 /* Prefetch might be worthwhile only when the loads/stores are dense. */
4086 if (PREFETCH_ONLY_DENSE_MEM)
4087 if (density * 256 > PREFETCH_DENSE_MEM * 100
4088 && (info[i].total_bytes / PREFETCH_BLOCK
4089 >= PREFETCH_BLOCKS_BEFORE_LOOP_MIN))
4091 info[i].prefetch_before_loop = 1;
4092 info[i].prefetch_in_loop
4093 = (info[i].total_bytes / PREFETCH_BLOCK
4094 > PREFETCH_BLOCKS_BEFORE_LOOP_MAX);
4096 else
4098 info[i].prefetch_in_loop = 0, info[i].prefetch_before_loop = 0;
4099 if (loop_dump_stream)
4100 fprintf (loop_dump_stream,
4101 "Prefetch: ignoring giv at %d: %d%% density is too low.\n",
4102 INSN_UID (info[i].giv->insn), density);
4104 else
4105 info[i].prefetch_in_loop = 1, info[i].prefetch_before_loop = 1;
4107 /* Find how many prefetch instructions we'll use within the loop. */
4108 if (info[i].prefetch_in_loop != 0)
4110 info[i].prefetch_in_loop = ((info[i].stride + PREFETCH_BLOCK - 1)
4111 / PREFETCH_BLOCK);
4112 num_real_prefetches += info[i].prefetch_in_loop;
4113 if (info[i].write)
4114 num_real_write_prefetches += info[i].prefetch_in_loop;
4118 /* Determine how many iterations ahead to prefetch within the loop, based
4119 on how many prefetches we currently expect to do within the loop. */
4120 if (num_real_prefetches != 0)
4122 if ((ahead = SIMULTANEOUS_PREFETCHES / num_real_prefetches) == 0)
4124 if (loop_dump_stream)
4125 fprintf (loop_dump_stream,
4126 "Prefetch: ignoring prefetches within loop: ahead is zero; %d < %d\n",
4127 SIMULTANEOUS_PREFETCHES, num_real_prefetches);
4128 num_real_prefetches = 0, num_real_write_prefetches = 0;
4131 /* We'll also use AHEAD to determine how many prefetch instructions to
4132 emit before a loop, so don't leave it zero. */
4133 if (ahead == 0)
4134 ahead = PREFETCH_BLOCKS_BEFORE_LOOP_MAX;
4136 for (i = 0; i < num_prefetches; i++)
4138 /* Update if we've decided not to prefetch anything within the loop. */
4139 if (num_real_prefetches == 0)
4140 info[i].prefetch_in_loop = 0;
4142 /* Find how many prefetch instructions we'll use before the loop. */
4143 if (info[i].prefetch_before_loop != 0)
4145 int n = info[i].total_bytes / PREFETCH_BLOCK;
4146 if (n > ahead)
4147 n = ahead;
4148 info[i].prefetch_before_loop = n;
4149 num_prefetches_before += n;
4150 if (info[i].write)
4151 num_write_prefetches_before += n;
4154 if (loop_dump_stream)
4156 if (info[i].prefetch_in_loop == 0
4157 && info[i].prefetch_before_loop == 0)
4158 continue;
4159 fprintf (loop_dump_stream, "Prefetch insn: %d",
4160 INSN_UID (info[i].giv->insn));
4161 fprintf (loop_dump_stream,
4162 "; in loop: %d; before: %d; %s\n",
4163 info[i].prefetch_in_loop,
4164 info[i].prefetch_before_loop,
4165 info[i].write ? "read/write" : "read only");
4166 fprintf (loop_dump_stream,
4167 " density: %d%%; bytes_accessed: %u; total_bytes: %u\n",
4168 (int) (info[i].bytes_accessed * 100 / info[i].stride),
4169 info[i].bytes_accessed, info[i].total_bytes);
4170 fprintf (loop_dump_stream, " index: ");
4171 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, info[i].index);
4172 fprintf (loop_dump_stream, "; stride: ");
4173 fprintf (loop_dump_stream, HOST_WIDE_INT_PRINT_DEC, info[i].stride);
4174 fprintf (loop_dump_stream, "; address: ");
4175 print_rtl (loop_dump_stream, info[i].base_address);
4176 fprintf (loop_dump_stream, "\n");
4180 if (num_real_prefetches + num_prefetches_before > 0)
4182 /* Record that this loop uses prefetch instructions. */
4183 LOOP_INFO (loop)->has_prefetch = 1;
4185 if (loop_dump_stream)
4187 fprintf (loop_dump_stream, "Real prefetches needed within loop: %d (write: %d)\n",
4188 num_real_prefetches, num_real_write_prefetches);
4189 fprintf (loop_dump_stream, "Real prefetches needed before loop: %d (write: %d)\n",
4190 num_prefetches_before, num_write_prefetches_before);
4194 for (i = 0; i < num_prefetches; i++)
4196 int y;
4198 for (y = 0; y < info[i].prefetch_in_loop; y++)
4200 rtx loc = copy_rtx (*info[i].giv->location);
4201 rtx insn;
4202 int bytes_ahead = PREFETCH_BLOCK * (ahead + y);
4203 rtx before_insn = info[i].giv->insn;
4204 rtx prev_insn = PREV_INSN (info[i].giv->insn);
4205 rtx seq;
4207 /* We can save some effort by offsetting the address on
4208 architectures with offsettable memory references. */
4209 if (offsettable_address_p (0, VOIDmode, loc))
4210 loc = plus_constant (loc, bytes_ahead);
4211 else
4213 rtx reg = gen_reg_rtx (Pmode);
4214 loop_iv_add_mult_emit_before (loop, loc, const1_rtx,
4215 GEN_INT (bytes_ahead), reg,
4216 0, before_insn);
4217 loc = reg;
4220 start_sequence ();
4221 /* Make sure the address operand is valid for prefetch. */
4222 if (! (*insn_data[(int)CODE_FOR_prefetch].operand[0].predicate)
4223 (loc, insn_data[(int)CODE_FOR_prefetch].operand[0].mode))
4224 loc = force_reg (Pmode, loc);
4225 emit_insn (gen_prefetch (loc, GEN_INT (info[i].write),
4226 GEN_INT (3)));
4227 seq = get_insns ();
4228 end_sequence ();
4229 emit_insn_before (seq, before_insn);
4231 /* Check all insns emitted and record the new GIV
4232 information. */
4233 insn = NEXT_INSN (prev_insn);
4234 while (insn != before_insn)
4236 insn = check_insn_for_givs (loop, insn,
4237 info[i].giv->always_executed,
4238 info[i].giv->maybe_multiple);
4239 insn = NEXT_INSN (insn);
4243 if (PREFETCH_BEFORE_LOOP)
4245 /* Emit insns before the loop to fetch the first cache lines or,
4246 if we're not prefetching within the loop, everything we expect
4247 to need. */
4248 for (y = 0; y < info[i].prefetch_before_loop; y++)
4250 rtx reg = gen_reg_rtx (Pmode);
4251 rtx loop_start = loop->start;
4252 rtx init_val = info[i].class->initial_value;
4253 rtx add_val = simplify_gen_binary (PLUS, Pmode,
4254 info[i].giv->add_val,
4255 GEN_INT (y * PREFETCH_BLOCK));
4257 /* Functions called by LOOP_IV_ADD_EMIT_BEFORE expect a
4258 non-constant INIT_VAL to have the same mode as REG, which
4259 in this case we know to be Pmode. */
4260 if (GET_MODE (init_val) != Pmode && !CONSTANT_P (init_val))
4262 rtx seq;
4264 start_sequence ();
4265 init_val = convert_to_mode (Pmode, init_val, 0);
4266 seq = get_insns ();
4267 end_sequence ();
4268 loop_insn_emit_before (loop, 0, loop_start, seq);
4270 loop_iv_add_mult_emit_before (loop, init_val,
4271 info[i].giv->mult_val,
4272 add_val, reg, 0, loop_start);
4273 emit_insn_before (gen_prefetch (reg, GEN_INT (info[i].write),
4274 GEN_INT (3)),
4275 loop_start);
4280 return;
4283 /* A "basic induction variable" or biv is a pseudo reg that is set
4284 (within this loop) only by incrementing or decrementing it. */
4285 /* A "general induction variable" or giv is a pseudo reg whose
4286 value is a linear function of a biv. */
4288 /* Bivs are recognized by `basic_induction_var';
4289 Givs by `general_induction_var'. */
4291 /* Communication with routines called via `note_stores'. */
4293 static rtx note_insn;
4295 /* Dummy register to have nonzero DEST_REG for DEST_ADDR type givs. */
4297 static rtx addr_placeholder;
4299 /* ??? Unfinished optimizations, and possible future optimizations,
4300 for the strength reduction code. */
4302 /* ??? The interaction of biv elimination, and recognition of 'constant'
4303 bivs, may cause problems. */
4305 /* ??? Add heuristics so that DEST_ADDR strength reduction does not cause
4306 performance problems.
4308 Perhaps don't eliminate things that can be combined with an addressing
4309 mode. Find all givs that have the same biv, mult_val, and add_val;
4310 then for each giv, check to see if its only use dies in a following
4311 memory address. If so, generate a new memory address and check to see
4312 if it is valid. If it is valid, then store the modified memory address,
4313 otherwise, mark the giv as not done so that it will get its own iv. */
4315 /* ??? Could try to optimize branches when it is known that a biv is always
4316 positive. */
4318 /* ??? When replace a biv in a compare insn, we should replace with closest
4319 giv so that an optimized branch can still be recognized by the combiner,
4320 e.g. the VAX acb insn. */
4322 /* ??? Many of the checks involving uid_luid could be simplified if regscan
4323 was rerun in loop_optimize whenever a register was added or moved.
4324 Also, some of the optimizations could be a little less conservative. */
4326 /* Scan the loop body and call FNCALL for each insn. In the addition to the
4327 LOOP and INSN parameters pass MAYBE_MULTIPLE and NOT_EVERY_ITERATION to the
4328 callback.
4330 NOT_EVERY_ITERATION is 1 if current insn is not known to be executed at
4331 least once for every loop iteration except for the last one.
4333 MAYBE_MULTIPLE is 1 if current insn may be executed more than once for every
4334 loop iteration.
4336 void
4337 for_each_insn_in_loop (loop, fncall)
4338 struct loop *loop;
4339 loop_insn_callback fncall;
4341 int not_every_iteration = 0;
4342 int maybe_multiple = 0;
4343 int past_loop_latch = 0;
4344 int loop_depth = 0;
4345 rtx p;
4347 /* If loop_scan_start points to the loop exit test, we have to be wary of
4348 subversive use of gotos inside expression statements. */
4349 if (prev_nonnote_insn (loop->scan_start) != prev_nonnote_insn (loop->start))
4350 maybe_multiple = back_branch_in_range_p (loop, loop->scan_start);
4352 /* Scan through loop and update NOT_EVERY_ITERATION and MAYBE_MULTIPLE. */
4353 for (p = next_insn_in_loop (loop, loop->scan_start);
4354 p != NULL_RTX;
4355 p = next_insn_in_loop (loop, p))
4357 p = fncall (loop, p, not_every_iteration, maybe_multiple);
4359 /* Past CODE_LABEL, we get to insns that may be executed multiple
4360 times. The only way we can be sure that they can't is if every
4361 jump insn between here and the end of the loop either
4362 returns, exits the loop, is a jump to a location that is still
4363 behind the label, or is a jump to the loop start. */
4365 if (GET_CODE (p) == CODE_LABEL)
4367 rtx insn = p;
4369 maybe_multiple = 0;
4371 while (1)
4373 insn = NEXT_INSN (insn);
4374 if (insn == loop->scan_start)
4375 break;
4376 if (insn == loop->end)
4378 if (loop->top != 0)
4379 insn = loop->top;
4380 else
4381 break;
4382 if (insn == loop->scan_start)
4383 break;
4386 if (GET_CODE (insn) == JUMP_INSN
4387 && GET_CODE (PATTERN (insn)) != RETURN
4388 && (!any_condjump_p (insn)
4389 || (JUMP_LABEL (insn) != 0
4390 && JUMP_LABEL (insn) != loop->scan_start
4391 && !loop_insn_first_p (p, JUMP_LABEL (insn)))))
4393 maybe_multiple = 1;
4394 break;
4399 /* Past a jump, we get to insns for which we can't count
4400 on whether they will be executed during each iteration. */
4401 /* This code appears twice in strength_reduce. There is also similar
4402 code in scan_loop. */
4403 if (GET_CODE (p) == JUMP_INSN
4404 /* If we enter the loop in the middle, and scan around to the
4405 beginning, don't set not_every_iteration for that.
4406 This can be any kind of jump, since we want to know if insns
4407 will be executed if the loop is executed. */
4408 && !(JUMP_LABEL (p) == loop->top
4409 && ((NEXT_INSN (NEXT_INSN (p)) == loop->end
4410 && any_uncondjump_p (p))
4411 || (NEXT_INSN (p) == loop->end && any_condjump_p (p)))))
4413 rtx label = 0;
4415 /* If this is a jump outside the loop, then it also doesn't
4416 matter. Check to see if the target of this branch is on the
4417 loop->exits_labels list. */
4419 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
4420 if (XEXP (label, 0) == JUMP_LABEL (p))
4421 break;
4423 if (!label)
4424 not_every_iteration = 1;
4427 else if (GET_CODE (p) == NOTE)
4429 /* At the virtual top of a converted loop, insns are again known to
4430 be executed each iteration: logically, the loop begins here
4431 even though the exit code has been duplicated.
4433 Insns are also again known to be executed each iteration at
4434 the LOOP_CONT note. */
4435 if ((NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_VTOP
4436 || NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_CONT)
4437 && loop_depth == 0)
4438 not_every_iteration = 0;
4439 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_BEG)
4440 loop_depth++;
4441 else if (NOTE_LINE_NUMBER (p) == NOTE_INSN_LOOP_END)
4442 loop_depth--;
4445 /* Note if we pass a loop latch. If we do, then we can not clear
4446 NOT_EVERY_ITERATION below when we pass the last CODE_LABEL in
4447 a loop since a jump before the last CODE_LABEL may have started
4448 a new loop iteration.
4450 Note that LOOP_TOP is only set for rotated loops and we need
4451 this check for all loops, so compare against the CODE_LABEL
4452 which immediately follows LOOP_START. */
4453 if (GET_CODE (p) == JUMP_INSN
4454 && JUMP_LABEL (p) == NEXT_INSN (loop->start))
4455 past_loop_latch = 1;
4457 /* Unlike in the code motion pass where MAYBE_NEVER indicates that
4458 an insn may never be executed, NOT_EVERY_ITERATION indicates whether
4459 or not an insn is known to be executed each iteration of the
4460 loop, whether or not any iterations are known to occur.
4462 Therefore, if we have just passed a label and have no more labels
4463 between here and the test insn of the loop, and we have not passed
4464 a jump to the top of the loop, then we know these insns will be
4465 executed each iteration. */
4467 if (not_every_iteration
4468 && !past_loop_latch
4469 && GET_CODE (p) == CODE_LABEL
4470 && no_labels_between_p (p, loop->end)
4471 && loop_insn_first_p (p, loop->cont))
4472 not_every_iteration = 0;
4476 static void
4477 loop_bivs_find (loop)
4478 struct loop *loop;
4480 struct loop_regs *regs = LOOP_REGS (loop);
4481 struct loop_ivs *ivs = LOOP_IVS (loop);
4482 /* Temporary list pointers for traversing ivs->list. */
4483 struct iv_class *bl, **backbl;
4485 ivs->list = 0;
4487 for_each_insn_in_loop (loop, check_insn_for_bivs);
4489 /* Scan ivs->list to remove all regs that proved not to be bivs.
4490 Make a sanity check against regs->n_times_set. */
4491 for (backbl = &ivs->list, bl = *backbl; bl; bl = bl->next)
4493 if (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4494 /* Above happens if register modified by subreg, etc. */
4495 /* Make sure it is not recognized as a basic induction var: */
4496 || regs->array[bl->regno].n_times_set != bl->biv_count
4497 /* If never incremented, it is invariant that we decided not to
4498 move. So leave it alone. */
4499 || ! bl->incremented)
4501 if (loop_dump_stream)
4502 fprintf (loop_dump_stream, "Biv %d: discarded, %s\n",
4503 bl->regno,
4504 (REG_IV_TYPE (ivs, bl->regno) != BASIC_INDUCT
4505 ? "not induction variable"
4506 : (! bl->incremented ? "never incremented"
4507 : "count error")));
4509 REG_IV_TYPE (ivs, bl->regno) = NOT_BASIC_INDUCT;
4510 *backbl = bl->next;
4512 else
4514 backbl = &bl->next;
4516 if (loop_dump_stream)
4517 fprintf (loop_dump_stream, "Biv %d: verified\n", bl->regno);
4523 /* Determine how BIVS are initialized by looking through pre-header
4524 extended basic block. */
4525 static void
4526 loop_bivs_init_find (loop)
4527 struct loop *loop;
4529 struct loop_ivs *ivs = LOOP_IVS (loop);
4530 /* Temporary list pointers for traversing ivs->list. */
4531 struct iv_class *bl;
4532 int call_seen;
4533 rtx p;
4535 /* Find initial value for each biv by searching backwards from loop_start,
4536 halting at first label. Also record any test condition. */
4538 call_seen = 0;
4539 for (p = loop->start; p && GET_CODE (p) != CODE_LABEL; p = PREV_INSN (p))
4541 rtx test;
4543 note_insn = p;
4545 if (GET_CODE (p) == CALL_INSN)
4546 call_seen = 1;
4548 if (INSN_P (p))
4549 note_stores (PATTERN (p), record_initial, ivs);
4551 /* Record any test of a biv that branches around the loop if no store
4552 between it and the start of loop. We only care about tests with
4553 constants and registers and only certain of those. */
4554 if (GET_CODE (p) == JUMP_INSN
4555 && JUMP_LABEL (p) != 0
4556 && next_real_insn (JUMP_LABEL (p)) == next_real_insn (loop->end)
4557 && (test = get_condition_for_loop (loop, p)) != 0
4558 && GET_CODE (XEXP (test, 0)) == REG
4559 && REGNO (XEXP (test, 0)) < max_reg_before_loop
4560 && (bl = REG_IV_CLASS (ivs, REGNO (XEXP (test, 0)))) != 0
4561 && valid_initial_value_p (XEXP (test, 1), p, call_seen, loop->start)
4562 && bl->init_insn == 0)
4564 /* If an NE test, we have an initial value! */
4565 if (GET_CODE (test) == NE)
4567 bl->init_insn = p;
4568 bl->init_set = gen_rtx_SET (VOIDmode,
4569 XEXP (test, 0), XEXP (test, 1));
4571 else
4572 bl->initial_test = test;
4578 /* Look at the each biv and see if we can say anything better about its
4579 initial value from any initializing insns set up above. (This is done
4580 in two passes to avoid missing SETs in a PARALLEL.) */
4581 static void
4582 loop_bivs_check (loop)
4583 struct loop *loop;
4585 struct loop_ivs *ivs = LOOP_IVS (loop);
4586 /* Temporary list pointers for traversing ivs->list. */
4587 struct iv_class *bl;
4588 struct iv_class **backbl;
4590 for (backbl = &ivs->list; (bl = *backbl); backbl = &bl->next)
4592 rtx src;
4593 rtx note;
4595 if (! bl->init_insn)
4596 continue;
4598 /* IF INIT_INSN has a REG_EQUAL or REG_EQUIV note and the value
4599 is a constant, use the value of that. */
4600 if (((note = find_reg_note (bl->init_insn, REG_EQUAL, 0)) != NULL
4601 && CONSTANT_P (XEXP (note, 0)))
4602 || ((note = find_reg_note (bl->init_insn, REG_EQUIV, 0)) != NULL
4603 && CONSTANT_P (XEXP (note, 0))))
4604 src = XEXP (note, 0);
4605 else
4606 src = SET_SRC (bl->init_set);
4608 if (loop_dump_stream)
4609 fprintf (loop_dump_stream,
4610 "Biv %d: initialized at insn %d: initial value ",
4611 bl->regno, INSN_UID (bl->init_insn));
4613 if ((GET_MODE (src) == GET_MODE (regno_reg_rtx[bl->regno])
4614 || GET_MODE (src) == VOIDmode)
4615 && valid_initial_value_p (src, bl->init_insn,
4616 LOOP_INFO (loop)->pre_header_has_call,
4617 loop->start))
4619 bl->initial_value = src;
4621 if (loop_dump_stream)
4623 print_simple_rtl (loop_dump_stream, src);
4624 fputc ('\n', loop_dump_stream);
4627 /* If we can't make it a giv,
4628 let biv keep initial value of "itself". */
4629 else if (loop_dump_stream)
4630 fprintf (loop_dump_stream, "is complex\n");
4635 /* Search the loop for general induction variables. */
4637 static void
4638 loop_givs_find (loop)
4639 struct loop* loop;
4641 for_each_insn_in_loop (loop, check_insn_for_givs);
4645 /* For each giv for which we still don't know whether or not it is
4646 replaceable, check to see if it is replaceable because its final value
4647 can be calculated. */
4649 static void
4650 loop_givs_check (loop)
4651 struct loop *loop;
4653 struct loop_ivs *ivs = LOOP_IVS (loop);
4654 struct iv_class *bl;
4656 for (bl = ivs->list; bl; bl = bl->next)
4658 struct induction *v;
4660 for (v = bl->giv; v; v = v->next_iv)
4661 if (! v->replaceable && ! v->not_replaceable)
4662 check_final_value (loop, v);
4667 /* Return nonzero if it is possible to eliminate the biv BL provided
4668 all givs are reduced. This is possible if either the reg is not
4669 used outside the loop, or we can compute what its final value will
4670 be. */
4672 static int
4673 loop_biv_eliminable_p (loop, bl, threshold, insn_count)
4674 struct loop *loop;
4675 struct iv_class *bl;
4676 int threshold;
4677 int insn_count;
4679 /* For architectures with a decrement_and_branch_until_zero insn,
4680 don't do this if we put a REG_NONNEG note on the endtest for this
4681 biv. */
4683 #ifdef HAVE_decrement_and_branch_until_zero
4684 if (bl->nonneg)
4686 if (loop_dump_stream)
4687 fprintf (loop_dump_stream,
4688 "Cannot eliminate nonneg biv %d.\n", bl->regno);
4689 return 0;
4691 #endif
4693 /* Check that biv is used outside loop or if it has a final value.
4694 Compare against bl->init_insn rather than loop->start. We aren't
4695 concerned with any uses of the biv between init_insn and
4696 loop->start since these won't be affected by the value of the biv
4697 elsewhere in the function, so long as init_insn doesn't use the
4698 biv itself. */
4700 if ((REGNO_LAST_LUID (bl->regno) < INSN_LUID (loop->end)
4701 && bl->init_insn
4702 && INSN_UID (bl->init_insn) < max_uid_for_loop
4703 && REGNO_FIRST_LUID (bl->regno) >= INSN_LUID (bl->init_insn)
4704 && ! reg_mentioned_p (bl->biv->dest_reg, SET_SRC (bl->init_set)))
4705 || (bl->final_value = final_biv_value (loop, bl)))
4706 return maybe_eliminate_biv (loop, bl, 0, threshold, insn_count);
4708 if (loop_dump_stream)
4710 fprintf (loop_dump_stream,
4711 "Cannot eliminate biv %d.\n",
4712 bl->regno);
4713 fprintf (loop_dump_stream,
4714 "First use: insn %d, last use: insn %d.\n",
4715 REGNO_FIRST_UID (bl->regno),
4716 REGNO_LAST_UID (bl->regno));
4718 return 0;
4722 /* Reduce each giv of BL that we have decided to reduce. */
4724 static void
4725 loop_givs_reduce (loop, bl)
4726 struct loop *loop;
4727 struct iv_class *bl;
4729 struct induction *v;
4731 for (v = bl->giv; v; v = v->next_iv)
4733 struct induction *tv;
4734 if (! v->ignore && v->same == 0)
4736 int auto_inc_opt = 0;
4738 /* If the code for derived givs immediately below has already
4739 allocated a new_reg, we must keep it. */
4740 if (! v->new_reg)
4741 v->new_reg = gen_reg_rtx (v->mode);
4743 #ifdef AUTO_INC_DEC
4744 /* If the target has auto-increment addressing modes, and
4745 this is an address giv, then try to put the increment
4746 immediately after its use, so that flow can create an
4747 auto-increment addressing mode. */
4748 if (v->giv_type == DEST_ADDR && bl->biv_count == 1
4749 && bl->biv->always_executed && ! bl->biv->maybe_multiple
4750 /* We don't handle reversed biv's because bl->biv->insn
4751 does not have a valid INSN_LUID. */
4752 && ! bl->reversed
4753 && v->always_executed && ! v->maybe_multiple
4754 && INSN_UID (v->insn) < max_uid_for_loop)
4756 /* If other giv's have been combined with this one, then
4757 this will work only if all uses of the other giv's occur
4758 before this giv's insn. This is difficult to check.
4760 We simplify this by looking for the common case where
4761 there is one DEST_REG giv, and this giv's insn is the
4762 last use of the dest_reg of that DEST_REG giv. If the
4763 increment occurs after the address giv, then we can
4764 perform the optimization. (Otherwise, the increment
4765 would have to go before other_giv, and we would not be
4766 able to combine it with the address giv to get an
4767 auto-inc address.) */
4768 if (v->combined_with)
4770 struct induction *other_giv = 0;
4772 for (tv = bl->giv; tv; tv = tv->next_iv)
4773 if (tv->same == v)
4775 if (other_giv)
4776 break;
4777 else
4778 other_giv = tv;
4780 if (! tv && other_giv
4781 && REGNO (other_giv->dest_reg) < max_reg_before_loop
4782 && (REGNO_LAST_UID (REGNO (other_giv->dest_reg))
4783 == INSN_UID (v->insn))
4784 && INSN_LUID (v->insn) < INSN_LUID (bl->biv->insn))
4785 auto_inc_opt = 1;
4787 /* Check for case where increment is before the address
4788 giv. Do this test in "loop order". */
4789 else if ((INSN_LUID (v->insn) > INSN_LUID (bl->biv->insn)
4790 && (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4791 || (INSN_LUID (bl->biv->insn)
4792 > INSN_LUID (loop->scan_start))))
4793 || (INSN_LUID (v->insn) < INSN_LUID (loop->scan_start)
4794 && (INSN_LUID (loop->scan_start)
4795 < INSN_LUID (bl->biv->insn))))
4796 auto_inc_opt = -1;
4797 else
4798 auto_inc_opt = 1;
4800 #ifdef HAVE_cc0
4802 rtx prev;
4804 /* We can't put an insn immediately after one setting
4805 cc0, or immediately before one using cc0. */
4806 if ((auto_inc_opt == 1 && sets_cc0_p (PATTERN (v->insn)))
4807 || (auto_inc_opt == -1
4808 && (prev = prev_nonnote_insn (v->insn)) != 0
4809 && INSN_P (prev)
4810 && sets_cc0_p (PATTERN (prev))))
4811 auto_inc_opt = 0;
4813 #endif
4815 if (auto_inc_opt)
4816 v->auto_inc_opt = 1;
4818 #endif
4820 /* For each place where the biv is incremented, add an insn
4821 to increment the new, reduced reg for the giv. */
4822 for (tv = bl->biv; tv; tv = tv->next_iv)
4824 rtx insert_before;
4826 /* Skip if location is the same as a previous one. */
4827 if (tv->same)
4828 continue;
4829 if (! auto_inc_opt)
4830 insert_before = NEXT_INSN (tv->insn);
4831 else if (auto_inc_opt == 1)
4832 insert_before = NEXT_INSN (v->insn);
4833 else
4834 insert_before = v->insn;
4836 if (tv->mult_val == const1_rtx)
4837 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4838 v->new_reg, v->new_reg,
4839 0, insert_before);
4840 else /* tv->mult_val == const0_rtx */
4841 /* A multiply is acceptable here
4842 since this is presumed to be seldom executed. */
4843 loop_iv_add_mult_emit_before (loop, tv->add_val, v->mult_val,
4844 v->add_val, v->new_reg,
4845 0, insert_before);
4848 /* Add code at loop start to initialize giv's reduced reg. */
4850 loop_iv_add_mult_hoist (loop,
4851 extend_value_for_giv (v, bl->initial_value),
4852 v->mult_val, v->add_val, v->new_reg);
4858 /* Check for givs whose first use is their definition and whose
4859 last use is the definition of another giv. If so, it is likely
4860 dead and should not be used to derive another giv nor to
4861 eliminate a biv. */
4863 static void
4864 loop_givs_dead_check (loop, bl)
4865 struct loop *loop ATTRIBUTE_UNUSED;
4866 struct iv_class *bl;
4868 struct induction *v;
4870 for (v = bl->giv; v; v = v->next_iv)
4872 if (v->ignore
4873 || (v->same && v->same->ignore))
4874 continue;
4876 if (v->giv_type == DEST_REG
4877 && REGNO_FIRST_UID (REGNO (v->dest_reg)) == INSN_UID (v->insn))
4879 struct induction *v1;
4881 for (v1 = bl->giv; v1; v1 = v1->next_iv)
4882 if (REGNO_LAST_UID (REGNO (v->dest_reg)) == INSN_UID (v1->insn))
4883 v->maybe_dead = 1;
4889 static void
4890 loop_givs_rescan (loop, bl, reg_map)
4891 struct loop *loop;
4892 struct iv_class *bl;
4893 rtx *reg_map;
4895 struct induction *v;
4897 for (v = bl->giv; v; v = v->next_iv)
4899 if (v->same && v->same->ignore)
4900 v->ignore = 1;
4902 if (v->ignore)
4903 continue;
4905 /* Update expression if this was combined, in case other giv was
4906 replaced. */
4907 if (v->same)
4908 v->new_reg = replace_rtx (v->new_reg,
4909 v->same->dest_reg, v->same->new_reg);
4911 /* See if this register is known to be a pointer to something. If
4912 so, see if we can find the alignment. First see if there is a
4913 destination register that is a pointer. If so, this shares the
4914 alignment too. Next see if we can deduce anything from the
4915 computational information. If not, and this is a DEST_ADDR
4916 giv, at least we know that it's a pointer, though we don't know
4917 the alignment. */
4918 if (GET_CODE (v->new_reg) == REG
4919 && v->giv_type == DEST_REG
4920 && REG_POINTER (v->dest_reg))
4921 mark_reg_pointer (v->new_reg,
4922 REGNO_POINTER_ALIGN (REGNO (v->dest_reg)));
4923 else if (GET_CODE (v->new_reg) == REG
4924 && REG_POINTER (v->src_reg))
4926 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->src_reg));
4928 if (align == 0
4929 || GET_CODE (v->add_val) != CONST_INT
4930 || INTVAL (v->add_val) % (align / BITS_PER_UNIT) != 0)
4931 align = 0;
4933 mark_reg_pointer (v->new_reg, align);
4935 else if (GET_CODE (v->new_reg) == REG
4936 && GET_CODE (v->add_val) == REG
4937 && REG_POINTER (v->add_val))
4939 unsigned int align = REGNO_POINTER_ALIGN (REGNO (v->add_val));
4941 if (align == 0 || GET_CODE (v->mult_val) != CONST_INT
4942 || INTVAL (v->mult_val) % (align / BITS_PER_UNIT) != 0)
4943 align = 0;
4945 mark_reg_pointer (v->new_reg, align);
4947 else if (GET_CODE (v->new_reg) == REG && v->giv_type == DEST_ADDR)
4948 mark_reg_pointer (v->new_reg, 0);
4950 if (v->giv_type == DEST_ADDR)
4951 /* Store reduced reg as the address in the memref where we found
4952 this giv. */
4953 validate_change (v->insn, v->location, v->new_reg, 0);
4954 else if (v->replaceable)
4956 reg_map[REGNO (v->dest_reg)] = v->new_reg;
4958 else
4960 rtx original_insn = v->insn;
4961 rtx note;
4963 /* Not replaceable; emit an insn to set the original giv reg from
4964 the reduced giv, same as above. */
4965 v->insn = loop_insn_emit_after (loop, 0, original_insn,
4966 gen_move_insn (v->dest_reg,
4967 v->new_reg));
4969 /* The original insn may have a REG_EQUAL note. This note is
4970 now incorrect and may result in invalid substitutions later.
4971 The original insn is dead, but may be part of a libcall
4972 sequence, which doesn't seem worth the bother of handling. */
4973 note = find_reg_note (original_insn, REG_EQUAL, NULL_RTX);
4974 if (note)
4975 remove_note (original_insn, note);
4978 /* When a loop is reversed, givs which depend on the reversed
4979 biv, and which are live outside the loop, must be set to their
4980 correct final value. This insn is only needed if the giv is
4981 not replaceable. The correct final value is the same as the
4982 value that the giv starts the reversed loop with. */
4983 if (bl->reversed && ! v->replaceable)
4984 loop_iv_add_mult_sink (loop,
4985 extend_value_for_giv (v, bl->initial_value),
4986 v->mult_val, v->add_val, v->dest_reg);
4987 else if (v->final_value)
4988 loop_insn_sink_or_swim (loop,
4989 gen_load_of_final_value (v->dest_reg,
4990 v->final_value));
4992 if (loop_dump_stream)
4994 fprintf (loop_dump_stream, "giv at %d reduced to ",
4995 INSN_UID (v->insn));
4996 print_simple_rtl (loop_dump_stream, v->new_reg);
4997 fprintf (loop_dump_stream, "\n");
5003 static int
5004 loop_giv_reduce_benefit (loop, bl, v, test_reg)
5005 struct loop *loop ATTRIBUTE_UNUSED;
5006 struct iv_class *bl;
5007 struct induction *v;
5008 rtx test_reg;
5010 int add_cost;
5011 int benefit;
5013 benefit = v->benefit;
5014 PUT_MODE (test_reg, v->mode);
5015 add_cost = iv_add_mult_cost (bl->biv->add_val, v->mult_val,
5016 test_reg, test_reg);
5018 /* Reduce benefit if not replaceable, since we will insert a
5019 move-insn to replace the insn that calculates this giv. Don't do
5020 this unless the giv is a user variable, since it will often be
5021 marked non-replaceable because of the duplication of the exit
5022 code outside the loop. In such a case, the copies we insert are
5023 dead and will be deleted. So they don't have a cost. Similar
5024 situations exist. */
5025 /* ??? The new final_[bg]iv_value code does a much better job of
5026 finding replaceable giv's, and hence this code may no longer be
5027 necessary. */
5028 if (! v->replaceable && ! bl->eliminable
5029 && REG_USERVAR_P (v->dest_reg))
5030 benefit -= copy_cost;
5032 /* Decrease the benefit to count the add-insns that we will insert
5033 to increment the reduced reg for the giv. ??? This can
5034 overestimate the run-time cost of the additional insns, e.g. if
5035 there are multiple basic blocks that increment the biv, but only
5036 one of these blocks is executed during each iteration. There is
5037 no good way to detect cases like this with the current structure
5038 of the loop optimizer. This code is more accurate for
5039 determining code size than run-time benefits. */
5040 benefit -= add_cost * bl->biv_count;
5042 /* Decide whether to strength-reduce this giv or to leave the code
5043 unchanged (recompute it from the biv each time it is used). This
5044 decision can be made independently for each giv. */
5046 #ifdef AUTO_INC_DEC
5047 /* Attempt to guess whether autoincrement will handle some of the
5048 new add insns; if so, increase BENEFIT (undo the subtraction of
5049 add_cost that was done above). */
5050 if (v->giv_type == DEST_ADDR
5051 /* Increasing the benefit is risky, since this is only a guess.
5052 Avoid increasing register pressure in cases where there would
5053 be no other benefit from reducing this giv. */
5054 && benefit > 0
5055 && GET_CODE (v->mult_val) == CONST_INT)
5057 int size = GET_MODE_SIZE (GET_MODE (v->mem));
5059 if (HAVE_POST_INCREMENT
5060 && INTVAL (v->mult_val) == size)
5061 benefit += add_cost * bl->biv_count;
5062 else if (HAVE_PRE_INCREMENT
5063 && INTVAL (v->mult_val) == size)
5064 benefit += add_cost * bl->biv_count;
5065 else if (HAVE_POST_DECREMENT
5066 && -INTVAL (v->mult_val) == size)
5067 benefit += add_cost * bl->biv_count;
5068 else if (HAVE_PRE_DECREMENT
5069 && -INTVAL (v->mult_val) == size)
5070 benefit += add_cost * bl->biv_count;
5072 #endif
5074 return benefit;
5078 /* Free IV structures for LOOP. */
5080 static void
5081 loop_ivs_free (loop)
5082 struct loop *loop;
5084 struct loop_ivs *ivs = LOOP_IVS (loop);
5085 struct iv_class *iv = ivs->list;
5087 free (ivs->regs);
5089 while (iv)
5091 struct iv_class *next = iv->next;
5092 struct induction *induction;
5093 struct induction *next_induction;
5095 for (induction = iv->biv; induction; induction = next_induction)
5097 next_induction = induction->next_iv;
5098 free (induction);
5100 for (induction = iv->giv; induction; induction = next_induction)
5102 next_induction = induction->next_iv;
5103 free (induction);
5106 free (iv);
5107 iv = next;
5112 /* Perform strength reduction and induction variable elimination.
5114 Pseudo registers created during this function will be beyond the
5115 last valid index in several tables including
5116 REGS->ARRAY[I].N_TIMES_SET and REGNO_LAST_UID. This does not cause a
5117 problem here, because the added registers cannot be givs outside of
5118 their loop, and hence will never be reconsidered. But scan_loop
5119 must check regnos to make sure they are in bounds. */
5121 static void
5122 strength_reduce (loop, flags)
5123 struct loop *loop;
5124 int flags;
5126 struct loop_info *loop_info = LOOP_INFO (loop);
5127 struct loop_regs *regs = LOOP_REGS (loop);
5128 struct loop_ivs *ivs = LOOP_IVS (loop);
5129 rtx p;
5130 /* Temporary list pointer for traversing ivs->list. */
5131 struct iv_class *bl;
5132 /* Ratio of extra register life span we can justify
5133 for saving an instruction. More if loop doesn't call subroutines
5134 since in that case saving an insn makes more difference
5135 and more registers are available. */
5136 /* ??? could set this to last value of threshold in move_movables */
5137 int threshold = (loop_info->has_call ? 1 : 2) * (3 + n_non_fixed_regs);
5138 /* Map of pseudo-register replacements. */
5139 rtx *reg_map = NULL;
5140 int reg_map_size;
5141 int unrolled_insn_copies = 0;
5142 rtx test_reg = gen_rtx_REG (word_mode, LAST_VIRTUAL_REGISTER + 1);
5143 int insn_count = count_insns_in_loop (loop);
5145 addr_placeholder = gen_reg_rtx (Pmode);
5147 ivs->n_regs = max_reg_before_loop;
5148 ivs->regs = (struct iv *) xcalloc (ivs->n_regs, sizeof (struct iv));
5150 /* Find all BIVs in loop. */
5151 loop_bivs_find (loop);
5153 /* Exit if there are no bivs. */
5154 if (! ivs->list)
5156 /* Can still unroll the loop anyways, but indicate that there is no
5157 strength reduction info available. */
5158 if (flags & LOOP_UNROLL)
5159 unroll_loop (loop, insn_count, 0);
5161 loop_ivs_free (loop);
5162 return;
5165 /* Determine how BIVS are initialized by looking through pre-header
5166 extended basic block. */
5167 loop_bivs_init_find (loop);
5169 /* Look at the each biv and see if we can say anything better about its
5170 initial value from any initializing insns set up above. */
5171 loop_bivs_check (loop);
5173 /* Search the loop for general induction variables. */
5174 loop_givs_find (loop);
5176 /* Try to calculate and save the number of loop iterations. This is
5177 set to zero if the actual number can not be calculated. This must
5178 be called after all giv's have been identified, since otherwise it may
5179 fail if the iteration variable is a giv. */
5180 loop_iterations (loop);
5182 #ifdef HAVE_prefetch
5183 if (flags & LOOP_PREFETCH)
5184 emit_prefetch_instructions (loop);
5185 #endif
5187 /* Now for each giv for which we still don't know whether or not it is
5188 replaceable, check to see if it is replaceable because its final value
5189 can be calculated. This must be done after loop_iterations is called,
5190 so that final_giv_value will work correctly. */
5191 loop_givs_check (loop);
5193 /* Try to prove that the loop counter variable (if any) is always
5194 nonnegative; if so, record that fact with a REG_NONNEG note
5195 so that "decrement and branch until zero" insn can be used. */
5196 check_dbra_loop (loop, insn_count);
5198 /* Create reg_map to hold substitutions for replaceable giv regs.
5199 Some givs might have been made from biv increments, so look at
5200 ivs->reg_iv_type for a suitable size. */
5201 reg_map_size = ivs->n_regs;
5202 reg_map = (rtx *) xcalloc (reg_map_size, sizeof (rtx));
5204 /* Examine each iv class for feasibility of strength reduction/induction
5205 variable elimination. */
5207 for (bl = ivs->list; bl; bl = bl->next)
5209 struct induction *v;
5210 int benefit;
5212 /* Test whether it will be possible to eliminate this biv
5213 provided all givs are reduced. */
5214 bl->eliminable = loop_biv_eliminable_p (loop, bl, threshold, insn_count);
5216 /* This will be true at the end, if all givs which depend on this
5217 biv have been strength reduced.
5218 We can't (currently) eliminate the biv unless this is so. */
5219 bl->all_reduced = 1;
5221 /* Check each extension dependent giv in this class to see if its
5222 root biv is safe from wrapping in the interior mode. */
5223 check_ext_dependent_givs (bl, loop_info);
5225 /* Combine all giv's for this iv_class. */
5226 combine_givs (regs, bl);
5228 for (v = bl->giv; v; v = v->next_iv)
5230 struct induction *tv;
5232 if (v->ignore || v->same)
5233 continue;
5235 benefit = loop_giv_reduce_benefit (loop, bl, v, test_reg);
5237 /* If an insn is not to be strength reduced, then set its ignore
5238 flag, and clear bl->all_reduced. */
5240 /* A giv that depends on a reversed biv must be reduced if it is
5241 used after the loop exit, otherwise, it would have the wrong
5242 value after the loop exit. To make it simple, just reduce all
5243 of such giv's whether or not we know they are used after the loop
5244 exit. */
5246 if (! flag_reduce_all_givs
5247 && v->lifetime * threshold * benefit < insn_count
5248 && ! bl->reversed)
5250 if (loop_dump_stream)
5251 fprintf (loop_dump_stream,
5252 "giv of insn %d not worth while, %d vs %d.\n",
5253 INSN_UID (v->insn),
5254 v->lifetime * threshold * benefit, insn_count);
5255 v->ignore = 1;
5256 bl->all_reduced = 0;
5258 else
5260 /* Check that we can increment the reduced giv without a
5261 multiply insn. If not, reject it. */
5263 for (tv = bl->biv; tv; tv = tv->next_iv)
5264 if (tv->mult_val == const1_rtx
5265 && ! product_cheap_p (tv->add_val, v->mult_val))
5267 if (loop_dump_stream)
5268 fprintf (loop_dump_stream,
5269 "giv of insn %d: would need a multiply.\n",
5270 INSN_UID (v->insn));
5271 v->ignore = 1;
5272 bl->all_reduced = 0;
5273 break;
5278 /* Check for givs whose first use is their definition and whose
5279 last use is the definition of another giv. If so, it is likely
5280 dead and should not be used to derive another giv nor to
5281 eliminate a biv. */
5282 loop_givs_dead_check (loop, bl);
5284 /* Reduce each giv that we decided to reduce. */
5285 loop_givs_reduce (loop, bl);
5287 /* Rescan all givs. If a giv is the same as a giv not reduced, mark it
5288 as not reduced.
5290 For each giv register that can be reduced now: if replaceable,
5291 substitute reduced reg wherever the old giv occurs;
5292 else add new move insn "giv_reg = reduced_reg". */
5293 loop_givs_rescan (loop, bl, reg_map);
5295 /* All the givs based on the biv bl have been reduced if they
5296 merit it. */
5298 /* For each giv not marked as maybe dead that has been combined with a
5299 second giv, clear any "maybe dead" mark on that second giv.
5300 v->new_reg will either be or refer to the register of the giv it
5301 combined with.
5303 Doing this clearing avoids problems in biv elimination where
5304 a giv's new_reg is a complex value that can't be put in the
5305 insn but the giv combined with (with a reg as new_reg) is
5306 marked maybe_dead. Since the register will be used in either
5307 case, we'd prefer it be used from the simpler giv. */
5309 for (v = bl->giv; v; v = v->next_iv)
5310 if (! v->maybe_dead && v->same)
5311 v->same->maybe_dead = 0;
5313 /* Try to eliminate the biv, if it is a candidate.
5314 This won't work if ! bl->all_reduced,
5315 since the givs we planned to use might not have been reduced.
5317 We have to be careful that we didn't initially think we could
5318 eliminate this biv because of a giv that we now think may be
5319 dead and shouldn't be used as a biv replacement.
5321 Also, there is the possibility that we may have a giv that looks
5322 like it can be used to eliminate a biv, but the resulting insn
5323 isn't valid. This can happen, for example, on the 88k, where a
5324 JUMP_INSN can compare a register only with zero. Attempts to
5325 replace it with a compare with a constant will fail.
5327 Note that in cases where this call fails, we may have replaced some
5328 of the occurrences of the biv with a giv, but no harm was done in
5329 doing so in the rare cases where it can occur. */
5331 if (bl->all_reduced == 1 && bl->eliminable
5332 && maybe_eliminate_biv (loop, bl, 1, threshold, insn_count))
5334 /* ?? If we created a new test to bypass the loop entirely,
5335 or otherwise drop straight in, based on this test, then
5336 we might want to rewrite it also. This way some later
5337 pass has more hope of removing the initialization of this
5338 biv entirely. */
5340 /* If final_value != 0, then the biv may be used after loop end
5341 and we must emit an insn to set it just in case.
5343 Reversed bivs already have an insn after the loop setting their
5344 value, so we don't need another one. We can't calculate the
5345 proper final value for such a biv here anyways. */
5346 if (bl->final_value && ! bl->reversed)
5347 loop_insn_sink_or_swim (loop,
5348 gen_load_of_final_value (bl->biv->dest_reg,
5349 bl->final_value));
5351 if (loop_dump_stream)
5352 fprintf (loop_dump_stream, "Reg %d: biv eliminated\n",
5353 bl->regno);
5355 /* See above note wrt final_value. But since we couldn't eliminate
5356 the biv, we must set the value after the loop instead of before. */
5357 else if (bl->final_value && ! bl->reversed)
5358 loop_insn_sink (loop, gen_load_of_final_value (bl->biv->dest_reg,
5359 bl->final_value));
5362 /* Go through all the instructions in the loop, making all the
5363 register substitutions scheduled in REG_MAP. */
5365 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
5366 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5367 || GET_CODE (p) == CALL_INSN)
5369 replace_regs (PATTERN (p), reg_map, reg_map_size, 0);
5370 replace_regs (REG_NOTES (p), reg_map, reg_map_size, 0);
5371 INSN_CODE (p) = -1;
5374 if (loop_info->n_iterations > 0)
5376 /* When we completely unroll a loop we will likely not need the increment
5377 of the loop BIV and we will not need the conditional branch at the
5378 end of the loop. */
5379 unrolled_insn_copies = insn_count - 2;
5381 #ifdef HAVE_cc0
5382 /* When we completely unroll a loop on a HAVE_cc0 machine we will not
5383 need the comparison before the conditional branch at the end of the
5384 loop. */
5385 unrolled_insn_copies -= 1;
5386 #endif
5388 /* We'll need one copy for each loop iteration. */
5389 unrolled_insn_copies *= loop_info->n_iterations;
5391 /* A little slop to account for the ability to remove initialization
5392 code, better CSE, and other secondary benefits of completely
5393 unrolling some loops. */
5394 unrolled_insn_copies -= 1;
5396 /* Clamp the value. */
5397 if (unrolled_insn_copies < 0)
5398 unrolled_insn_copies = 0;
5401 /* Unroll loops from within strength reduction so that we can use the
5402 induction variable information that strength_reduce has already
5403 collected. Always unroll loops that would be as small or smaller
5404 unrolled than when rolled. */
5405 if ((flags & LOOP_UNROLL)
5406 || ((flags & LOOP_AUTO_UNROLL)
5407 && loop_info->n_iterations > 0
5408 && unrolled_insn_copies <= insn_count))
5409 unroll_loop (loop, insn_count, 1);
5411 #ifdef HAVE_doloop_end
5412 if (HAVE_doloop_end && (flags & LOOP_BCT) && flag_branch_on_count_reg)
5413 doloop_optimize (loop);
5414 #endif /* HAVE_doloop_end */
5416 /* In case number of iterations is known, drop branch prediction note
5417 in the branch. Do that only in second loop pass, as loop unrolling
5418 may change the number of iterations performed. */
5419 if (flags & LOOP_BCT)
5421 unsigned HOST_WIDE_INT n
5422 = loop_info->n_iterations / loop_info->unroll_number;
5423 if (n > 1)
5424 predict_insn (prev_nonnote_insn (loop->end), PRED_LOOP_ITERATIONS,
5425 REG_BR_PROB_BASE - REG_BR_PROB_BASE / n);
5428 if (loop_dump_stream)
5429 fprintf (loop_dump_stream, "\n");
5431 loop_ivs_free (loop);
5432 if (reg_map)
5433 free (reg_map);
5436 /*Record all basic induction variables calculated in the insn. */
5437 static rtx
5438 check_insn_for_bivs (loop, p, not_every_iteration, maybe_multiple)
5439 struct loop *loop;
5440 rtx p;
5441 int not_every_iteration;
5442 int maybe_multiple;
5444 struct loop_ivs *ivs = LOOP_IVS (loop);
5445 rtx set;
5446 rtx dest_reg;
5447 rtx inc_val;
5448 rtx mult_val;
5449 rtx *location;
5451 if (GET_CODE (p) == INSN
5452 && (set = single_set (p))
5453 && GET_CODE (SET_DEST (set)) == REG)
5455 dest_reg = SET_DEST (set);
5456 if (REGNO (dest_reg) < max_reg_before_loop
5457 && REGNO (dest_reg) >= FIRST_PSEUDO_REGISTER
5458 && REG_IV_TYPE (ivs, REGNO (dest_reg)) != NOT_BASIC_INDUCT)
5460 if (basic_induction_var (loop, SET_SRC (set),
5461 GET_MODE (SET_SRC (set)),
5462 dest_reg, p, &inc_val, &mult_val,
5463 &location))
5465 /* It is a possible basic induction variable.
5466 Create and initialize an induction structure for it. */
5468 struct induction *v
5469 = (struct induction *) xmalloc (sizeof (struct induction));
5471 record_biv (loop, v, p, dest_reg, inc_val, mult_val, location,
5472 not_every_iteration, maybe_multiple);
5473 REG_IV_TYPE (ivs, REGNO (dest_reg)) = BASIC_INDUCT;
5475 else if (REGNO (dest_reg) < ivs->n_regs)
5476 REG_IV_TYPE (ivs, REGNO (dest_reg)) = NOT_BASIC_INDUCT;
5479 return p;
5482 /* Record all givs calculated in the insn.
5483 A register is a giv if: it is only set once, it is a function of a
5484 biv and a constant (or invariant), and it is not a biv. */
5485 static rtx
5486 check_insn_for_givs (loop, p, not_every_iteration, maybe_multiple)
5487 struct loop *loop;
5488 rtx p;
5489 int not_every_iteration;
5490 int maybe_multiple;
5492 struct loop_regs *regs = LOOP_REGS (loop);
5494 rtx set;
5495 /* Look for a general induction variable in a register. */
5496 if (GET_CODE (p) == INSN
5497 && (set = single_set (p))
5498 && GET_CODE (SET_DEST (set)) == REG
5499 && ! regs->array[REGNO (SET_DEST (set))].may_not_optimize)
5501 rtx src_reg;
5502 rtx dest_reg;
5503 rtx add_val;
5504 rtx mult_val;
5505 rtx ext_val;
5506 int benefit;
5507 rtx regnote = 0;
5508 rtx last_consec_insn;
5510 dest_reg = SET_DEST (set);
5511 if (REGNO (dest_reg) < FIRST_PSEUDO_REGISTER)
5512 return p;
5514 if (/* SET_SRC is a giv. */
5515 (general_induction_var (loop, SET_SRC (set), &src_reg, &add_val,
5516 &mult_val, &ext_val, 0, &benefit, VOIDmode)
5517 /* Equivalent expression is a giv. */
5518 || ((regnote = find_reg_note (p, REG_EQUAL, NULL_RTX))
5519 && general_induction_var (loop, XEXP (regnote, 0), &src_reg,
5520 &add_val, &mult_val, &ext_val, 0,
5521 &benefit, VOIDmode)))
5522 /* Don't try to handle any regs made by loop optimization.
5523 We have nothing on them in regno_first_uid, etc. */
5524 && REGNO (dest_reg) < max_reg_before_loop
5525 /* Don't recognize a BASIC_INDUCT_VAR here. */
5526 && dest_reg != src_reg
5527 /* This must be the only place where the register is set. */
5528 && (regs->array[REGNO (dest_reg)].n_times_set == 1
5529 /* or all sets must be consecutive and make a giv. */
5530 || (benefit = consec_sets_giv (loop, benefit, p,
5531 src_reg, dest_reg,
5532 &add_val, &mult_val, &ext_val,
5533 &last_consec_insn))))
5535 struct induction *v
5536 = (struct induction *) xmalloc (sizeof (struct induction));
5538 /* If this is a library call, increase benefit. */
5539 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
5540 benefit += libcall_benefit (p);
5542 /* Skip the consecutive insns, if there are any. */
5543 if (regs->array[REGNO (dest_reg)].n_times_set != 1)
5544 p = last_consec_insn;
5546 record_giv (loop, v, p, src_reg, dest_reg, mult_val, add_val,
5547 ext_val, benefit, DEST_REG, not_every_iteration,
5548 maybe_multiple, (rtx*) 0);
5553 #ifndef DONT_REDUCE_ADDR
5554 /* Look for givs which are memory addresses. */
5555 /* This resulted in worse code on a VAX 8600. I wonder if it
5556 still does. */
5557 if (GET_CODE (p) == INSN)
5558 find_mem_givs (loop, PATTERN (p), p, not_every_iteration,
5559 maybe_multiple);
5560 #endif
5562 /* Update the status of whether giv can derive other givs. This can
5563 change when we pass a label or an insn that updates a biv. */
5564 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
5565 || GET_CODE (p) == CODE_LABEL)
5566 update_giv_derive (loop, p);
5567 return p;
5570 /* Return 1 if X is a valid source for an initial value (or as value being
5571 compared against in an initial test).
5573 X must be either a register or constant and must not be clobbered between
5574 the current insn and the start of the loop.
5576 INSN is the insn containing X. */
5578 static int
5579 valid_initial_value_p (x, insn, call_seen, loop_start)
5580 rtx x;
5581 rtx insn;
5582 int call_seen;
5583 rtx loop_start;
5585 if (CONSTANT_P (x))
5586 return 1;
5588 /* Only consider pseudos we know about initialized in insns whose luids
5589 we know. */
5590 if (GET_CODE (x) != REG
5591 || REGNO (x) >= max_reg_before_loop)
5592 return 0;
5594 /* Don't use call-clobbered registers across a call which clobbers it. On
5595 some machines, don't use any hard registers at all. */
5596 if (REGNO (x) < FIRST_PSEUDO_REGISTER
5597 && (SMALL_REGISTER_CLASSES
5598 || (call_used_regs[REGNO (x)] && call_seen)))
5599 return 0;
5601 /* Don't use registers that have been clobbered before the start of the
5602 loop. */
5603 if (reg_set_between_p (x, insn, loop_start))
5604 return 0;
5606 return 1;
5609 /* Scan X for memory refs and check each memory address
5610 as a possible giv. INSN is the insn whose pattern X comes from.
5611 NOT_EVERY_ITERATION is 1 if the insn might not be executed during
5612 every loop iteration. MAYBE_MULTIPLE is 1 if the insn might be executed
5613 more than once in each loop iteration. */
5615 static void
5616 find_mem_givs (loop, x, insn, not_every_iteration, maybe_multiple)
5617 const struct loop *loop;
5618 rtx x;
5619 rtx insn;
5620 int not_every_iteration, maybe_multiple;
5622 int i, j;
5623 enum rtx_code code;
5624 const char *fmt;
5626 if (x == 0)
5627 return;
5629 code = GET_CODE (x);
5630 switch (code)
5632 case REG:
5633 case CONST_INT:
5634 case CONST:
5635 case CONST_DOUBLE:
5636 case SYMBOL_REF:
5637 case LABEL_REF:
5638 case PC:
5639 case CC0:
5640 case ADDR_VEC:
5641 case ADDR_DIFF_VEC:
5642 case USE:
5643 case CLOBBER:
5644 return;
5646 case MEM:
5648 rtx src_reg;
5649 rtx add_val;
5650 rtx mult_val;
5651 rtx ext_val;
5652 int benefit;
5654 /* This code used to disable creating GIVs with mult_val == 1 and
5655 add_val == 0. However, this leads to lost optimizations when
5656 it comes time to combine a set of related DEST_ADDR GIVs, since
5657 this one would not be seen. */
5659 if (general_induction_var (loop, XEXP (x, 0), &src_reg, &add_val,
5660 &mult_val, &ext_val, 1, &benefit,
5661 GET_MODE (x)))
5663 /* Found one; record it. */
5664 struct induction *v
5665 = (struct induction *) xmalloc (sizeof (struct induction));
5667 record_giv (loop, v, insn, src_reg, addr_placeholder, mult_val,
5668 add_val, ext_val, benefit, DEST_ADDR,
5669 not_every_iteration, maybe_multiple, &XEXP (x, 0));
5671 v->mem = x;
5674 return;
5676 default:
5677 break;
5680 /* Recursively scan the subexpressions for other mem refs. */
5682 fmt = GET_RTX_FORMAT (code);
5683 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
5684 if (fmt[i] == 'e')
5685 find_mem_givs (loop, XEXP (x, i), insn, not_every_iteration,
5686 maybe_multiple);
5687 else if (fmt[i] == 'E')
5688 for (j = 0; j < XVECLEN (x, i); j++)
5689 find_mem_givs (loop, XVECEXP (x, i, j), insn, not_every_iteration,
5690 maybe_multiple);
5693 /* Fill in the data about one biv update.
5694 V is the `struct induction' in which we record the biv. (It is
5695 allocated by the caller, with alloca.)
5696 INSN is the insn that sets it.
5697 DEST_REG is the biv's reg.
5699 MULT_VAL is const1_rtx if the biv is being incremented here, in which case
5700 INC_VAL is the increment. Otherwise, MULT_VAL is const0_rtx and the biv is
5701 being set to INC_VAL.
5703 NOT_EVERY_ITERATION is nonzero if this biv update is not know to be
5704 executed every iteration; MAYBE_MULTIPLE is nonzero if this biv update
5705 can be executed more than once per iteration. If MAYBE_MULTIPLE
5706 and NOT_EVERY_ITERATION are both zero, we know that the biv update is
5707 executed exactly once per iteration. */
5709 static void
5710 record_biv (loop, v, insn, dest_reg, inc_val, mult_val, location,
5711 not_every_iteration, maybe_multiple)
5712 struct loop *loop;
5713 struct induction *v;
5714 rtx insn;
5715 rtx dest_reg;
5716 rtx inc_val;
5717 rtx mult_val;
5718 rtx *location;
5719 int not_every_iteration;
5720 int maybe_multiple;
5722 struct loop_ivs *ivs = LOOP_IVS (loop);
5723 struct iv_class *bl;
5725 v->insn = insn;
5726 v->src_reg = dest_reg;
5727 v->dest_reg = dest_reg;
5728 v->mult_val = mult_val;
5729 v->add_val = inc_val;
5730 v->ext_dependent = NULL_RTX;
5731 v->location = location;
5732 v->mode = GET_MODE (dest_reg);
5733 v->always_computable = ! not_every_iteration;
5734 v->always_executed = ! not_every_iteration;
5735 v->maybe_multiple = maybe_multiple;
5736 v->same = 0;
5738 /* Add this to the reg's iv_class, creating a class
5739 if this is the first incrementation of the reg. */
5741 bl = REG_IV_CLASS (ivs, REGNO (dest_reg));
5742 if (bl == 0)
5744 /* Create and initialize new iv_class. */
5746 bl = (struct iv_class *) xmalloc (sizeof (struct iv_class));
5748 bl->regno = REGNO (dest_reg);
5749 bl->biv = 0;
5750 bl->giv = 0;
5751 bl->biv_count = 0;
5752 bl->giv_count = 0;
5754 /* Set initial value to the reg itself. */
5755 bl->initial_value = dest_reg;
5756 bl->final_value = 0;
5757 /* We haven't seen the initializing insn yet */
5758 bl->init_insn = 0;
5759 bl->init_set = 0;
5760 bl->initial_test = 0;
5761 bl->incremented = 0;
5762 bl->eliminable = 0;
5763 bl->nonneg = 0;
5764 bl->reversed = 0;
5765 bl->total_benefit = 0;
5767 /* Add this class to ivs->list. */
5768 bl->next = ivs->list;
5769 ivs->list = bl;
5771 /* Put it in the array of biv register classes. */
5772 REG_IV_CLASS (ivs, REGNO (dest_reg)) = bl;
5774 else
5776 /* Check if location is the same as a previous one. */
5777 struct induction *induction;
5778 for (induction = bl->biv; induction; induction = induction->next_iv)
5779 if (location == induction->location)
5781 v->same = induction;
5782 break;
5786 /* Update IV_CLASS entry for this biv. */
5787 v->next_iv = bl->biv;
5788 bl->biv = v;
5789 bl->biv_count++;
5790 if (mult_val == const1_rtx)
5791 bl->incremented = 1;
5793 if (loop_dump_stream)
5794 loop_biv_dump (v, loop_dump_stream, 0);
5797 /* Fill in the data about one giv.
5798 V is the `struct induction' in which we record the giv. (It is
5799 allocated by the caller, with alloca.)
5800 INSN is the insn that sets it.
5801 BENEFIT estimates the savings from deleting this insn.
5802 TYPE is DEST_REG or DEST_ADDR; it says whether the giv is computed
5803 into a register or is used as a memory address.
5805 SRC_REG is the biv reg which the giv is computed from.
5806 DEST_REG is the giv's reg (if the giv is stored in a reg).
5807 MULT_VAL and ADD_VAL are the coefficients used to compute the giv.
5808 LOCATION points to the place where this giv's value appears in INSN. */
5810 static void
5811 record_giv (loop, v, insn, src_reg, dest_reg, mult_val, add_val, ext_val,
5812 benefit, type, not_every_iteration, maybe_multiple, location)
5813 const struct loop *loop;
5814 struct induction *v;
5815 rtx insn;
5816 rtx src_reg;
5817 rtx dest_reg;
5818 rtx mult_val, add_val, ext_val;
5819 int benefit;
5820 enum g_types type;
5821 int not_every_iteration, maybe_multiple;
5822 rtx *location;
5824 struct loop_ivs *ivs = LOOP_IVS (loop);
5825 struct induction *b;
5826 struct iv_class *bl;
5827 rtx set = single_set (insn);
5828 rtx temp;
5830 /* Attempt to prove constantness of the values. Don't let simplify_rtx
5831 undo the MULT canonicalization that we performed earlier. */
5832 temp = simplify_rtx (add_val);
5833 if (temp
5834 && ! (GET_CODE (add_val) == MULT
5835 && GET_CODE (temp) == ASHIFT))
5836 add_val = temp;
5838 v->insn = insn;
5839 v->src_reg = src_reg;
5840 v->giv_type = type;
5841 v->dest_reg = dest_reg;
5842 v->mult_val = mult_val;
5843 v->add_val = add_val;
5844 v->ext_dependent = ext_val;
5845 v->benefit = benefit;
5846 v->location = location;
5847 v->cant_derive = 0;
5848 v->combined_with = 0;
5849 v->maybe_multiple = maybe_multiple;
5850 v->maybe_dead = 0;
5851 v->derive_adjustment = 0;
5852 v->same = 0;
5853 v->ignore = 0;
5854 v->new_reg = 0;
5855 v->final_value = 0;
5856 v->same_insn = 0;
5857 v->auto_inc_opt = 0;
5858 v->unrolled = 0;
5859 v->shared = 0;
5861 /* The v->always_computable field is used in update_giv_derive, to
5862 determine whether a giv can be used to derive another giv. For a
5863 DEST_REG giv, INSN computes a new value for the giv, so its value
5864 isn't computable if INSN insn't executed every iteration.
5865 However, for a DEST_ADDR giv, INSN merely uses the value of the giv;
5866 it does not compute a new value. Hence the value is always computable
5867 regardless of whether INSN is executed each iteration. */
5869 if (type == DEST_ADDR)
5870 v->always_computable = 1;
5871 else
5872 v->always_computable = ! not_every_iteration;
5874 v->always_executed = ! not_every_iteration;
5876 if (type == DEST_ADDR)
5878 v->mode = GET_MODE (*location);
5879 v->lifetime = 1;
5881 else /* type == DEST_REG */
5883 v->mode = GET_MODE (SET_DEST (set));
5885 v->lifetime = LOOP_REG_LIFETIME (loop, REGNO (dest_reg));
5887 /* If the lifetime is zero, it means that this register is
5888 really a dead store. So mark this as a giv that can be
5889 ignored. This will not prevent the biv from being eliminated. */
5890 if (v->lifetime == 0)
5891 v->ignore = 1;
5893 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
5894 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
5897 /* Add the giv to the class of givs computed from one biv. */
5899 bl = REG_IV_CLASS (ivs, REGNO (src_reg));
5900 if (bl)
5902 v->next_iv = bl->giv;
5903 bl->giv = v;
5904 /* Don't count DEST_ADDR. This is supposed to count the number of
5905 insns that calculate givs. */
5906 if (type == DEST_REG)
5907 bl->giv_count++;
5908 bl->total_benefit += benefit;
5910 else
5911 /* Fatal error, biv missing for this giv? */
5912 abort ();
5914 if (type == DEST_ADDR)
5916 v->replaceable = 1;
5917 v->not_replaceable = 0;
5919 else
5921 /* The giv can be replaced outright by the reduced register only if all
5922 of the following conditions are true:
5923 - the insn that sets the giv is always executed on any iteration
5924 on which the giv is used at all
5925 (there are two ways to deduce this:
5926 either the insn is executed on every iteration,
5927 or all uses follow that insn in the same basic block),
5928 - the giv is not used outside the loop
5929 - no assignments to the biv occur during the giv's lifetime. */
5931 if (REGNO_FIRST_UID (REGNO (dest_reg)) == INSN_UID (insn)
5932 /* Previous line always fails if INSN was moved by loop opt. */
5933 && REGNO_LAST_LUID (REGNO (dest_reg))
5934 < INSN_LUID (loop->end)
5935 && (! not_every_iteration
5936 || last_use_this_basic_block (dest_reg, insn)))
5938 /* Now check that there are no assignments to the biv within the
5939 giv's lifetime. This requires two separate checks. */
5941 /* Check each biv update, and fail if any are between the first
5942 and last use of the giv.
5944 If this loop contains an inner loop that was unrolled, then
5945 the insn modifying the biv may have been emitted by the loop
5946 unrolling code, and hence does not have a valid luid. Just
5947 mark the biv as not replaceable in this case. It is not very
5948 useful as a biv, because it is used in two different loops.
5949 It is very unlikely that we would be able to optimize the giv
5950 using this biv anyways. */
5952 v->replaceable = 1;
5953 v->not_replaceable = 0;
5954 for (b = bl->biv; b; b = b->next_iv)
5956 if (INSN_UID (b->insn) >= max_uid_for_loop
5957 || ((INSN_LUID (b->insn)
5958 >= REGNO_FIRST_LUID (REGNO (dest_reg)))
5959 && (INSN_LUID (b->insn)
5960 <= REGNO_LAST_LUID (REGNO (dest_reg)))))
5962 v->replaceable = 0;
5963 v->not_replaceable = 1;
5964 break;
5968 /* If there are any backwards branches that go from after the
5969 biv update to before it, then this giv is not replaceable. */
5970 if (v->replaceable)
5971 for (b = bl->biv; b; b = b->next_iv)
5972 if (back_branch_in_range_p (loop, b->insn))
5974 v->replaceable = 0;
5975 v->not_replaceable = 1;
5976 break;
5979 else
5981 /* May still be replaceable, we don't have enough info here to
5982 decide. */
5983 v->replaceable = 0;
5984 v->not_replaceable = 0;
5988 /* Record whether the add_val contains a const_int, for later use by
5989 combine_givs. */
5991 rtx tem = add_val;
5993 v->no_const_addval = 1;
5994 if (tem == const0_rtx)
5996 else if (CONSTANT_P (add_val))
5997 v->no_const_addval = 0;
5998 if (GET_CODE (tem) == PLUS)
6000 while (1)
6002 if (GET_CODE (XEXP (tem, 0)) == PLUS)
6003 tem = XEXP (tem, 0);
6004 else if (GET_CODE (XEXP (tem, 1)) == PLUS)
6005 tem = XEXP (tem, 1);
6006 else
6007 break;
6009 if (CONSTANT_P (XEXP (tem, 1)))
6010 v->no_const_addval = 0;
6014 if (loop_dump_stream)
6015 loop_giv_dump (v, loop_dump_stream, 0);
6018 /* All this does is determine whether a giv can be made replaceable because
6019 its final value can be calculated. This code can not be part of record_giv
6020 above, because final_giv_value requires that the number of loop iterations
6021 be known, and that can not be accurately calculated until after all givs
6022 have been identified. */
6024 static void
6025 check_final_value (loop, v)
6026 const struct loop *loop;
6027 struct induction *v;
6029 rtx final_value = 0;
6031 /* DEST_ADDR givs will never reach here, because they are always marked
6032 replaceable above in record_giv. */
6034 /* The giv can be replaced outright by the reduced register only if all
6035 of the following conditions are true:
6036 - the insn that sets the giv is always executed on any iteration
6037 on which the giv is used at all
6038 (there are two ways to deduce this:
6039 either the insn is executed on every iteration,
6040 or all uses follow that insn in the same basic block),
6041 - its final value can be calculated (this condition is different
6042 than the one above in record_giv)
6043 - it's not used before the it's set
6044 - no assignments to the biv occur during the giv's lifetime. */
6046 #if 0
6047 /* This is only called now when replaceable is known to be false. */
6048 /* Clear replaceable, so that it won't confuse final_giv_value. */
6049 v->replaceable = 0;
6050 #endif
6052 if ((final_value = final_giv_value (loop, v))
6053 && (v->always_executed
6054 || last_use_this_basic_block (v->dest_reg, v->insn)))
6056 int biv_increment_seen = 0, before_giv_insn = 0;
6057 rtx p = v->insn;
6058 rtx last_giv_use;
6060 v->replaceable = 1;
6061 v->not_replaceable = 0;
6063 /* When trying to determine whether or not a biv increment occurs
6064 during the lifetime of the giv, we can ignore uses of the variable
6065 outside the loop because final_value is true. Hence we can not
6066 use regno_last_uid and regno_first_uid as above in record_giv. */
6068 /* Search the loop to determine whether any assignments to the
6069 biv occur during the giv's lifetime. Start with the insn
6070 that sets the giv, and search around the loop until we come
6071 back to that insn again.
6073 Also fail if there is a jump within the giv's lifetime that jumps
6074 to somewhere outside the lifetime but still within the loop. This
6075 catches spaghetti code where the execution order is not linear, and
6076 hence the above test fails. Here we assume that the giv lifetime
6077 does not extend from one iteration of the loop to the next, so as
6078 to make the test easier. Since the lifetime isn't known yet,
6079 this requires two loops. See also record_giv above. */
6081 last_giv_use = v->insn;
6083 while (1)
6085 p = NEXT_INSN (p);
6086 if (p == loop->end)
6088 before_giv_insn = 1;
6089 p = NEXT_INSN (loop->start);
6091 if (p == v->insn)
6092 break;
6094 if (GET_CODE (p) == INSN || GET_CODE (p) == JUMP_INSN
6095 || GET_CODE (p) == CALL_INSN)
6097 /* It is possible for the BIV increment to use the GIV if we
6098 have a cycle. Thus we must be sure to check each insn for
6099 both BIV and GIV uses, and we must check for BIV uses
6100 first. */
6102 if (! biv_increment_seen
6103 && reg_set_p (v->src_reg, PATTERN (p)))
6104 biv_increment_seen = 1;
6106 if (reg_mentioned_p (v->dest_reg, PATTERN (p)))
6108 if (biv_increment_seen || before_giv_insn)
6110 v->replaceable = 0;
6111 v->not_replaceable = 1;
6112 break;
6114 last_giv_use = p;
6119 /* Now that the lifetime of the giv is known, check for branches
6120 from within the lifetime to outside the lifetime if it is still
6121 replaceable. */
6123 if (v->replaceable)
6125 p = v->insn;
6126 while (1)
6128 p = NEXT_INSN (p);
6129 if (p == loop->end)
6130 p = NEXT_INSN (loop->start);
6131 if (p == last_giv_use)
6132 break;
6134 if (GET_CODE (p) == JUMP_INSN && JUMP_LABEL (p)
6135 && LABEL_NAME (JUMP_LABEL (p))
6136 && ((loop_insn_first_p (JUMP_LABEL (p), v->insn)
6137 && loop_insn_first_p (loop->start, JUMP_LABEL (p)))
6138 || (loop_insn_first_p (last_giv_use, JUMP_LABEL (p))
6139 && loop_insn_first_p (JUMP_LABEL (p), loop->end))))
6141 v->replaceable = 0;
6142 v->not_replaceable = 1;
6144 if (loop_dump_stream)
6145 fprintf (loop_dump_stream,
6146 "Found branch outside giv lifetime.\n");
6148 break;
6153 /* If it is replaceable, then save the final value. */
6154 if (v->replaceable)
6155 v->final_value = final_value;
6158 if (loop_dump_stream && v->replaceable)
6159 fprintf (loop_dump_stream, "Insn %d: giv reg %d final_value replaceable\n",
6160 INSN_UID (v->insn), REGNO (v->dest_reg));
6163 /* Update the status of whether a giv can derive other givs.
6165 We need to do something special if there is or may be an update to the biv
6166 between the time the giv is defined and the time it is used to derive
6167 another giv.
6169 In addition, a giv that is only conditionally set is not allowed to
6170 derive another giv once a label has been passed.
6172 The cases we look at are when a label or an update to a biv is passed. */
6174 static void
6175 update_giv_derive (loop, p)
6176 const struct loop *loop;
6177 rtx p;
6179 struct loop_ivs *ivs = LOOP_IVS (loop);
6180 struct iv_class *bl;
6181 struct induction *biv, *giv;
6182 rtx tem;
6183 int dummy;
6185 /* Search all IV classes, then all bivs, and finally all givs.
6187 There are three cases we are concerned with. First we have the situation
6188 of a giv that is only updated conditionally. In that case, it may not
6189 derive any givs after a label is passed.
6191 The second case is when a biv update occurs, or may occur, after the
6192 definition of a giv. For certain biv updates (see below) that are
6193 known to occur between the giv definition and use, we can adjust the
6194 giv definition. For others, or when the biv update is conditional,
6195 we must prevent the giv from deriving any other givs. There are two
6196 sub-cases within this case.
6198 If this is a label, we are concerned with any biv update that is done
6199 conditionally, since it may be done after the giv is defined followed by
6200 a branch here (actually, we need to pass both a jump and a label, but
6201 this extra tracking doesn't seem worth it).
6203 If this is a jump, we are concerned about any biv update that may be
6204 executed multiple times. We are actually only concerned about
6205 backward jumps, but it is probably not worth performing the test
6206 on the jump again here.
6208 If this is a biv update, we must adjust the giv status to show that a
6209 subsequent biv update was performed. If this adjustment cannot be done,
6210 the giv cannot derive further givs. */
6212 for (bl = ivs->list; bl; bl = bl->next)
6213 for (biv = bl->biv; biv; biv = biv->next_iv)
6214 if (GET_CODE (p) == CODE_LABEL || GET_CODE (p) == JUMP_INSN
6215 || biv->insn == p)
6217 for (giv = bl->giv; giv; giv = giv->next_iv)
6219 /* If cant_derive is already true, there is no point in
6220 checking all of these conditions again. */
6221 if (giv->cant_derive)
6222 continue;
6224 /* If this giv is conditionally set and we have passed a label,
6225 it cannot derive anything. */
6226 if (GET_CODE (p) == CODE_LABEL && ! giv->always_computable)
6227 giv->cant_derive = 1;
6229 /* Skip givs that have mult_val == 0, since
6230 they are really invariants. Also skip those that are
6231 replaceable, since we know their lifetime doesn't contain
6232 any biv update. */
6233 else if (giv->mult_val == const0_rtx || giv->replaceable)
6234 continue;
6236 /* The only way we can allow this giv to derive another
6237 is if this is a biv increment and we can form the product
6238 of biv->add_val and giv->mult_val. In this case, we will
6239 be able to compute a compensation. */
6240 else if (biv->insn == p)
6242 rtx ext_val_dummy;
6244 tem = 0;
6245 if (biv->mult_val == const1_rtx)
6246 tem = simplify_giv_expr (loop,
6247 gen_rtx_MULT (giv->mode,
6248 biv->add_val,
6249 giv->mult_val),
6250 &ext_val_dummy, &dummy);
6252 if (tem && giv->derive_adjustment)
6253 tem = simplify_giv_expr
6254 (loop,
6255 gen_rtx_PLUS (giv->mode, tem, giv->derive_adjustment),
6256 &ext_val_dummy, &dummy);
6258 if (tem)
6259 giv->derive_adjustment = tem;
6260 else
6261 giv->cant_derive = 1;
6263 else if ((GET_CODE (p) == CODE_LABEL && ! biv->always_computable)
6264 || (GET_CODE (p) == JUMP_INSN && biv->maybe_multiple))
6265 giv->cant_derive = 1;
6270 /* Check whether an insn is an increment legitimate for a basic induction var.
6271 X is the source of insn P, or a part of it.
6272 MODE is the mode in which X should be interpreted.
6274 DEST_REG is the putative biv, also the destination of the insn.
6275 We accept patterns of these forms:
6276 REG = REG + INVARIANT (includes REG = REG - CONSTANT)
6277 REG = INVARIANT + REG
6279 If X is suitable, we return 1, set *MULT_VAL to CONST1_RTX,
6280 store the additive term into *INC_VAL, and store the place where
6281 we found the additive term into *LOCATION.
6283 If X is an assignment of an invariant into DEST_REG, we set
6284 *MULT_VAL to CONST0_RTX, and store the invariant into *INC_VAL.
6286 We also want to detect a BIV when it corresponds to a variable
6287 whose mode was promoted via PROMOTED_MODE. In that case, an increment
6288 of the variable may be a PLUS that adds a SUBREG of that variable to
6289 an invariant and then sign- or zero-extends the result of the PLUS
6290 into the variable.
6292 Most GIVs in such cases will be in the promoted mode, since that is the
6293 probably the natural computation mode (and almost certainly the mode
6294 used for addresses) on the machine. So we view the pseudo-reg containing
6295 the variable as the BIV, as if it were simply incremented.
6297 Note that treating the entire pseudo as a BIV will result in making
6298 simple increments to any GIVs based on it. However, if the variable
6299 overflows in its declared mode but not its promoted mode, the result will
6300 be incorrect. This is acceptable if the variable is signed, since
6301 overflows in such cases are undefined, but not if it is unsigned, since
6302 those overflows are defined. So we only check for SIGN_EXTEND and
6303 not ZERO_EXTEND.
6305 If we cannot find a biv, we return 0. */
6307 static int
6308 basic_induction_var (loop, x, mode, dest_reg, p, inc_val, mult_val, location)
6309 const struct loop *loop;
6310 rtx x;
6311 enum machine_mode mode;
6312 rtx dest_reg;
6313 rtx p;
6314 rtx *inc_val;
6315 rtx *mult_val;
6316 rtx **location;
6318 enum rtx_code code;
6319 rtx *argp, arg;
6320 rtx insn, set = 0;
6322 code = GET_CODE (x);
6323 *location = NULL;
6324 switch (code)
6326 case PLUS:
6327 if (rtx_equal_p (XEXP (x, 0), dest_reg)
6328 || (GET_CODE (XEXP (x, 0)) == SUBREG
6329 && SUBREG_PROMOTED_VAR_P (XEXP (x, 0))
6330 && SUBREG_REG (XEXP (x, 0)) == dest_reg))
6332 argp = &XEXP (x, 1);
6334 else if (rtx_equal_p (XEXP (x, 1), dest_reg)
6335 || (GET_CODE (XEXP (x, 1)) == SUBREG
6336 && SUBREG_PROMOTED_VAR_P (XEXP (x, 1))
6337 && SUBREG_REG (XEXP (x, 1)) == dest_reg))
6339 argp = &XEXP (x, 0);
6341 else
6342 return 0;
6344 arg = *argp;
6345 if (loop_invariant_p (loop, arg) != 1)
6346 return 0;
6348 *inc_val = convert_modes (GET_MODE (dest_reg), GET_MODE (x), arg, 0);
6349 *mult_val = const1_rtx;
6350 *location = argp;
6351 return 1;
6353 case SUBREG:
6354 /* If what's inside the SUBREG is a BIV, then the SUBREG. This will
6355 handle addition of promoted variables.
6356 ??? The comment at the start of this function is wrong: promoted
6357 variable increments don't look like it says they do. */
6358 return basic_induction_var (loop, SUBREG_REG (x),
6359 GET_MODE (SUBREG_REG (x)),
6360 dest_reg, p, inc_val, mult_val, location);
6362 case REG:
6363 /* If this register is assigned in a previous insn, look at its
6364 source, but don't go outside the loop or past a label. */
6366 /* If this sets a register to itself, we would repeat any previous
6367 biv increment if we applied this strategy blindly. */
6368 if (rtx_equal_p (dest_reg, x))
6369 return 0;
6371 insn = p;
6372 while (1)
6374 rtx dest;
6377 insn = PREV_INSN (insn);
6379 while (insn && GET_CODE (insn) == NOTE
6380 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6382 if (!insn)
6383 break;
6384 set = single_set (insn);
6385 if (set == 0)
6386 break;
6387 dest = SET_DEST (set);
6388 if (dest == x
6389 || (GET_CODE (dest) == SUBREG
6390 && (GET_MODE_SIZE (GET_MODE (dest)) <= UNITS_PER_WORD)
6391 && (GET_MODE_CLASS (GET_MODE (dest)) == MODE_INT)
6392 && SUBREG_REG (dest) == x))
6393 return basic_induction_var (loop, SET_SRC (set),
6394 (GET_MODE (SET_SRC (set)) == VOIDmode
6395 ? GET_MODE (x)
6396 : GET_MODE (SET_SRC (set))),
6397 dest_reg, insn,
6398 inc_val, mult_val, location);
6400 while (GET_CODE (dest) == SIGN_EXTRACT
6401 || GET_CODE (dest) == ZERO_EXTRACT
6402 || GET_CODE (dest) == SUBREG
6403 || GET_CODE (dest) == STRICT_LOW_PART)
6404 dest = XEXP (dest, 0);
6405 if (dest == x)
6406 break;
6408 /* Fall through. */
6410 /* Can accept constant setting of biv only when inside inner most loop.
6411 Otherwise, a biv of an inner loop may be incorrectly recognized
6412 as a biv of the outer loop,
6413 causing code to be moved INTO the inner loop. */
6414 case MEM:
6415 if (loop_invariant_p (loop, x) != 1)
6416 return 0;
6417 case CONST_INT:
6418 case SYMBOL_REF:
6419 case CONST:
6420 /* convert_modes aborts if we try to convert to or from CCmode, so just
6421 exclude that case. It is very unlikely that a condition code value
6422 would be a useful iterator anyways. convert_modes aborts if we try to
6423 convert a float mode to non-float or vice versa too. */
6424 if (loop->level == 1
6425 && GET_MODE_CLASS (mode) == GET_MODE_CLASS (GET_MODE (dest_reg))
6426 && GET_MODE_CLASS (mode) != MODE_CC)
6428 /* Possible bug here? Perhaps we don't know the mode of X. */
6429 *inc_val = convert_modes (GET_MODE (dest_reg), mode, x, 0);
6430 *mult_val = const0_rtx;
6431 return 1;
6433 else
6434 return 0;
6436 case SIGN_EXTEND:
6437 return basic_induction_var (loop, XEXP (x, 0), GET_MODE (XEXP (x, 0)),
6438 dest_reg, p, inc_val, mult_val, location);
6440 case ASHIFTRT:
6441 /* Similar, since this can be a sign extension. */
6442 for (insn = PREV_INSN (p);
6443 (insn && GET_CODE (insn) == NOTE
6444 && NOTE_LINE_NUMBER (insn) != NOTE_INSN_LOOP_BEG);
6445 insn = PREV_INSN (insn))
6448 if (insn)
6449 set = single_set (insn);
6451 if (! rtx_equal_p (dest_reg, XEXP (x, 0))
6452 && set && SET_DEST (set) == XEXP (x, 0)
6453 && GET_CODE (XEXP (x, 1)) == CONST_INT
6454 && INTVAL (XEXP (x, 1)) >= 0
6455 && GET_CODE (SET_SRC (set)) == ASHIFT
6456 && XEXP (x, 1) == XEXP (SET_SRC (set), 1))
6457 return basic_induction_var (loop, XEXP (SET_SRC (set), 0),
6458 GET_MODE (XEXP (x, 0)),
6459 dest_reg, insn, inc_val, mult_val,
6460 location);
6461 return 0;
6463 default:
6464 return 0;
6468 /* A general induction variable (giv) is any quantity that is a linear
6469 function of a basic induction variable,
6470 i.e. giv = biv * mult_val + add_val.
6471 The coefficients can be any loop invariant quantity.
6472 A giv need not be computed directly from the biv;
6473 it can be computed by way of other givs. */
6475 /* Determine whether X computes a giv.
6476 If it does, return a nonzero value
6477 which is the benefit from eliminating the computation of X;
6478 set *SRC_REG to the register of the biv that it is computed from;
6479 set *ADD_VAL and *MULT_VAL to the coefficients,
6480 such that the value of X is biv * mult + add; */
6482 static int
6483 general_induction_var (loop, x, src_reg, add_val, mult_val, ext_val,
6484 is_addr, pbenefit, addr_mode)
6485 const struct loop *loop;
6486 rtx x;
6487 rtx *src_reg;
6488 rtx *add_val;
6489 rtx *mult_val;
6490 rtx *ext_val;
6491 int is_addr;
6492 int *pbenefit;
6493 enum machine_mode addr_mode;
6495 struct loop_ivs *ivs = LOOP_IVS (loop);
6496 rtx orig_x = x;
6498 /* If this is an invariant, forget it, it isn't a giv. */
6499 if (loop_invariant_p (loop, x) == 1)
6500 return 0;
6502 *pbenefit = 0;
6503 *ext_val = NULL_RTX;
6504 x = simplify_giv_expr (loop, x, ext_val, pbenefit);
6505 if (x == 0)
6506 return 0;
6508 switch (GET_CODE (x))
6510 case USE:
6511 case CONST_INT:
6512 /* Since this is now an invariant and wasn't before, it must be a giv
6513 with MULT_VAL == 0. It doesn't matter which BIV we associate this
6514 with. */
6515 *src_reg = ivs->list->biv->dest_reg;
6516 *mult_val = const0_rtx;
6517 *add_val = x;
6518 break;
6520 case REG:
6521 /* This is equivalent to a BIV. */
6522 *src_reg = x;
6523 *mult_val = const1_rtx;
6524 *add_val = const0_rtx;
6525 break;
6527 case PLUS:
6528 /* Either (plus (biv) (invar)) or
6529 (plus (mult (biv) (invar_1)) (invar_2)). */
6530 if (GET_CODE (XEXP (x, 0)) == MULT)
6532 *src_reg = XEXP (XEXP (x, 0), 0);
6533 *mult_val = XEXP (XEXP (x, 0), 1);
6535 else
6537 *src_reg = XEXP (x, 0);
6538 *mult_val = const1_rtx;
6540 *add_val = XEXP (x, 1);
6541 break;
6543 case MULT:
6544 /* ADD_VAL is zero. */
6545 *src_reg = XEXP (x, 0);
6546 *mult_val = XEXP (x, 1);
6547 *add_val = const0_rtx;
6548 break;
6550 default:
6551 abort ();
6554 /* Remove any enclosing USE from ADD_VAL and MULT_VAL (there will be
6555 unless they are CONST_INT). */
6556 if (GET_CODE (*add_val) == USE)
6557 *add_val = XEXP (*add_val, 0);
6558 if (GET_CODE (*mult_val) == USE)
6559 *mult_val = XEXP (*mult_val, 0);
6561 if (is_addr)
6562 *pbenefit += address_cost (orig_x, addr_mode) - reg_address_cost;
6563 else
6564 *pbenefit += rtx_cost (orig_x, SET);
6566 /* Always return true if this is a giv so it will be detected as such,
6567 even if the benefit is zero or negative. This allows elimination
6568 of bivs that might otherwise not be eliminated. */
6569 return 1;
6572 /* Given an expression, X, try to form it as a linear function of a biv.
6573 We will canonicalize it to be of the form
6574 (plus (mult (BIV) (invar_1))
6575 (invar_2))
6576 with possible degeneracies.
6578 The invariant expressions must each be of a form that can be used as a
6579 machine operand. We surround then with a USE rtx (a hack, but localized
6580 and certainly unambiguous!) if not a CONST_INT for simplicity in this
6581 routine; it is the caller's responsibility to strip them.
6583 If no such canonicalization is possible (i.e., two biv's are used or an
6584 expression that is neither invariant nor a biv or giv), this routine
6585 returns 0.
6587 For a nonzero return, the result will have a code of CONST_INT, USE,
6588 REG (for a BIV), PLUS, or MULT. No other codes will occur.
6590 *BENEFIT will be incremented by the benefit of any sub-giv encountered. */
6592 static rtx sge_plus PARAMS ((enum machine_mode, rtx, rtx));
6593 static rtx sge_plus_constant PARAMS ((rtx, rtx));
6595 static rtx
6596 simplify_giv_expr (loop, x, ext_val, benefit)
6597 const struct loop *loop;
6598 rtx x;
6599 rtx *ext_val;
6600 int *benefit;
6602 struct loop_ivs *ivs = LOOP_IVS (loop);
6603 struct loop_regs *regs = LOOP_REGS (loop);
6604 enum machine_mode mode = GET_MODE (x);
6605 rtx arg0, arg1;
6606 rtx tem;
6608 /* If this is not an integer mode, or if we cannot do arithmetic in this
6609 mode, this can't be a giv. */
6610 if (mode != VOIDmode
6611 && (GET_MODE_CLASS (mode) != MODE_INT
6612 || GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT))
6613 return NULL_RTX;
6615 switch (GET_CODE (x))
6617 case PLUS:
6618 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6619 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6620 if (arg0 == 0 || arg1 == 0)
6621 return NULL_RTX;
6623 /* Put constant last, CONST_INT last if both constant. */
6624 if ((GET_CODE (arg0) == USE
6625 || GET_CODE (arg0) == CONST_INT)
6626 && ! ((GET_CODE (arg0) == USE
6627 && GET_CODE (arg1) == USE)
6628 || GET_CODE (arg1) == CONST_INT))
6629 tem = arg0, arg0 = arg1, arg1 = tem;
6631 /* Handle addition of zero, then addition of an invariant. */
6632 if (arg1 == const0_rtx)
6633 return arg0;
6634 else if (GET_CODE (arg1) == CONST_INT || GET_CODE (arg1) == USE)
6635 switch (GET_CODE (arg0))
6637 case CONST_INT:
6638 case USE:
6639 /* Adding two invariants must result in an invariant, so enclose
6640 addition operation inside a USE and return it. */
6641 if (GET_CODE (arg0) == USE)
6642 arg0 = XEXP (arg0, 0);
6643 if (GET_CODE (arg1) == USE)
6644 arg1 = XEXP (arg1, 0);
6646 if (GET_CODE (arg0) == CONST_INT)
6647 tem = arg0, arg0 = arg1, arg1 = tem;
6648 if (GET_CODE (arg1) == CONST_INT)
6649 tem = sge_plus_constant (arg0, arg1);
6650 else
6651 tem = sge_plus (mode, arg0, arg1);
6653 if (GET_CODE (tem) != CONST_INT)
6654 tem = gen_rtx_USE (mode, tem);
6655 return tem;
6657 case REG:
6658 case MULT:
6659 /* biv + invar or mult + invar. Return sum. */
6660 return gen_rtx_PLUS (mode, arg0, arg1);
6662 case PLUS:
6663 /* (a + invar_1) + invar_2. Associate. */
6664 return
6665 simplify_giv_expr (loop,
6666 gen_rtx_PLUS (mode,
6667 XEXP (arg0, 0),
6668 gen_rtx_PLUS (mode,
6669 XEXP (arg0, 1),
6670 arg1)),
6671 ext_val, benefit);
6673 default:
6674 abort ();
6677 /* Each argument must be either REG, PLUS, or MULT. Convert REG to
6678 MULT to reduce cases. */
6679 if (GET_CODE (arg0) == REG)
6680 arg0 = gen_rtx_MULT (mode, arg0, const1_rtx);
6681 if (GET_CODE (arg1) == REG)
6682 arg1 = gen_rtx_MULT (mode, arg1, const1_rtx);
6684 /* Now have PLUS + PLUS, PLUS + MULT, MULT + PLUS, or MULT + MULT.
6685 Put a MULT first, leaving PLUS + PLUS, MULT + PLUS, or MULT + MULT.
6686 Recurse to associate the second PLUS. */
6687 if (GET_CODE (arg1) == MULT)
6688 tem = arg0, arg0 = arg1, arg1 = tem;
6690 if (GET_CODE (arg1) == PLUS)
6691 return
6692 simplify_giv_expr (loop,
6693 gen_rtx_PLUS (mode,
6694 gen_rtx_PLUS (mode, arg0,
6695 XEXP (arg1, 0)),
6696 XEXP (arg1, 1)),
6697 ext_val, benefit);
6699 /* Now must have MULT + MULT. Distribute if same biv, else not giv. */
6700 if (GET_CODE (arg0) != MULT || GET_CODE (arg1) != MULT)
6701 return NULL_RTX;
6703 if (!rtx_equal_p (arg0, arg1))
6704 return NULL_RTX;
6706 return simplify_giv_expr (loop,
6707 gen_rtx_MULT (mode,
6708 XEXP (arg0, 0),
6709 gen_rtx_PLUS (mode,
6710 XEXP (arg0, 1),
6711 XEXP (arg1, 1))),
6712 ext_val, benefit);
6714 case MINUS:
6715 /* Handle "a - b" as "a + b * (-1)". */
6716 return simplify_giv_expr (loop,
6717 gen_rtx_PLUS (mode,
6718 XEXP (x, 0),
6719 gen_rtx_MULT (mode,
6720 XEXP (x, 1),
6721 constm1_rtx)),
6722 ext_val, benefit);
6724 case MULT:
6725 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6726 arg1 = simplify_giv_expr (loop, XEXP (x, 1), ext_val, benefit);
6727 if (arg0 == 0 || arg1 == 0)
6728 return NULL_RTX;
6730 /* Put constant last, CONST_INT last if both constant. */
6731 if ((GET_CODE (arg0) == USE || GET_CODE (arg0) == CONST_INT)
6732 && GET_CODE (arg1) != CONST_INT)
6733 tem = arg0, arg0 = arg1, arg1 = tem;
6735 /* If second argument is not now constant, not giv. */
6736 if (GET_CODE (arg1) != USE && GET_CODE (arg1) != CONST_INT)
6737 return NULL_RTX;
6739 /* Handle multiply by 0 or 1. */
6740 if (arg1 == const0_rtx)
6741 return const0_rtx;
6743 else if (arg1 == const1_rtx)
6744 return arg0;
6746 switch (GET_CODE (arg0))
6748 case REG:
6749 /* biv * invar. Done. */
6750 return gen_rtx_MULT (mode, arg0, arg1);
6752 case CONST_INT:
6753 /* Product of two constants. */
6754 return GEN_INT (INTVAL (arg0) * INTVAL (arg1));
6756 case USE:
6757 /* invar * invar is a giv, but attempt to simplify it somehow. */
6758 if (GET_CODE (arg1) != CONST_INT)
6759 return NULL_RTX;
6761 arg0 = XEXP (arg0, 0);
6762 if (GET_CODE (arg0) == MULT)
6764 /* (invar_0 * invar_1) * invar_2. Associate. */
6765 return simplify_giv_expr (loop,
6766 gen_rtx_MULT (mode,
6767 XEXP (arg0, 0),
6768 gen_rtx_MULT (mode,
6769 XEXP (arg0,
6771 arg1)),
6772 ext_val, benefit);
6774 /* Propagate the MULT expressions to the intermost nodes. */
6775 else if (GET_CODE (arg0) == PLUS)
6777 /* (invar_0 + invar_1) * invar_2. Distribute. */
6778 return simplify_giv_expr (loop,
6779 gen_rtx_PLUS (mode,
6780 gen_rtx_MULT (mode,
6781 XEXP (arg0,
6783 arg1),
6784 gen_rtx_MULT (mode,
6785 XEXP (arg0,
6787 arg1)),
6788 ext_val, benefit);
6790 return gen_rtx_USE (mode, gen_rtx_MULT (mode, arg0, arg1));
6792 case MULT:
6793 /* (a * invar_1) * invar_2. Associate. */
6794 return simplify_giv_expr (loop,
6795 gen_rtx_MULT (mode,
6796 XEXP (arg0, 0),
6797 gen_rtx_MULT (mode,
6798 XEXP (arg0, 1),
6799 arg1)),
6800 ext_val, benefit);
6802 case PLUS:
6803 /* (a + invar_1) * invar_2. Distribute. */
6804 return simplify_giv_expr (loop,
6805 gen_rtx_PLUS (mode,
6806 gen_rtx_MULT (mode,
6807 XEXP (arg0, 0),
6808 arg1),
6809 gen_rtx_MULT (mode,
6810 XEXP (arg0, 1),
6811 arg1)),
6812 ext_val, benefit);
6814 default:
6815 abort ();
6818 case ASHIFT:
6819 /* Shift by constant is multiply by power of two. */
6820 if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6821 return 0;
6823 return
6824 simplify_giv_expr (loop,
6825 gen_rtx_MULT (mode,
6826 XEXP (x, 0),
6827 GEN_INT ((HOST_WIDE_INT) 1
6828 << INTVAL (XEXP (x, 1)))),
6829 ext_val, benefit);
6831 case NEG:
6832 /* "-a" is "a * (-1)" */
6833 return simplify_giv_expr (loop,
6834 gen_rtx_MULT (mode, XEXP (x, 0), constm1_rtx),
6835 ext_val, benefit);
6837 case NOT:
6838 /* "~a" is "-a - 1". Silly, but easy. */
6839 return simplify_giv_expr (loop,
6840 gen_rtx_MINUS (mode,
6841 gen_rtx_NEG (mode, XEXP (x, 0)),
6842 const1_rtx),
6843 ext_val, benefit);
6845 case USE:
6846 /* Already in proper form for invariant. */
6847 return x;
6849 case SIGN_EXTEND:
6850 case ZERO_EXTEND:
6851 case TRUNCATE:
6852 /* Conditionally recognize extensions of simple IVs. After we've
6853 computed loop traversal counts and verified the range of the
6854 source IV, we'll reevaluate this as a GIV. */
6855 if (*ext_val == NULL_RTX)
6857 arg0 = simplify_giv_expr (loop, XEXP (x, 0), ext_val, benefit);
6858 if (arg0 && *ext_val == NULL_RTX && GET_CODE (arg0) == REG)
6860 *ext_val = gen_rtx_fmt_e (GET_CODE (x), mode, arg0);
6861 return arg0;
6864 goto do_default;
6866 case REG:
6867 /* If this is a new register, we can't deal with it. */
6868 if (REGNO (x) >= max_reg_before_loop)
6869 return 0;
6871 /* Check for biv or giv. */
6872 switch (REG_IV_TYPE (ivs, REGNO (x)))
6874 case BASIC_INDUCT:
6875 return x;
6876 case GENERAL_INDUCT:
6878 struct induction *v = REG_IV_INFO (ivs, REGNO (x));
6880 /* Form expression from giv and add benefit. Ensure this giv
6881 can derive another and subtract any needed adjustment if so. */
6883 /* Increasing the benefit here is risky. The only case in which it
6884 is arguably correct is if this is the only use of V. In other
6885 cases, this will artificially inflate the benefit of the current
6886 giv, and lead to suboptimal code. Thus, it is disabled, since
6887 potentially not reducing an only marginally beneficial giv is
6888 less harmful than reducing many givs that are not really
6889 beneficial. */
6891 rtx single_use = regs->array[REGNO (x)].single_usage;
6892 if (single_use && single_use != const0_rtx)
6893 *benefit += v->benefit;
6896 if (v->cant_derive)
6897 return 0;
6899 tem = gen_rtx_PLUS (mode, gen_rtx_MULT (mode,
6900 v->src_reg, v->mult_val),
6901 v->add_val);
6903 if (v->derive_adjustment)
6904 tem = gen_rtx_MINUS (mode, tem, v->derive_adjustment);
6905 arg0 = simplify_giv_expr (loop, tem, ext_val, benefit);
6906 if (*ext_val)
6908 if (!v->ext_dependent)
6909 return arg0;
6911 else
6913 *ext_val = v->ext_dependent;
6914 return arg0;
6916 return 0;
6919 default:
6920 do_default:
6921 /* If it isn't an induction variable, and it is invariant, we
6922 may be able to simplify things further by looking through
6923 the bits we just moved outside the loop. */
6924 if (loop_invariant_p (loop, x) == 1)
6926 struct movable *m;
6927 struct loop_movables *movables = LOOP_MOVABLES (loop);
6929 for (m = movables->head; m; m = m->next)
6930 if (rtx_equal_p (x, m->set_dest))
6932 /* Ok, we found a match. Substitute and simplify. */
6934 /* If we match another movable, we must use that, as
6935 this one is going away. */
6936 if (m->match)
6937 return simplify_giv_expr (loop, m->match->set_dest,
6938 ext_val, benefit);
6940 /* If consec is nonzero, this is a member of a group of
6941 instructions that were moved together. We handle this
6942 case only to the point of seeking to the last insn and
6943 looking for a REG_EQUAL. Fail if we don't find one. */
6944 if (m->consec != 0)
6946 int i = m->consec;
6947 tem = m->insn;
6950 tem = NEXT_INSN (tem);
6952 while (--i > 0);
6954 tem = find_reg_note (tem, REG_EQUAL, NULL_RTX);
6955 if (tem)
6956 tem = XEXP (tem, 0);
6958 else
6960 tem = single_set (m->insn);
6961 if (tem)
6962 tem = SET_SRC (tem);
6965 if (tem)
6967 /* What we are most interested in is pointer
6968 arithmetic on invariants -- only take
6969 patterns we may be able to do something with. */
6970 if (GET_CODE (tem) == PLUS
6971 || GET_CODE (tem) == MULT
6972 || GET_CODE (tem) == ASHIFT
6973 || GET_CODE (tem) == CONST_INT
6974 || GET_CODE (tem) == SYMBOL_REF)
6976 tem = simplify_giv_expr (loop, tem, ext_val,
6977 benefit);
6978 if (tem)
6979 return tem;
6981 else if (GET_CODE (tem) == CONST
6982 && GET_CODE (XEXP (tem, 0)) == PLUS
6983 && GET_CODE (XEXP (XEXP (tem, 0), 0)) == SYMBOL_REF
6984 && GET_CODE (XEXP (XEXP (tem, 0), 1)) == CONST_INT)
6986 tem = simplify_giv_expr (loop, XEXP (tem, 0),
6987 ext_val, benefit);
6988 if (tem)
6989 return tem;
6992 break;
6995 break;
6998 /* Fall through to general case. */
6999 default:
7000 /* If invariant, return as USE (unless CONST_INT).
7001 Otherwise, not giv. */
7002 if (GET_CODE (x) == USE)
7003 x = XEXP (x, 0);
7005 if (loop_invariant_p (loop, x) == 1)
7007 if (GET_CODE (x) == CONST_INT)
7008 return x;
7009 if (GET_CODE (x) == CONST
7010 && GET_CODE (XEXP (x, 0)) == PLUS
7011 && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF
7012 && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
7013 x = XEXP (x, 0);
7014 return gen_rtx_USE (mode, x);
7016 else
7017 return 0;
7021 /* This routine folds invariants such that there is only ever one
7022 CONST_INT in the summation. It is only used by simplify_giv_expr. */
7024 static rtx
7025 sge_plus_constant (x, c)
7026 rtx x, c;
7028 if (GET_CODE (x) == CONST_INT)
7029 return GEN_INT (INTVAL (x) + INTVAL (c));
7030 else if (GET_CODE (x) != PLUS)
7031 return gen_rtx_PLUS (GET_MODE (x), x, c);
7032 else if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7034 return gen_rtx_PLUS (GET_MODE (x), XEXP (x, 0),
7035 GEN_INT (INTVAL (XEXP (x, 1)) + INTVAL (c)));
7037 else if (GET_CODE (XEXP (x, 0)) == PLUS
7038 || GET_CODE (XEXP (x, 1)) != PLUS)
7040 return gen_rtx_PLUS (GET_MODE (x),
7041 sge_plus_constant (XEXP (x, 0), c), XEXP (x, 1));
7043 else
7045 return gen_rtx_PLUS (GET_MODE (x),
7046 sge_plus_constant (XEXP (x, 1), c), XEXP (x, 0));
7050 static rtx
7051 sge_plus (mode, x, y)
7052 enum machine_mode mode;
7053 rtx x, y;
7055 while (GET_CODE (y) == PLUS)
7057 rtx a = XEXP (y, 0);
7058 if (GET_CODE (a) == CONST_INT)
7059 x = sge_plus_constant (x, a);
7060 else
7061 x = gen_rtx_PLUS (mode, x, a);
7062 y = XEXP (y, 1);
7064 if (GET_CODE (y) == CONST_INT)
7065 x = sge_plus_constant (x, y);
7066 else
7067 x = gen_rtx_PLUS (mode, x, y);
7068 return x;
7071 /* Help detect a giv that is calculated by several consecutive insns;
7072 for example,
7073 giv = biv * M
7074 giv = giv + A
7075 The caller has already identified the first insn P as having a giv as dest;
7076 we check that all other insns that set the same register follow
7077 immediately after P, that they alter nothing else,
7078 and that the result of the last is still a giv.
7080 The value is 0 if the reg set in P is not really a giv.
7081 Otherwise, the value is the amount gained by eliminating
7082 all the consecutive insns that compute the value.
7084 FIRST_BENEFIT is the amount gained by eliminating the first insn, P.
7085 SRC_REG is the reg of the biv; DEST_REG is the reg of the giv.
7087 The coefficients of the ultimate giv value are stored in
7088 *MULT_VAL and *ADD_VAL. */
7090 static int
7091 consec_sets_giv (loop, first_benefit, p, src_reg, dest_reg,
7092 add_val, mult_val, ext_val, last_consec_insn)
7093 const struct loop *loop;
7094 int first_benefit;
7095 rtx p;
7096 rtx src_reg;
7097 rtx dest_reg;
7098 rtx *add_val;
7099 rtx *mult_val;
7100 rtx *ext_val;
7101 rtx *last_consec_insn;
7103 struct loop_ivs *ivs = LOOP_IVS (loop);
7104 struct loop_regs *regs = LOOP_REGS (loop);
7105 int count;
7106 enum rtx_code code;
7107 int benefit;
7108 rtx temp;
7109 rtx set;
7111 /* Indicate that this is a giv so that we can update the value produced in
7112 each insn of the multi-insn sequence.
7114 This induction structure will be used only by the call to
7115 general_induction_var below, so we can allocate it on our stack.
7116 If this is a giv, our caller will replace the induct var entry with
7117 a new induction structure. */
7118 struct induction *v;
7120 if (REG_IV_TYPE (ivs, REGNO (dest_reg)) != UNKNOWN_INDUCT)
7121 return 0;
7123 v = (struct induction *) alloca (sizeof (struct induction));
7124 v->src_reg = src_reg;
7125 v->mult_val = *mult_val;
7126 v->add_val = *add_val;
7127 v->benefit = first_benefit;
7128 v->cant_derive = 0;
7129 v->derive_adjustment = 0;
7130 v->ext_dependent = NULL_RTX;
7132 REG_IV_TYPE (ivs, REGNO (dest_reg)) = GENERAL_INDUCT;
7133 REG_IV_INFO (ivs, REGNO (dest_reg)) = v;
7135 count = regs->array[REGNO (dest_reg)].n_times_set - 1;
7137 while (count > 0)
7139 p = NEXT_INSN (p);
7140 code = GET_CODE (p);
7142 /* If libcall, skip to end of call sequence. */
7143 if (code == INSN && (temp = find_reg_note (p, REG_LIBCALL, NULL_RTX)))
7144 p = XEXP (temp, 0);
7146 if (code == INSN
7147 && (set = single_set (p))
7148 && GET_CODE (SET_DEST (set)) == REG
7149 && SET_DEST (set) == dest_reg
7150 && (general_induction_var (loop, SET_SRC (set), &src_reg,
7151 add_val, mult_val, ext_val, 0,
7152 &benefit, VOIDmode)
7153 /* Giv created by equivalent expression. */
7154 || ((temp = find_reg_note (p, REG_EQUAL, NULL_RTX))
7155 && general_induction_var (loop, XEXP (temp, 0), &src_reg,
7156 add_val, mult_val, ext_val, 0,
7157 &benefit, VOIDmode)))
7158 && src_reg == v->src_reg)
7160 if (find_reg_note (p, REG_RETVAL, NULL_RTX))
7161 benefit += libcall_benefit (p);
7163 count--;
7164 v->mult_val = *mult_val;
7165 v->add_val = *add_val;
7166 v->benefit += benefit;
7168 else if (code != NOTE)
7170 /* Allow insns that set something other than this giv to a
7171 constant. Such insns are needed on machines which cannot
7172 include long constants and should not disqualify a giv. */
7173 if (code == INSN
7174 && (set = single_set (p))
7175 && SET_DEST (set) != dest_reg
7176 && CONSTANT_P (SET_SRC (set)))
7177 continue;
7179 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7180 return 0;
7184 REG_IV_TYPE (ivs, REGNO (dest_reg)) = UNKNOWN_INDUCT;
7185 *last_consec_insn = p;
7186 return v->benefit;
7189 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7190 represented by G1. If no such expression can be found, or it is clear that
7191 it cannot possibly be a valid address, 0 is returned.
7193 To perform the computation, we note that
7194 G1 = x * v + a and
7195 G2 = y * v + b
7196 where `v' is the biv.
7198 So G2 = (y/b) * G1 + (b - a*y/x).
7200 Note that MULT = y/x.
7202 Update: A and B are now allowed to be additive expressions such that
7203 B contains all variables in A. That is, computing B-A will not require
7204 subtracting variables. */
7206 static rtx
7207 express_from_1 (a, b, mult)
7208 rtx a, b, mult;
7210 /* If MULT is zero, then A*MULT is zero, and our expression is B. */
7212 if (mult == const0_rtx)
7213 return b;
7215 /* If MULT is not 1, we cannot handle A with non-constants, since we
7216 would then be required to subtract multiples of the registers in A.
7217 This is theoretically possible, and may even apply to some Fortran
7218 constructs, but it is a lot of work and we do not attempt it here. */
7220 if (mult != const1_rtx && GET_CODE (a) != CONST_INT)
7221 return NULL_RTX;
7223 /* In general these structures are sorted top to bottom (down the PLUS
7224 chain), but not left to right across the PLUS. If B is a higher
7225 order giv than A, we can strip one level and recurse. If A is higher
7226 order, we'll eventually bail out, but won't know that until the end.
7227 If they are the same, we'll strip one level around this loop. */
7229 while (GET_CODE (a) == PLUS && GET_CODE (b) == PLUS)
7231 rtx ra, rb, oa, ob, tmp;
7233 ra = XEXP (a, 0), oa = XEXP (a, 1);
7234 if (GET_CODE (ra) == PLUS)
7235 tmp = ra, ra = oa, oa = tmp;
7237 rb = XEXP (b, 0), ob = XEXP (b, 1);
7238 if (GET_CODE (rb) == PLUS)
7239 tmp = rb, rb = ob, ob = tmp;
7241 if (rtx_equal_p (ra, rb))
7242 /* We matched: remove one reg completely. */
7243 a = oa, b = ob;
7244 else if (GET_CODE (ob) != PLUS && rtx_equal_p (ra, ob))
7245 /* An alternate match. */
7246 a = oa, b = rb;
7247 else if (GET_CODE (oa) != PLUS && rtx_equal_p (oa, rb))
7248 /* An alternate match. */
7249 a = ra, b = ob;
7250 else
7252 /* Indicates an extra register in B. Strip one level from B and
7253 recurse, hoping B was the higher order expression. */
7254 ob = express_from_1 (a, ob, mult);
7255 if (ob == NULL_RTX)
7256 return NULL_RTX;
7257 return gen_rtx_PLUS (GET_MODE (b), rb, ob);
7261 /* Here we are at the last level of A, go through the cases hoping to
7262 get rid of everything but a constant. */
7264 if (GET_CODE (a) == PLUS)
7266 rtx ra, oa;
7268 ra = XEXP (a, 0), oa = XEXP (a, 1);
7269 if (rtx_equal_p (oa, b))
7270 oa = ra;
7271 else if (!rtx_equal_p (ra, b))
7272 return NULL_RTX;
7274 if (GET_CODE (oa) != CONST_INT)
7275 return NULL_RTX;
7277 return GEN_INT (-INTVAL (oa) * INTVAL (mult));
7279 else if (GET_CODE (a) == CONST_INT)
7281 return plus_constant (b, -INTVAL (a) * INTVAL (mult));
7283 else if (CONSTANT_P (a))
7285 enum machine_mode mode_a = GET_MODE (a);
7286 enum machine_mode mode_b = GET_MODE (b);
7287 enum machine_mode mode = mode_b == VOIDmode ? mode_a : mode_b;
7288 return simplify_gen_binary (MINUS, mode, b, a);
7290 else if (GET_CODE (b) == PLUS)
7292 if (rtx_equal_p (a, XEXP (b, 0)))
7293 return XEXP (b, 1);
7294 else if (rtx_equal_p (a, XEXP (b, 1)))
7295 return XEXP (b, 0);
7296 else
7297 return NULL_RTX;
7299 else if (rtx_equal_p (a, b))
7300 return const0_rtx;
7302 return NULL_RTX;
7306 express_from (g1, g2)
7307 struct induction *g1, *g2;
7309 rtx mult, add;
7311 /* The value that G1 will be multiplied by must be a constant integer. Also,
7312 the only chance we have of getting a valid address is if b*c/a (see above
7313 for notation) is also an integer. */
7314 if (GET_CODE (g1->mult_val) == CONST_INT
7315 && GET_CODE (g2->mult_val) == CONST_INT)
7317 if (g1->mult_val == const0_rtx
7318 || INTVAL (g2->mult_val) % INTVAL (g1->mult_val) != 0)
7319 return NULL_RTX;
7320 mult = GEN_INT (INTVAL (g2->mult_val) / INTVAL (g1->mult_val));
7322 else if (rtx_equal_p (g1->mult_val, g2->mult_val))
7323 mult = const1_rtx;
7324 else
7326 /* ??? Find out if the one is a multiple of the other? */
7327 return NULL_RTX;
7330 add = express_from_1 (g1->add_val, g2->add_val, mult);
7331 if (add == NULL_RTX)
7333 /* Failed. If we've got a multiplication factor between G1 and G2,
7334 scale G1's addend and try again. */
7335 if (INTVAL (mult) > 1)
7337 rtx g1_add_val = g1->add_val;
7338 if (GET_CODE (g1_add_val) == MULT
7339 && GET_CODE (XEXP (g1_add_val, 1)) == CONST_INT)
7341 HOST_WIDE_INT m;
7342 m = INTVAL (mult) * INTVAL (XEXP (g1_add_val, 1));
7343 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val),
7344 XEXP (g1_add_val, 0), GEN_INT (m));
7346 else
7348 g1_add_val = gen_rtx_MULT (GET_MODE (g1_add_val), g1_add_val,
7349 mult);
7352 add = express_from_1 (g1_add_val, g2->add_val, const1_rtx);
7355 if (add == NULL_RTX)
7356 return NULL_RTX;
7358 /* Form simplified final result. */
7359 if (mult == const0_rtx)
7360 return add;
7361 else if (mult == const1_rtx)
7362 mult = g1->dest_reg;
7363 else
7364 mult = gen_rtx_MULT (g2->mode, g1->dest_reg, mult);
7366 if (add == const0_rtx)
7367 return mult;
7368 else
7370 if (GET_CODE (add) == PLUS
7371 && CONSTANT_P (XEXP (add, 1)))
7373 rtx tem = XEXP (add, 1);
7374 mult = gen_rtx_PLUS (g2->mode, mult, XEXP (add, 0));
7375 add = tem;
7378 return gen_rtx_PLUS (g2->mode, mult, add);
7382 /* Return an rtx, if any, that expresses giv G2 as a function of the register
7383 represented by G1. This indicates that G2 should be combined with G1 and
7384 that G2 can use (either directly or via an address expression) a register
7385 used to represent G1. */
7387 static rtx
7388 combine_givs_p (g1, g2)
7389 struct induction *g1, *g2;
7391 rtx comb, ret;
7393 /* With the introduction of ext dependent givs, we must care for modes.
7394 G2 must not use a wider mode than G1. */
7395 if (GET_MODE_SIZE (g1->mode) < GET_MODE_SIZE (g2->mode))
7396 return NULL_RTX;
7398 ret = comb = express_from (g1, g2);
7399 if (comb == NULL_RTX)
7400 return NULL_RTX;
7401 if (g1->mode != g2->mode)
7402 ret = gen_lowpart (g2->mode, comb);
7404 /* If these givs are identical, they can be combined. We use the results
7405 of express_from because the addends are not in a canonical form, so
7406 rtx_equal_p is a weaker test. */
7407 /* But don't combine a DEST_REG giv with a DEST_ADDR giv; we want the
7408 combination to be the other way round. */
7409 if (comb == g1->dest_reg
7410 && (g1->giv_type == DEST_REG || g2->giv_type == DEST_ADDR))
7412 return ret;
7415 /* If G2 can be expressed as a function of G1 and that function is valid
7416 as an address and no more expensive than using a register for G2,
7417 the expression of G2 in terms of G1 can be used. */
7418 if (ret != NULL_RTX
7419 && g2->giv_type == DEST_ADDR
7420 && memory_address_p (GET_MODE (g2->mem), ret))
7421 return ret;
7423 return NULL_RTX;
7426 /* Check each extension dependent giv in this class to see if its
7427 root biv is safe from wrapping in the interior mode, which would
7428 make the giv illegal. */
7430 static void
7431 check_ext_dependent_givs (bl, loop_info)
7432 struct iv_class *bl;
7433 struct loop_info *loop_info;
7435 int ze_ok = 0, se_ok = 0, info_ok = 0;
7436 enum machine_mode biv_mode = GET_MODE (bl->biv->src_reg);
7437 HOST_WIDE_INT start_val;
7438 unsigned HOST_WIDE_INT u_end_val = 0;
7439 unsigned HOST_WIDE_INT u_start_val = 0;
7440 rtx incr = pc_rtx;
7441 struct induction *v;
7443 /* Make sure the iteration data is available. We must have
7444 constants in order to be certain of no overflow. */
7445 /* ??? An unknown iteration count with an increment of +-1
7446 combined with friendly exit tests of against an invariant
7447 value is also amenable to optimization. Not implemented. */
7448 if (loop_info->n_iterations > 0
7449 && bl->initial_value
7450 && GET_CODE (bl->initial_value) == CONST_INT
7451 && (incr = biv_total_increment (bl))
7452 && GET_CODE (incr) == CONST_INT
7453 /* Make sure the host can represent the arithmetic. */
7454 && HOST_BITS_PER_WIDE_INT >= GET_MODE_BITSIZE (biv_mode))
7456 unsigned HOST_WIDE_INT abs_incr, total_incr;
7457 HOST_WIDE_INT s_end_val;
7458 int neg_incr;
7460 info_ok = 1;
7461 start_val = INTVAL (bl->initial_value);
7462 u_start_val = start_val;
7464 neg_incr = 0, abs_incr = INTVAL (incr);
7465 if (INTVAL (incr) < 0)
7466 neg_incr = 1, abs_incr = -abs_incr;
7467 total_incr = abs_incr * loop_info->n_iterations;
7469 /* Check for host arithmetic overflow. */
7470 if (total_incr / loop_info->n_iterations == abs_incr)
7472 unsigned HOST_WIDE_INT u_max;
7473 HOST_WIDE_INT s_max;
7475 u_end_val = start_val + (neg_incr ? -total_incr : total_incr);
7476 s_end_val = u_end_val;
7477 u_max = GET_MODE_MASK (biv_mode);
7478 s_max = u_max >> 1;
7480 /* Check zero extension of biv ok. */
7481 if (start_val >= 0
7482 /* Check for host arithmetic overflow. */
7483 && (neg_incr
7484 ? u_end_val < u_start_val
7485 : u_end_val > u_start_val)
7486 /* Check for target arithmetic overflow. */
7487 && (neg_incr
7488 ? 1 /* taken care of with host overflow */
7489 : u_end_val <= u_max))
7491 ze_ok = 1;
7494 /* Check sign extension of biv ok. */
7495 /* ??? While it is true that overflow with signed and pointer
7496 arithmetic is undefined, I fear too many programmers don't
7497 keep this fact in mind -- myself included on occasion.
7498 So leave alone with the signed overflow optimizations. */
7499 if (start_val >= -s_max - 1
7500 /* Check for host arithmetic overflow. */
7501 && (neg_incr
7502 ? s_end_val < start_val
7503 : s_end_val > start_val)
7504 /* Check for target arithmetic overflow. */
7505 && (neg_incr
7506 ? s_end_val >= -s_max - 1
7507 : s_end_val <= s_max))
7509 se_ok = 1;
7514 /* Invalidate givs that fail the tests. */
7515 for (v = bl->giv; v; v = v->next_iv)
7516 if (v->ext_dependent)
7518 enum rtx_code code = GET_CODE (v->ext_dependent);
7519 int ok = 0;
7521 switch (code)
7523 case SIGN_EXTEND:
7524 ok = se_ok;
7525 break;
7526 case ZERO_EXTEND:
7527 ok = ze_ok;
7528 break;
7530 case TRUNCATE:
7531 /* We don't know whether this value is being used as either
7532 signed or unsigned, so to safely truncate we must satisfy
7533 both. The initial check here verifies the BIV itself;
7534 once that is successful we may check its range wrt the
7535 derived GIV. */
7536 if (se_ok && ze_ok)
7538 enum machine_mode outer_mode = GET_MODE (v->ext_dependent);
7539 unsigned HOST_WIDE_INT max = GET_MODE_MASK (outer_mode) >> 1;
7541 /* We know from the above that both endpoints are nonnegative,
7542 and that there is no wrapping. Verify that both endpoints
7543 are within the (signed) range of the outer mode. */
7544 if (u_start_val <= max && u_end_val <= max)
7545 ok = 1;
7547 break;
7549 default:
7550 abort ();
7553 if (ok)
7555 if (loop_dump_stream)
7557 fprintf (loop_dump_stream,
7558 "Verified ext dependent giv at %d of reg %d\n",
7559 INSN_UID (v->insn), bl->regno);
7562 else
7564 if (loop_dump_stream)
7566 const char *why;
7568 if (info_ok)
7569 why = "biv iteration values overflowed";
7570 else
7572 if (incr == pc_rtx)
7573 incr = biv_total_increment (bl);
7574 if (incr == const1_rtx)
7575 why = "biv iteration info incomplete; incr by 1";
7576 else
7577 why = "biv iteration info incomplete";
7580 fprintf (loop_dump_stream,
7581 "Failed ext dependent giv at %d, %s\n",
7582 INSN_UID (v->insn), why);
7584 v->ignore = 1;
7585 bl->all_reduced = 0;
7590 /* Generate a version of VALUE in a mode appropriate for initializing V. */
7593 extend_value_for_giv (v, value)
7594 struct induction *v;
7595 rtx value;
7597 rtx ext_dep = v->ext_dependent;
7599 if (! ext_dep)
7600 return value;
7602 /* Recall that check_ext_dependent_givs verified that the known bounds
7603 of a biv did not overflow or wrap with respect to the extension for
7604 the giv. Therefore, constants need no additional adjustment. */
7605 if (CONSTANT_P (value) && GET_MODE (value) == VOIDmode)
7606 return value;
7608 /* Otherwise, we must adjust the value to compensate for the
7609 differing modes of the biv and the giv. */
7610 return gen_rtx_fmt_e (GET_CODE (ext_dep), GET_MODE (ext_dep), value);
7613 struct combine_givs_stats
7615 int giv_number;
7616 int total_benefit;
7619 static int
7620 cmp_combine_givs_stats (xp, yp)
7621 const PTR xp;
7622 const PTR yp;
7624 const struct combine_givs_stats * const x =
7625 (const struct combine_givs_stats *) xp;
7626 const struct combine_givs_stats * const y =
7627 (const struct combine_givs_stats *) yp;
7628 int d;
7629 d = y->total_benefit - x->total_benefit;
7630 /* Stabilize the sort. */
7631 if (!d)
7632 d = x->giv_number - y->giv_number;
7633 return d;
7636 /* Check all pairs of givs for iv_class BL and see if any can be combined with
7637 any other. If so, point SAME to the giv combined with and set NEW_REG to
7638 be an expression (in terms of the other giv's DEST_REG) equivalent to the
7639 giv. Also, update BENEFIT and related fields for cost/benefit analysis. */
7641 static void
7642 combine_givs (regs, bl)
7643 struct loop_regs *regs;
7644 struct iv_class *bl;
7646 /* Additional benefit to add for being combined multiple times. */
7647 const int extra_benefit = 3;
7649 struct induction *g1, *g2, **giv_array;
7650 int i, j, k, giv_count;
7651 struct combine_givs_stats *stats;
7652 rtx *can_combine;
7654 /* Count givs, because bl->giv_count is incorrect here. */
7655 giv_count = 0;
7656 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7657 if (!g1->ignore)
7658 giv_count++;
7660 giv_array
7661 = (struct induction **) alloca (giv_count * sizeof (struct induction *));
7662 i = 0;
7663 for (g1 = bl->giv; g1; g1 = g1->next_iv)
7664 if (!g1->ignore)
7665 giv_array[i++] = g1;
7667 stats = (struct combine_givs_stats *) xcalloc (giv_count, sizeof (*stats));
7668 can_combine = (rtx *) xcalloc (giv_count, giv_count * sizeof (rtx));
7670 for (i = 0; i < giv_count; i++)
7672 int this_benefit;
7673 rtx single_use;
7675 g1 = giv_array[i];
7676 stats[i].giv_number = i;
7678 /* If a DEST_REG GIV is used only once, do not allow it to combine
7679 with anything, for in doing so we will gain nothing that cannot
7680 be had by simply letting the GIV with which we would have combined
7681 to be reduced on its own. The losage shows up in particular with
7682 DEST_ADDR targets on hosts with reg+reg addressing, though it can
7683 be seen elsewhere as well. */
7684 if (g1->giv_type == DEST_REG
7685 && (single_use = regs->array[REGNO (g1->dest_reg)].single_usage)
7686 && single_use != const0_rtx)
7687 continue;
7689 this_benefit = g1->benefit;
7690 /* Add an additional weight for zero addends. */
7691 if (g1->no_const_addval)
7692 this_benefit += 1;
7694 for (j = 0; j < giv_count; j++)
7696 rtx this_combine;
7698 g2 = giv_array[j];
7699 if (g1 != g2
7700 && (this_combine = combine_givs_p (g1, g2)) != NULL_RTX)
7702 can_combine[i * giv_count + j] = this_combine;
7703 this_benefit += g2->benefit + extra_benefit;
7706 stats[i].total_benefit = this_benefit;
7709 /* Iterate, combining until we can't. */
7710 restart:
7711 qsort (stats, giv_count, sizeof (*stats), cmp_combine_givs_stats);
7713 if (loop_dump_stream)
7715 fprintf (loop_dump_stream, "Sorted combine statistics:\n");
7716 for (k = 0; k < giv_count; k++)
7718 g1 = giv_array[stats[k].giv_number];
7719 if (!g1->combined_with && !g1->same)
7720 fprintf (loop_dump_stream, " {%d, %d}",
7721 INSN_UID (giv_array[stats[k].giv_number]->insn),
7722 stats[k].total_benefit);
7724 putc ('\n', loop_dump_stream);
7727 for (k = 0; k < giv_count; k++)
7729 int g1_add_benefit = 0;
7731 i = stats[k].giv_number;
7732 g1 = giv_array[i];
7734 /* If it has already been combined, skip. */
7735 if (g1->combined_with || g1->same)
7736 continue;
7738 for (j = 0; j < giv_count; j++)
7740 g2 = giv_array[j];
7741 if (g1 != g2 && can_combine[i * giv_count + j]
7742 /* If it has already been combined, skip. */
7743 && ! g2->same && ! g2->combined_with)
7745 int l;
7747 g2->new_reg = can_combine[i * giv_count + j];
7748 g2->same = g1;
7749 /* For destination, we now may replace by mem expression instead
7750 of register. This changes the costs considerably, so add the
7751 compensation. */
7752 if (g2->giv_type == DEST_ADDR)
7753 g2->benefit = (g2->benefit + reg_address_cost
7754 - address_cost (g2->new_reg,
7755 GET_MODE (g2->mem)));
7756 g1->combined_with++;
7757 g1->lifetime += g2->lifetime;
7759 g1_add_benefit += g2->benefit;
7761 /* ??? The new final_[bg]iv_value code does a much better job
7762 of finding replaceable giv's, and hence this code may no
7763 longer be necessary. */
7764 if (! g2->replaceable && REG_USERVAR_P (g2->dest_reg))
7765 g1_add_benefit -= copy_cost;
7767 /* To help optimize the next set of combinations, remove
7768 this giv from the benefits of other potential mates. */
7769 for (l = 0; l < giv_count; ++l)
7771 int m = stats[l].giv_number;
7772 if (can_combine[m * giv_count + j])
7773 stats[l].total_benefit -= g2->benefit + extra_benefit;
7776 if (loop_dump_stream)
7777 fprintf (loop_dump_stream,
7778 "giv at %d combined with giv at %d; new benefit %d + %d, lifetime %d\n",
7779 INSN_UID (g2->insn), INSN_UID (g1->insn),
7780 g1->benefit, g1_add_benefit, g1->lifetime);
7784 /* To help optimize the next set of combinations, remove
7785 this giv from the benefits of other potential mates. */
7786 if (g1->combined_with)
7788 for (j = 0; j < giv_count; ++j)
7790 int m = stats[j].giv_number;
7791 if (can_combine[m * giv_count + i])
7792 stats[j].total_benefit -= g1->benefit + extra_benefit;
7795 g1->benefit += g1_add_benefit;
7797 /* We've finished with this giv, and everything it touched.
7798 Restart the combination so that proper weights for the
7799 rest of the givs are properly taken into account. */
7800 /* ??? Ideally we would compact the arrays at this point, so
7801 as to not cover old ground. But sanely compacting
7802 can_combine is tricky. */
7803 goto restart;
7807 /* Clean up. */
7808 free (stats);
7809 free (can_combine);
7812 /* Generate sequence for REG = B * M + A. */
7814 static rtx
7815 gen_add_mult (b, m, a, reg)
7816 rtx b; /* initial value of basic induction variable */
7817 rtx m; /* multiplicative constant */
7818 rtx a; /* additive constant */
7819 rtx reg; /* destination register */
7821 rtx seq;
7822 rtx result;
7824 start_sequence ();
7825 /* Use unsigned arithmetic. */
7826 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
7827 if (reg != result)
7828 emit_move_insn (reg, result);
7829 seq = get_insns ();
7830 end_sequence ();
7832 return seq;
7836 /* Update registers created in insn sequence SEQ. */
7838 static void
7839 loop_regs_update (loop, seq)
7840 const struct loop *loop ATTRIBUTE_UNUSED;
7841 rtx seq;
7843 rtx insn;
7845 /* Update register info for alias analysis. */
7847 if (seq == NULL_RTX)
7848 return;
7850 if (INSN_P (seq))
7852 insn = seq;
7853 while (insn != NULL_RTX)
7855 rtx set = single_set (insn);
7857 if (set && GET_CODE (SET_DEST (set)) == REG)
7858 record_base_value (REGNO (SET_DEST (set)), SET_SRC (set), 0);
7860 insn = NEXT_INSN (insn);
7863 else if (GET_CODE (seq) == SET
7864 && GET_CODE (SET_DEST (seq)) == REG)
7865 record_base_value (REGNO (SET_DEST (seq)), SET_SRC (seq), 0);
7869 /* EMIT code before BEFORE_BB/BEFORE_INSN to set REG = B * M + A. */
7871 void
7872 loop_iv_add_mult_emit_before (loop, b, m, a, reg, before_bb, before_insn)
7873 const struct loop *loop;
7874 rtx b; /* initial value of basic induction variable */
7875 rtx m; /* multiplicative constant */
7876 rtx a; /* additive constant */
7877 rtx reg; /* destination register */
7878 basic_block before_bb;
7879 rtx before_insn;
7881 rtx seq;
7883 if (! before_insn)
7885 loop_iv_add_mult_hoist (loop, b, m, a, reg);
7886 return;
7889 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7890 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7892 /* Increase the lifetime of any invariants moved further in code. */
7893 update_reg_last_use (a, before_insn);
7894 update_reg_last_use (b, before_insn);
7895 update_reg_last_use (m, before_insn);
7897 loop_insn_emit_before (loop, before_bb, before_insn, seq);
7899 /* It is possible that the expansion created lots of new registers.
7900 Iterate over the sequence we just created and record them all. */
7901 loop_regs_update (loop, seq);
7905 /* Emit insns in loop pre-header to set REG = B * M + A. */
7907 void
7908 loop_iv_add_mult_sink (loop, b, m, a, reg)
7909 const struct loop *loop;
7910 rtx b; /* initial value of basic induction variable */
7911 rtx m; /* multiplicative constant */
7912 rtx a; /* additive constant */
7913 rtx reg; /* destination register */
7915 rtx seq;
7917 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7918 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7920 /* Increase the lifetime of any invariants moved further in code.
7921 ???? Is this really necessary? */
7922 update_reg_last_use (a, loop->sink);
7923 update_reg_last_use (b, loop->sink);
7924 update_reg_last_use (m, loop->sink);
7926 loop_insn_sink (loop, seq);
7928 /* It is possible that the expansion created lots of new registers.
7929 Iterate over the sequence we just created and record them all. */
7930 loop_regs_update (loop, seq);
7934 /* Emit insns after loop to set REG = B * M + A. */
7936 void
7937 loop_iv_add_mult_hoist (loop, b, m, a, reg)
7938 const struct loop *loop;
7939 rtx b; /* initial value of basic induction variable */
7940 rtx m; /* multiplicative constant */
7941 rtx a; /* additive constant */
7942 rtx reg; /* destination register */
7944 rtx seq;
7946 /* Use copy_rtx to prevent unexpected sharing of these rtx. */
7947 seq = gen_add_mult (copy_rtx (b), copy_rtx (m), copy_rtx (a), reg);
7949 loop_insn_hoist (loop, seq);
7951 /* It is possible that the expansion created lots of new registers.
7952 Iterate over the sequence we just created and record them all. */
7953 loop_regs_update (loop, seq);
7958 /* Similar to gen_add_mult, but compute cost rather than generating
7959 sequence. */
7961 static int
7962 iv_add_mult_cost (b, m, a, reg)
7963 rtx b; /* initial value of basic induction variable */
7964 rtx m; /* multiplicative constant */
7965 rtx a; /* additive constant */
7966 rtx reg; /* destination register */
7968 int cost = 0;
7969 rtx last, result;
7971 start_sequence ();
7972 result = expand_mult_add (b, reg, m, a, GET_MODE (reg), 1);
7973 if (reg != result)
7974 emit_move_insn (reg, result);
7975 last = get_last_insn ();
7976 while (last)
7978 rtx t = single_set (last);
7979 if (t)
7980 cost += rtx_cost (SET_SRC (t), SET);
7981 last = PREV_INSN (last);
7983 end_sequence ();
7984 return cost;
7987 /* Test whether A * B can be computed without
7988 an actual multiply insn. Value is 1 if so.
7990 ??? This function stinks because it generates a ton of wasted RTL
7991 ??? and as a result fragments GC memory to no end. There are other
7992 ??? places in the compiler which are invoked a lot and do the same
7993 ??? thing, generate wasted RTL just to see if something is possible. */
7995 static int
7996 product_cheap_p (a, b)
7997 rtx a;
7998 rtx b;
8000 rtx tmp;
8001 int win, n_insns;
8003 /* If only one is constant, make it B. */
8004 if (GET_CODE (a) == CONST_INT)
8005 tmp = a, a = b, b = tmp;
8007 /* If first constant, both constant, so don't need multiply. */
8008 if (GET_CODE (a) == CONST_INT)
8009 return 1;
8011 /* If second not constant, neither is constant, so would need multiply. */
8012 if (GET_CODE (b) != CONST_INT)
8013 return 0;
8015 /* One operand is constant, so might not need multiply insn. Generate the
8016 code for the multiply and see if a call or multiply, or long sequence
8017 of insns is generated. */
8019 start_sequence ();
8020 expand_mult (GET_MODE (a), a, b, NULL_RTX, 1);
8021 tmp = get_insns ();
8022 end_sequence ();
8024 win = 1;
8025 if (INSN_P (tmp))
8027 n_insns = 0;
8028 while (tmp != NULL_RTX)
8030 rtx next = NEXT_INSN (tmp);
8032 if (++n_insns > 3
8033 || GET_CODE (tmp) != INSN
8034 || (GET_CODE (PATTERN (tmp)) == SET
8035 && GET_CODE (SET_SRC (PATTERN (tmp))) == MULT)
8036 || (GET_CODE (PATTERN (tmp)) == PARALLEL
8037 && GET_CODE (XVECEXP (PATTERN (tmp), 0, 0)) == SET
8038 && GET_CODE (SET_SRC (XVECEXP (PATTERN (tmp), 0, 0))) == MULT))
8040 win = 0;
8041 break;
8044 tmp = next;
8047 else if (GET_CODE (tmp) == SET
8048 && GET_CODE (SET_SRC (tmp)) == MULT)
8049 win = 0;
8050 else if (GET_CODE (tmp) == PARALLEL
8051 && GET_CODE (XVECEXP (tmp, 0, 0)) == SET
8052 && GET_CODE (SET_SRC (XVECEXP (tmp, 0, 0))) == MULT)
8053 win = 0;
8055 return win;
8058 /* Check to see if loop can be terminated by a "decrement and branch until
8059 zero" instruction. If so, add a REG_NONNEG note to the branch insn if so.
8060 Also try reversing an increment loop to a decrement loop
8061 to see if the optimization can be performed.
8062 Value is nonzero if optimization was performed. */
8064 /* This is useful even if the architecture doesn't have such an insn,
8065 because it might change a loops which increments from 0 to n to a loop
8066 which decrements from n to 0. A loop that decrements to zero is usually
8067 faster than one that increments from zero. */
8069 /* ??? This could be rewritten to use some of the loop unrolling procedures,
8070 such as approx_final_value, biv_total_increment, loop_iterations, and
8071 final_[bg]iv_value. */
8073 static int
8074 check_dbra_loop (loop, insn_count)
8075 struct loop *loop;
8076 int insn_count;
8078 struct loop_info *loop_info = LOOP_INFO (loop);
8079 struct loop_regs *regs = LOOP_REGS (loop);
8080 struct loop_ivs *ivs = LOOP_IVS (loop);
8081 struct iv_class *bl;
8082 rtx reg;
8083 rtx jump_label;
8084 rtx final_value;
8085 rtx start_value;
8086 rtx new_add_val;
8087 rtx comparison;
8088 rtx before_comparison;
8089 rtx p;
8090 rtx jump;
8091 rtx first_compare;
8092 int compare_and_branch;
8093 rtx loop_start = loop->start;
8094 rtx loop_end = loop->end;
8096 /* If last insn is a conditional branch, and the insn before tests a
8097 register value, try to optimize it. Otherwise, we can't do anything. */
8099 jump = PREV_INSN (loop_end);
8100 comparison = get_condition_for_loop (loop, jump);
8101 if (comparison == 0)
8102 return 0;
8103 if (!onlyjump_p (jump))
8104 return 0;
8106 /* Try to compute whether the compare/branch at the loop end is one or
8107 two instructions. */
8108 get_condition (jump, &first_compare);
8109 if (first_compare == jump)
8110 compare_and_branch = 1;
8111 else if (first_compare == prev_nonnote_insn (jump))
8112 compare_and_branch = 2;
8113 else
8114 return 0;
8117 /* If more than one condition is present to control the loop, then
8118 do not proceed, as this function does not know how to rewrite
8119 loop tests with more than one condition.
8121 Look backwards from the first insn in the last comparison
8122 sequence and see if we've got another comparison sequence. */
8124 rtx jump1;
8125 if ((jump1 = prev_nonnote_insn (first_compare)) != loop->cont)
8126 if (GET_CODE (jump1) == JUMP_INSN)
8127 return 0;
8130 /* Check all of the bivs to see if the compare uses one of them.
8131 Skip biv's set more than once because we can't guarantee that
8132 it will be zero on the last iteration. Also skip if the biv is
8133 used between its update and the test insn. */
8135 for (bl = ivs->list; bl; bl = bl->next)
8137 if (bl->biv_count == 1
8138 && ! bl->biv->maybe_multiple
8139 && bl->biv->dest_reg == XEXP (comparison, 0)
8140 && ! reg_used_between_p (regno_reg_rtx[bl->regno], bl->biv->insn,
8141 first_compare))
8142 break;
8145 if (! bl)
8146 return 0;
8148 /* Look for the case where the basic induction variable is always
8149 nonnegative, and equals zero on the last iteration.
8150 In this case, add a reg_note REG_NONNEG, which allows the
8151 m68k DBRA instruction to be used. */
8153 if (((GET_CODE (comparison) == GT
8154 && GET_CODE (XEXP (comparison, 1)) == CONST_INT
8155 && INTVAL (XEXP (comparison, 1)) == -1)
8156 || (GET_CODE (comparison) == NE && XEXP (comparison, 1) == const0_rtx))
8157 && GET_CODE (bl->biv->add_val) == CONST_INT
8158 && INTVAL (bl->biv->add_val) < 0)
8160 /* Initial value must be greater than 0,
8161 init_val % -dec_value == 0 to ensure that it equals zero on
8162 the last iteration */
8164 if (GET_CODE (bl->initial_value) == CONST_INT
8165 && INTVAL (bl->initial_value) > 0
8166 && (INTVAL (bl->initial_value)
8167 % (-INTVAL (bl->biv->add_val))) == 0)
8169 /* register always nonnegative, add REG_NOTE to branch */
8170 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8171 REG_NOTES (jump)
8172 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8173 REG_NOTES (jump));
8174 bl->nonneg = 1;
8176 return 1;
8179 /* If the decrement is 1 and the value was tested as >= 0 before
8180 the loop, then we can safely optimize. */
8181 for (p = loop_start; p; p = PREV_INSN (p))
8183 if (GET_CODE (p) == CODE_LABEL)
8184 break;
8185 if (GET_CODE (p) != JUMP_INSN)
8186 continue;
8188 before_comparison = get_condition_for_loop (loop, p);
8189 if (before_comparison
8190 && XEXP (before_comparison, 0) == bl->biv->dest_reg
8191 && GET_CODE (before_comparison) == LT
8192 && XEXP (before_comparison, 1) == const0_rtx
8193 && ! reg_set_between_p (bl->biv->dest_reg, p, loop_start)
8194 && INTVAL (bl->biv->add_val) == -1)
8196 if (! find_reg_note (jump, REG_NONNEG, NULL_RTX))
8197 REG_NOTES (jump)
8198 = gen_rtx_EXPR_LIST (REG_NONNEG, bl->biv->dest_reg,
8199 REG_NOTES (jump));
8200 bl->nonneg = 1;
8202 return 1;
8206 else if (GET_CODE (bl->biv->add_val) == CONST_INT
8207 && INTVAL (bl->biv->add_val) > 0)
8209 /* Try to change inc to dec, so can apply above optimization. */
8210 /* Can do this if:
8211 all registers modified are induction variables or invariant,
8212 all memory references have non-overlapping addresses
8213 (obviously true if only one write)
8214 allow 2 insns for the compare/jump at the end of the loop. */
8215 /* Also, we must avoid any instructions which use both the reversed
8216 biv and another biv. Such instructions will fail if the loop is
8217 reversed. We meet this condition by requiring that either
8218 no_use_except_counting is true, or else that there is only
8219 one biv. */
8220 int num_nonfixed_reads = 0;
8221 /* 1 if the iteration var is used only to count iterations. */
8222 int no_use_except_counting = 0;
8223 /* 1 if the loop has no memory store, or it has a single memory store
8224 which is reversible. */
8225 int reversible_mem_store = 1;
8227 if (bl->giv_count == 0
8228 && !loop->exit_count
8229 && !loop_info->has_multiple_exit_targets)
8231 rtx bivreg = regno_reg_rtx[bl->regno];
8232 struct iv_class *blt;
8234 /* If there are no givs for this biv, and the only exit is the
8235 fall through at the end of the loop, then
8236 see if perhaps there are no uses except to count. */
8237 no_use_except_counting = 1;
8238 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8239 if (INSN_P (p))
8241 rtx set = single_set (p);
8243 if (set && GET_CODE (SET_DEST (set)) == REG
8244 && REGNO (SET_DEST (set)) == bl->regno)
8245 /* An insn that sets the biv is okay. */
8247 else if ((p == prev_nonnote_insn (prev_nonnote_insn (loop_end))
8248 || p == prev_nonnote_insn (loop_end))
8249 && reg_mentioned_p (bivreg, PATTERN (p)))
8251 /* If either of these insns uses the biv and sets a pseudo
8252 that has more than one usage, then the biv has uses
8253 other than counting since it's used to derive a value
8254 that is used more than one time. */
8255 note_stores (PATTERN (p), note_set_pseudo_multiple_uses,
8256 regs);
8257 if (regs->multiple_uses)
8259 no_use_except_counting = 0;
8260 break;
8263 else if (reg_mentioned_p (bivreg, PATTERN (p)))
8265 no_use_except_counting = 0;
8266 break;
8270 /* A biv has uses besides counting if it is used to set
8271 another biv. */
8272 for (blt = ivs->list; blt; blt = blt->next)
8273 if (blt->init_set
8274 && reg_mentioned_p (bivreg, SET_SRC (blt->init_set)))
8276 no_use_except_counting = 0;
8277 break;
8281 if (no_use_except_counting)
8282 /* No need to worry about MEMs. */
8284 else if (loop_info->num_mem_sets <= 1)
8286 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8287 if (INSN_P (p))
8288 num_nonfixed_reads += count_nonfixed_reads (loop, PATTERN (p));
8290 /* If the loop has a single store, and the destination address is
8291 invariant, then we can't reverse the loop, because this address
8292 might then have the wrong value at loop exit.
8293 This would work if the source was invariant also, however, in that
8294 case, the insn should have been moved out of the loop. */
8296 if (loop_info->num_mem_sets == 1)
8298 struct induction *v;
8300 /* If we could prove that each of the memory locations
8301 written to was different, then we could reverse the
8302 store -- but we don't presently have any way of
8303 knowing that. */
8304 reversible_mem_store = 0;
8306 /* If the store depends on a register that is set after the
8307 store, it depends on the initial value, and is thus not
8308 reversible. */
8309 for (v = bl->giv; reversible_mem_store && v; v = v->next_iv)
8311 if (v->giv_type == DEST_REG
8312 && reg_mentioned_p (v->dest_reg,
8313 PATTERN (loop_info->first_loop_store_insn))
8314 && loop_insn_first_p (loop_info->first_loop_store_insn,
8315 v->insn))
8316 reversible_mem_store = 0;
8320 else
8321 return 0;
8323 /* This code only acts for innermost loops. Also it simplifies
8324 the memory address check by only reversing loops with
8325 zero or one memory access.
8326 Two memory accesses could involve parts of the same array,
8327 and that can't be reversed.
8328 If the biv is used only for counting, than we don't need to worry
8329 about all these things. */
8331 if ((num_nonfixed_reads <= 1
8332 && ! loop_info->has_nonconst_call
8333 && ! loop_info->has_prefetch
8334 && ! loop_info->has_volatile
8335 && reversible_mem_store
8336 && (bl->giv_count + bl->biv_count + loop_info->num_mem_sets
8337 + num_unmoved_movables (loop) + compare_and_branch == insn_count)
8338 && (bl == ivs->list && bl->next == 0))
8339 || (no_use_except_counting && ! loop_info->has_prefetch))
8341 rtx tem;
8343 /* Loop can be reversed. */
8344 if (loop_dump_stream)
8345 fprintf (loop_dump_stream, "Can reverse loop\n");
8347 /* Now check other conditions:
8349 The increment must be a constant, as must the initial value,
8350 and the comparison code must be LT.
8352 This test can probably be improved since +/- 1 in the constant
8353 can be obtained by changing LT to LE and vice versa; this is
8354 confusing. */
8356 if (comparison
8357 /* for constants, LE gets turned into LT */
8358 && (GET_CODE (comparison) == LT
8359 || (GET_CODE (comparison) == LE
8360 && no_use_except_counting)))
8362 HOST_WIDE_INT add_val, add_adjust, comparison_val = 0;
8363 rtx initial_value, comparison_value;
8364 int nonneg = 0;
8365 enum rtx_code cmp_code;
8366 int comparison_const_width;
8367 unsigned HOST_WIDE_INT comparison_sign_mask;
8369 add_val = INTVAL (bl->biv->add_val);
8370 comparison_value = XEXP (comparison, 1);
8371 if (GET_MODE (comparison_value) == VOIDmode)
8372 comparison_const_width
8373 = GET_MODE_BITSIZE (GET_MODE (XEXP (comparison, 0)));
8374 else
8375 comparison_const_width
8376 = GET_MODE_BITSIZE (GET_MODE (comparison_value));
8377 if (comparison_const_width > HOST_BITS_PER_WIDE_INT)
8378 comparison_const_width = HOST_BITS_PER_WIDE_INT;
8379 comparison_sign_mask
8380 = (unsigned HOST_WIDE_INT) 1 << (comparison_const_width - 1);
8382 /* If the comparison value is not a loop invariant, then we
8383 can not reverse this loop.
8385 ??? If the insns which initialize the comparison value as
8386 a whole compute an invariant result, then we could move
8387 them out of the loop and proceed with loop reversal. */
8388 if (! loop_invariant_p (loop, comparison_value))
8389 return 0;
8391 if (GET_CODE (comparison_value) == CONST_INT)
8392 comparison_val = INTVAL (comparison_value);
8393 initial_value = bl->initial_value;
8395 /* Normalize the initial value if it is an integer and
8396 has no other use except as a counter. This will allow
8397 a few more loops to be reversed. */
8398 if (no_use_except_counting
8399 && GET_CODE (comparison_value) == CONST_INT
8400 && GET_CODE (initial_value) == CONST_INT)
8402 comparison_val = comparison_val - INTVAL (bl->initial_value);
8403 /* The code below requires comparison_val to be a multiple
8404 of add_val in order to do the loop reversal, so
8405 round up comparison_val to a multiple of add_val.
8406 Since comparison_value is constant, we know that the
8407 current comparison code is LT. */
8408 comparison_val = comparison_val + add_val - 1;
8409 comparison_val
8410 -= (unsigned HOST_WIDE_INT) comparison_val % add_val;
8411 /* We postpone overflow checks for COMPARISON_VAL here;
8412 even if there is an overflow, we might still be able to
8413 reverse the loop, if converting the loop exit test to
8414 NE is possible. */
8415 initial_value = const0_rtx;
8418 /* First check if we can do a vanilla loop reversal. */
8419 if (initial_value == const0_rtx
8420 /* If we have a decrement_and_branch_on_count,
8421 prefer the NE test, since this will allow that
8422 instruction to be generated. Note that we must
8423 use a vanilla loop reversal if the biv is used to
8424 calculate a giv or has a non-counting use. */
8425 #if ! defined (HAVE_decrement_and_branch_until_zero) \
8426 && defined (HAVE_decrement_and_branch_on_count)
8427 && (! (add_val == 1 && loop->vtop
8428 && (bl->biv_count == 0
8429 || no_use_except_counting)))
8430 #endif
8431 && GET_CODE (comparison_value) == CONST_INT
8432 /* Now do postponed overflow checks on COMPARISON_VAL. */
8433 && ! (((comparison_val - add_val) ^ INTVAL (comparison_value))
8434 & comparison_sign_mask))
8436 /* Register will always be nonnegative, with value
8437 0 on last iteration */
8438 add_adjust = add_val;
8439 nonneg = 1;
8440 cmp_code = GE;
8442 else if (add_val == 1 && loop->vtop
8443 && (bl->biv_count == 0
8444 || no_use_except_counting))
8446 add_adjust = 0;
8447 cmp_code = NE;
8449 else
8450 return 0;
8452 if (GET_CODE (comparison) == LE)
8453 add_adjust -= add_val;
8455 /* If the initial value is not zero, or if the comparison
8456 value is not an exact multiple of the increment, then we
8457 can not reverse this loop. */
8458 if (initial_value == const0_rtx
8459 && GET_CODE (comparison_value) == CONST_INT)
8461 if (((unsigned HOST_WIDE_INT) comparison_val % add_val) != 0)
8462 return 0;
8464 else
8466 if (! no_use_except_counting || add_val != 1)
8467 return 0;
8470 final_value = comparison_value;
8472 /* Reset these in case we normalized the initial value
8473 and comparison value above. */
8474 if (GET_CODE (comparison_value) == CONST_INT
8475 && GET_CODE (initial_value) == CONST_INT)
8477 comparison_value = GEN_INT (comparison_val);
8478 final_value
8479 = GEN_INT (comparison_val + INTVAL (bl->initial_value));
8481 bl->initial_value = initial_value;
8483 /* Save some info needed to produce the new insns. */
8484 reg = bl->biv->dest_reg;
8485 jump_label = condjump_label (PREV_INSN (loop_end));
8486 new_add_val = GEN_INT (-INTVAL (bl->biv->add_val));
8488 /* Set start_value; if this is not a CONST_INT, we need
8489 to generate a SUB.
8490 Initialize biv to start_value before loop start.
8491 The old initializing insn will be deleted as a
8492 dead store by flow.c. */
8493 if (initial_value == const0_rtx
8494 && GET_CODE (comparison_value) == CONST_INT)
8496 start_value = GEN_INT (comparison_val - add_adjust);
8497 loop_insn_hoist (loop, gen_move_insn (reg, start_value));
8499 else if (GET_CODE (initial_value) == CONST_INT)
8501 enum machine_mode mode = GET_MODE (reg);
8502 rtx offset = GEN_INT (-INTVAL (initial_value) - add_adjust);
8503 rtx add_insn = gen_add3_insn (reg, comparison_value, offset);
8505 if (add_insn == 0)
8506 return 0;
8508 start_value
8509 = gen_rtx_PLUS (mode, comparison_value, offset);
8510 loop_insn_hoist (loop, add_insn);
8511 if (GET_CODE (comparison) == LE)
8512 final_value = gen_rtx_PLUS (mode, comparison_value,
8513 GEN_INT (add_val));
8515 else if (! add_adjust)
8517 enum machine_mode mode = GET_MODE (reg);
8518 rtx sub_insn = gen_sub3_insn (reg, comparison_value,
8519 initial_value);
8521 if (sub_insn == 0)
8522 return 0;
8523 start_value
8524 = gen_rtx_MINUS (mode, comparison_value, initial_value);
8525 loop_insn_hoist (loop, sub_insn);
8527 else
8528 /* We could handle the other cases too, but it'll be
8529 better to have a testcase first. */
8530 return 0;
8532 /* We may not have a single insn which can increment a reg, so
8533 create a sequence to hold all the insns from expand_inc. */
8534 start_sequence ();
8535 expand_inc (reg, new_add_val);
8536 tem = get_insns ();
8537 end_sequence ();
8539 p = loop_insn_emit_before (loop, 0, bl->biv->insn, tem);
8540 delete_insn (bl->biv->insn);
8542 /* Update biv info to reflect its new status. */
8543 bl->biv->insn = p;
8544 bl->initial_value = start_value;
8545 bl->biv->add_val = new_add_val;
8547 /* Update loop info. */
8548 loop_info->initial_value = reg;
8549 loop_info->initial_equiv_value = reg;
8550 loop_info->final_value = const0_rtx;
8551 loop_info->final_equiv_value = const0_rtx;
8552 loop_info->comparison_value = const0_rtx;
8553 loop_info->comparison_code = cmp_code;
8554 loop_info->increment = new_add_val;
8556 /* Inc LABEL_NUSES so that delete_insn will
8557 not delete the label. */
8558 LABEL_NUSES (XEXP (jump_label, 0))++;
8560 /* Emit an insn after the end of the loop to set the biv's
8561 proper exit value if it is used anywhere outside the loop. */
8562 if ((REGNO_LAST_UID (bl->regno) != INSN_UID (first_compare))
8563 || ! bl->init_insn
8564 || REGNO_FIRST_UID (bl->regno) != INSN_UID (bl->init_insn))
8565 loop_insn_sink (loop, gen_load_of_final_value (reg, final_value));
8567 /* Delete compare/branch at end of loop. */
8568 delete_related_insns (PREV_INSN (loop_end));
8569 if (compare_and_branch == 2)
8570 delete_related_insns (first_compare);
8572 /* Add new compare/branch insn at end of loop. */
8573 start_sequence ();
8574 emit_cmp_and_jump_insns (reg, const0_rtx, cmp_code, NULL_RTX,
8575 GET_MODE (reg), 0,
8576 XEXP (jump_label, 0));
8577 tem = get_insns ();
8578 end_sequence ();
8579 emit_jump_insn_before (tem, loop_end);
8581 for (tem = PREV_INSN (loop_end);
8582 tem && GET_CODE (tem) != JUMP_INSN;
8583 tem = PREV_INSN (tem))
8586 if (tem)
8587 JUMP_LABEL (tem) = XEXP (jump_label, 0);
8589 if (nonneg)
8591 if (tem)
8593 /* Increment of LABEL_NUSES done above. */
8594 /* Register is now always nonnegative,
8595 so add REG_NONNEG note to the branch. */
8596 REG_NOTES (tem) = gen_rtx_EXPR_LIST (REG_NONNEG, reg,
8597 REG_NOTES (tem));
8599 bl->nonneg = 1;
8602 /* No insn may reference both the reversed and another biv or it
8603 will fail (see comment near the top of the loop reversal
8604 code).
8605 Earlier on, we have verified that the biv has no use except
8606 counting, or it is the only biv in this function.
8607 However, the code that computes no_use_except_counting does
8608 not verify reg notes. It's possible to have an insn that
8609 references another biv, and has a REG_EQUAL note with an
8610 expression based on the reversed biv. To avoid this case,
8611 remove all REG_EQUAL notes based on the reversed biv
8612 here. */
8613 for (p = loop_start; p != loop_end; p = NEXT_INSN (p))
8614 if (INSN_P (p))
8616 rtx *pnote;
8617 rtx set = single_set (p);
8618 /* If this is a set of a GIV based on the reversed biv, any
8619 REG_EQUAL notes should still be correct. */
8620 if (! set
8621 || GET_CODE (SET_DEST (set)) != REG
8622 || (size_t) REGNO (SET_DEST (set)) >= ivs->n_regs
8623 || REG_IV_TYPE (ivs, REGNO (SET_DEST (set))) != GENERAL_INDUCT
8624 || REG_IV_INFO (ivs, REGNO (SET_DEST (set)))->src_reg != bl->biv->src_reg)
8625 for (pnote = &REG_NOTES (p); *pnote;)
8627 if (REG_NOTE_KIND (*pnote) == REG_EQUAL
8628 && reg_mentioned_p (regno_reg_rtx[bl->regno],
8629 XEXP (*pnote, 0)))
8630 *pnote = XEXP (*pnote, 1);
8631 else
8632 pnote = &XEXP (*pnote, 1);
8636 /* Mark that this biv has been reversed. Each giv which depends
8637 on this biv, and which is also live past the end of the loop
8638 will have to be fixed up. */
8640 bl->reversed = 1;
8642 if (loop_dump_stream)
8644 fprintf (loop_dump_stream, "Reversed loop");
8645 if (bl->nonneg)
8646 fprintf (loop_dump_stream, " and added reg_nonneg\n");
8647 else
8648 fprintf (loop_dump_stream, "\n");
8651 return 1;
8656 return 0;
8659 /* Verify whether the biv BL appears to be eliminable,
8660 based on the insns in the loop that refer to it.
8662 If ELIMINATE_P is nonzero, actually do the elimination.
8664 THRESHOLD and INSN_COUNT are from loop_optimize and are used to
8665 determine whether invariant insns should be placed inside or at the
8666 start of the loop. */
8668 static int
8669 maybe_eliminate_biv (loop, bl, eliminate_p, threshold, insn_count)
8670 const struct loop *loop;
8671 struct iv_class *bl;
8672 int eliminate_p;
8673 int threshold, insn_count;
8675 struct loop_ivs *ivs = LOOP_IVS (loop);
8676 rtx reg = bl->biv->dest_reg;
8677 rtx p;
8679 /* Scan all insns in the loop, stopping if we find one that uses the
8680 biv in a way that we cannot eliminate. */
8682 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
8684 enum rtx_code code = GET_CODE (p);
8685 basic_block where_bb = 0;
8686 rtx where_insn = threshold >= insn_count ? 0 : p;
8687 rtx note;
8689 /* If this is a libcall that sets a giv, skip ahead to its end. */
8690 if (GET_RTX_CLASS (code) == 'i')
8692 note = find_reg_note (p, REG_LIBCALL, NULL_RTX);
8694 if (note)
8696 rtx last = XEXP (note, 0);
8697 rtx set = single_set (last);
8699 if (set && GET_CODE (SET_DEST (set)) == REG)
8701 unsigned int regno = REGNO (SET_DEST (set));
8703 if (regno < ivs->n_regs
8704 && REG_IV_TYPE (ivs, regno) == GENERAL_INDUCT
8705 && REG_IV_INFO (ivs, regno)->src_reg == bl->biv->src_reg)
8706 p = last;
8711 /* Closely examine the insn if the biv is mentioned. */
8712 if ((code == INSN || code == JUMP_INSN || code == CALL_INSN)
8713 && reg_mentioned_p (reg, PATTERN (p))
8714 && ! maybe_eliminate_biv_1 (loop, PATTERN (p), p, bl,
8715 eliminate_p, where_bb, where_insn))
8717 if (loop_dump_stream)
8718 fprintf (loop_dump_stream,
8719 "Cannot eliminate biv %d: biv used in insn %d.\n",
8720 bl->regno, INSN_UID (p));
8721 break;
8724 /* If we are eliminating, kill REG_EQUAL notes mentioning the biv. */
8725 if (eliminate_p
8726 && (note = find_reg_note (p, REG_EQUAL, NULL_RTX)) != NULL_RTX
8727 && reg_mentioned_p (reg, XEXP (note, 0)))
8728 remove_note (p, note);
8731 if (p == loop->end)
8733 if (loop_dump_stream)
8734 fprintf (loop_dump_stream, "biv %d %s eliminated.\n",
8735 bl->regno, eliminate_p ? "was" : "can be");
8736 return 1;
8739 return 0;
8742 /* INSN and REFERENCE are instructions in the same insn chain.
8743 Return nonzero if INSN is first. */
8746 loop_insn_first_p (insn, reference)
8747 rtx insn, reference;
8749 rtx p, q;
8751 for (p = insn, q = reference;;)
8753 /* Start with test for not first so that INSN == REFERENCE yields not
8754 first. */
8755 if (q == insn || ! p)
8756 return 0;
8757 if (p == reference || ! q)
8758 return 1;
8760 /* Either of P or Q might be a NOTE. Notes have the same LUID as the
8761 previous insn, hence the <= comparison below does not work if
8762 P is a note. */
8763 if (INSN_UID (p) < max_uid_for_loop
8764 && INSN_UID (q) < max_uid_for_loop
8765 && GET_CODE (p) != NOTE)
8766 return INSN_LUID (p) <= INSN_LUID (q);
8768 if (INSN_UID (p) >= max_uid_for_loop
8769 || GET_CODE (p) == NOTE)
8770 p = NEXT_INSN (p);
8771 if (INSN_UID (q) >= max_uid_for_loop)
8772 q = NEXT_INSN (q);
8776 /* We are trying to eliminate BIV in INSN using GIV. Return nonzero if
8777 the offset that we have to take into account due to auto-increment /
8778 div derivation is zero. */
8779 static int
8780 biv_elimination_giv_has_0_offset (biv, giv, insn)
8781 struct induction *biv, *giv;
8782 rtx insn;
8784 /* If the giv V had the auto-inc address optimization applied
8785 to it, and INSN occurs between the giv insn and the biv
8786 insn, then we'd have to adjust the value used here.
8787 This is rare, so we don't bother to make this possible. */
8788 if (giv->auto_inc_opt
8789 && ((loop_insn_first_p (giv->insn, insn)
8790 && loop_insn_first_p (insn, biv->insn))
8791 || (loop_insn_first_p (biv->insn, insn)
8792 && loop_insn_first_p (insn, giv->insn))))
8793 return 0;
8795 return 1;
8798 /* If BL appears in X (part of the pattern of INSN), see if we can
8799 eliminate its use. If so, return 1. If not, return 0.
8801 If BIV does not appear in X, return 1.
8803 If ELIMINATE_P is nonzero, actually do the elimination.
8804 WHERE_INSN/WHERE_BB indicate where extra insns should be added.
8805 Depending on how many items have been moved out of the loop, it
8806 will either be before INSN (when WHERE_INSN is nonzero) or at the
8807 start of the loop (when WHERE_INSN is zero). */
8809 static int
8810 maybe_eliminate_biv_1 (loop, x, insn, bl, eliminate_p, where_bb, where_insn)
8811 const struct loop *loop;
8812 rtx x, insn;
8813 struct iv_class *bl;
8814 int eliminate_p;
8815 basic_block where_bb;
8816 rtx where_insn;
8818 enum rtx_code code = GET_CODE (x);
8819 rtx reg = bl->biv->dest_reg;
8820 enum machine_mode mode = GET_MODE (reg);
8821 struct induction *v;
8822 rtx arg, tem;
8823 #ifdef HAVE_cc0
8824 rtx new;
8825 #endif
8826 int arg_operand;
8827 const char *fmt;
8828 int i, j;
8830 switch (code)
8832 case REG:
8833 /* If we haven't already been able to do something with this BIV,
8834 we can't eliminate it. */
8835 if (x == reg)
8836 return 0;
8837 return 1;
8839 case SET:
8840 /* If this sets the BIV, it is not a problem. */
8841 if (SET_DEST (x) == reg)
8842 return 1;
8844 /* If this is an insn that defines a giv, it is also ok because
8845 it will go away when the giv is reduced. */
8846 for (v = bl->giv; v; v = v->next_iv)
8847 if (v->giv_type == DEST_REG && SET_DEST (x) == v->dest_reg)
8848 return 1;
8850 #ifdef HAVE_cc0
8851 if (SET_DEST (x) == cc0_rtx && SET_SRC (x) == reg)
8853 /* Can replace with any giv that was reduced and
8854 that has (MULT_VAL != 0) and (ADD_VAL == 0).
8855 Require a constant for MULT_VAL, so we know it's nonzero.
8856 ??? We disable this optimization to avoid potential
8857 overflows. */
8859 for (v = bl->giv; v; v = v->next_iv)
8860 if (GET_CODE (v->mult_val) == CONST_INT && v->mult_val != const0_rtx
8861 && v->add_val == const0_rtx
8862 && ! v->ignore && ! v->maybe_dead && v->always_computable
8863 && v->mode == mode
8864 && 0)
8866 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8867 continue;
8869 if (! eliminate_p)
8870 return 1;
8872 /* If the giv has the opposite direction of change,
8873 then reverse the comparison. */
8874 if (INTVAL (v->mult_val) < 0)
8875 new = gen_rtx_COMPARE (GET_MODE (v->new_reg),
8876 const0_rtx, v->new_reg);
8877 else
8878 new = v->new_reg;
8880 /* We can probably test that giv's reduced reg. */
8881 if (validate_change (insn, &SET_SRC (x), new, 0))
8882 return 1;
8885 /* Look for a giv with (MULT_VAL != 0) and (ADD_VAL != 0);
8886 replace test insn with a compare insn (cmp REDUCED_GIV ADD_VAL).
8887 Require a constant for MULT_VAL, so we know it's nonzero.
8888 ??? Do this only if ADD_VAL is a pointer to avoid a potential
8889 overflow problem. */
8891 for (v = bl->giv; v; v = v->next_iv)
8892 if (GET_CODE (v->mult_val) == CONST_INT
8893 && v->mult_val != const0_rtx
8894 && ! v->ignore && ! v->maybe_dead && v->always_computable
8895 && v->mode == mode
8896 && (GET_CODE (v->add_val) == SYMBOL_REF
8897 || GET_CODE (v->add_val) == LABEL_REF
8898 || GET_CODE (v->add_val) == CONST
8899 || (GET_CODE (v->add_val) == REG
8900 && REG_POINTER (v->add_val))))
8902 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8903 continue;
8905 if (! eliminate_p)
8906 return 1;
8908 /* If the giv has the opposite direction of change,
8909 then reverse the comparison. */
8910 if (INTVAL (v->mult_val) < 0)
8911 new = gen_rtx_COMPARE (VOIDmode, copy_rtx (v->add_val),
8912 v->new_reg);
8913 else
8914 new = gen_rtx_COMPARE (VOIDmode, v->new_reg,
8915 copy_rtx (v->add_val));
8917 /* Replace biv with the giv's reduced register. */
8918 update_reg_last_use (v->add_val, insn);
8919 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8920 return 1;
8922 /* Insn doesn't support that constant or invariant. Copy it
8923 into a register (it will be a loop invariant.) */
8924 tem = gen_reg_rtx (GET_MODE (v->new_reg));
8926 loop_insn_emit_before (loop, 0, where_insn,
8927 gen_move_insn (tem,
8928 copy_rtx (v->add_val)));
8930 /* Substitute the new register for its invariant value in
8931 the compare expression. */
8932 XEXP (new, (INTVAL (v->mult_val) < 0) ? 0 : 1) = tem;
8933 if (validate_change (insn, &SET_SRC (PATTERN (insn)), new, 0))
8934 return 1;
8937 #endif
8938 break;
8940 case COMPARE:
8941 case EQ: case NE:
8942 case GT: case GE: case GTU: case GEU:
8943 case LT: case LE: case LTU: case LEU:
8944 /* See if either argument is the biv. */
8945 if (XEXP (x, 0) == reg)
8946 arg = XEXP (x, 1), arg_operand = 1;
8947 else if (XEXP (x, 1) == reg)
8948 arg = XEXP (x, 0), arg_operand = 0;
8949 else
8950 break;
8952 if (CONSTANT_P (arg))
8954 /* First try to replace with any giv that has constant positive
8955 mult_val and constant add_val. We might be able to support
8956 negative mult_val, but it seems complex to do it in general. */
8958 for (v = bl->giv; v; v = v->next_iv)
8959 if (GET_CODE (v->mult_val) == CONST_INT
8960 && INTVAL (v->mult_val) > 0
8961 && (GET_CODE (v->add_val) == SYMBOL_REF
8962 || GET_CODE (v->add_val) == LABEL_REF
8963 || GET_CODE (v->add_val) == CONST
8964 || (GET_CODE (v->add_val) == REG
8965 && REG_POINTER (v->add_val)))
8966 && ! v->ignore && ! v->maybe_dead && v->always_computable
8967 && v->mode == mode)
8969 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
8970 continue;
8972 /* Don't eliminate if the linear combination that makes up
8973 the giv overflows when it is applied to ARG. */
8974 if (GET_CODE (arg) == CONST_INT)
8976 rtx add_val;
8978 if (GET_CODE (v->add_val) == CONST_INT)
8979 add_val = v->add_val;
8980 else
8981 add_val = const0_rtx;
8983 if (const_mult_add_overflow_p (arg, v->mult_val,
8984 add_val, mode, 1))
8985 continue;
8988 if (! eliminate_p)
8989 return 1;
8991 /* Replace biv with the giv's reduced reg. */
8992 validate_change (insn, &XEXP (x, 1 - arg_operand), v->new_reg, 1);
8994 /* If all constants are actually constant integers and
8995 the derived constant can be directly placed in the COMPARE,
8996 do so. */
8997 if (GET_CODE (arg) == CONST_INT
8998 && GET_CODE (v->add_val) == CONST_INT)
9000 tem = expand_mult_add (arg, NULL_RTX, v->mult_val,
9001 v->add_val, mode, 1);
9003 else
9005 /* Otherwise, load it into a register. */
9006 tem = gen_reg_rtx (mode);
9007 loop_iv_add_mult_emit_before (loop, arg,
9008 v->mult_val, v->add_val,
9009 tem, where_bb, where_insn);
9012 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9014 if (apply_change_group ())
9015 return 1;
9018 /* Look for giv with positive constant mult_val and nonconst add_val.
9019 Insert insns to calculate new compare value.
9020 ??? Turn this off due to possible overflow. */
9022 for (v = bl->giv; v; v = v->next_iv)
9023 if (GET_CODE (v->mult_val) == CONST_INT
9024 && INTVAL (v->mult_val) > 0
9025 && ! v->ignore && ! v->maybe_dead && v->always_computable
9026 && v->mode == mode
9027 && 0)
9029 rtx tem;
9031 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9032 continue;
9034 if (! eliminate_p)
9035 return 1;
9037 tem = gen_reg_rtx (mode);
9039 /* Replace biv with giv's reduced register. */
9040 validate_change (insn, &XEXP (x, 1 - arg_operand),
9041 v->new_reg, 1);
9043 /* Compute value to compare against. */
9044 loop_iv_add_mult_emit_before (loop, arg,
9045 v->mult_val, v->add_val,
9046 tem, where_bb, where_insn);
9047 /* Use it in this insn. */
9048 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9049 if (apply_change_group ())
9050 return 1;
9053 else if (GET_CODE (arg) == REG || GET_CODE (arg) == MEM)
9055 if (loop_invariant_p (loop, arg) == 1)
9057 /* Look for giv with constant positive mult_val and nonconst
9058 add_val. Insert insns to compute new compare value.
9059 ??? Turn this off due to possible overflow. */
9061 for (v = bl->giv; v; v = v->next_iv)
9062 if (GET_CODE (v->mult_val) == CONST_INT && INTVAL (v->mult_val) > 0
9063 && ! v->ignore && ! v->maybe_dead && v->always_computable
9064 && v->mode == mode
9065 && 0)
9067 rtx tem;
9069 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9070 continue;
9072 if (! eliminate_p)
9073 return 1;
9075 tem = gen_reg_rtx (mode);
9077 /* Replace biv with giv's reduced register. */
9078 validate_change (insn, &XEXP (x, 1 - arg_operand),
9079 v->new_reg, 1);
9081 /* Compute value to compare against. */
9082 loop_iv_add_mult_emit_before (loop, arg,
9083 v->mult_val, v->add_val,
9084 tem, where_bb, where_insn);
9085 validate_change (insn, &XEXP (x, arg_operand), tem, 1);
9086 if (apply_change_group ())
9087 return 1;
9091 /* This code has problems. Basically, you can't know when
9092 seeing if we will eliminate BL, whether a particular giv
9093 of ARG will be reduced. If it isn't going to be reduced,
9094 we can't eliminate BL. We can try forcing it to be reduced,
9095 but that can generate poor code.
9097 The problem is that the benefit of reducing TV, below should
9098 be increased if BL can actually be eliminated, but this means
9099 we might have to do a topological sort of the order in which
9100 we try to process biv. It doesn't seem worthwhile to do
9101 this sort of thing now. */
9103 #if 0
9104 /* Otherwise the reg compared with had better be a biv. */
9105 if (GET_CODE (arg) != REG
9106 || REG_IV_TYPE (ivs, REGNO (arg)) != BASIC_INDUCT)
9107 return 0;
9109 /* Look for a pair of givs, one for each biv,
9110 with identical coefficients. */
9111 for (v = bl->giv; v; v = v->next_iv)
9113 struct induction *tv;
9115 if (v->ignore || v->maybe_dead || v->mode != mode)
9116 continue;
9118 for (tv = REG_IV_CLASS (ivs, REGNO (arg))->giv; tv;
9119 tv = tv->next_iv)
9120 if (! tv->ignore && ! tv->maybe_dead
9121 && rtx_equal_p (tv->mult_val, v->mult_val)
9122 && rtx_equal_p (tv->add_val, v->add_val)
9123 && tv->mode == mode)
9125 if (! biv_elimination_giv_has_0_offset (bl->biv, v, insn))
9126 continue;
9128 if (! eliminate_p)
9129 return 1;
9131 /* Replace biv with its giv's reduced reg. */
9132 XEXP (x, 1 - arg_operand) = v->new_reg;
9133 /* Replace other operand with the other giv's
9134 reduced reg. */
9135 XEXP (x, arg_operand) = tv->new_reg;
9136 return 1;
9139 #endif
9142 /* If we get here, the biv can't be eliminated. */
9143 return 0;
9145 case MEM:
9146 /* If this address is a DEST_ADDR giv, it doesn't matter if the
9147 biv is used in it, since it will be replaced. */
9148 for (v = bl->giv; v; v = v->next_iv)
9149 if (v->giv_type == DEST_ADDR && v->location == &XEXP (x, 0))
9150 return 1;
9151 break;
9153 default:
9154 break;
9157 /* See if any subexpression fails elimination. */
9158 fmt = GET_RTX_FORMAT (code);
9159 for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
9161 switch (fmt[i])
9163 case 'e':
9164 if (! maybe_eliminate_biv_1 (loop, XEXP (x, i), insn, bl,
9165 eliminate_p, where_bb, where_insn))
9166 return 0;
9167 break;
9169 case 'E':
9170 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9171 if (! maybe_eliminate_biv_1 (loop, XVECEXP (x, i, j), insn, bl,
9172 eliminate_p, where_bb, where_insn))
9173 return 0;
9174 break;
9178 return 1;
9181 /* Return nonzero if the last use of REG
9182 is in an insn following INSN in the same basic block. */
9184 static int
9185 last_use_this_basic_block (reg, insn)
9186 rtx reg;
9187 rtx insn;
9189 rtx n;
9190 for (n = insn;
9191 n && GET_CODE (n) != CODE_LABEL && GET_CODE (n) != JUMP_INSN;
9192 n = NEXT_INSN (n))
9194 if (REGNO_LAST_UID (REGNO (reg)) == INSN_UID (n))
9195 return 1;
9197 return 0;
9200 /* Called via `note_stores' to record the initial value of a biv. Here we
9201 just record the location of the set and process it later. */
9203 static void
9204 record_initial (dest, set, data)
9205 rtx dest;
9206 rtx set;
9207 void *data ATTRIBUTE_UNUSED;
9209 struct loop_ivs *ivs = (struct loop_ivs *) data;
9210 struct iv_class *bl;
9212 if (GET_CODE (dest) != REG
9213 || REGNO (dest) >= ivs->n_regs
9214 || REG_IV_TYPE (ivs, REGNO (dest)) != BASIC_INDUCT)
9215 return;
9217 bl = REG_IV_CLASS (ivs, REGNO (dest));
9219 /* If this is the first set found, record it. */
9220 if (bl->init_insn == 0)
9222 bl->init_insn = note_insn;
9223 bl->init_set = set;
9227 /* If any of the registers in X are "old" and currently have a last use earlier
9228 than INSN, update them to have a last use of INSN. Their actual last use
9229 will be the previous insn but it will not have a valid uid_luid so we can't
9230 use it. X must be a source expression only. */
9232 static void
9233 update_reg_last_use (x, insn)
9234 rtx x;
9235 rtx insn;
9237 /* Check for the case where INSN does not have a valid luid. In this case,
9238 there is no need to modify the regno_last_uid, as this can only happen
9239 when code is inserted after the loop_end to set a pseudo's final value,
9240 and hence this insn will never be the last use of x.
9241 ???? This comment is not correct. See for example loop_givs_reduce.
9242 This may insert an insn before another new insn. */
9243 if (GET_CODE (x) == REG && REGNO (x) < max_reg_before_loop
9244 && INSN_UID (insn) < max_uid_for_loop
9245 && REGNO_LAST_LUID (REGNO (x)) < INSN_LUID (insn))
9247 REGNO_LAST_UID (REGNO (x)) = INSN_UID (insn);
9249 else
9251 int i, j;
9252 const char *fmt = GET_RTX_FORMAT (GET_CODE (x));
9253 for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9255 if (fmt[i] == 'e')
9256 update_reg_last_use (XEXP (x, i), insn);
9257 else if (fmt[i] == 'E')
9258 for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9259 update_reg_last_use (XVECEXP (x, i, j), insn);
9264 /* Given an insn INSN and condition COND, return the condition in a
9265 canonical form to simplify testing by callers. Specifically:
9267 (1) The code will always be a comparison operation (EQ, NE, GT, etc.).
9268 (2) Both operands will be machine operands; (cc0) will have been replaced.
9269 (3) If an operand is a constant, it will be the second operand.
9270 (4) (LE x const) will be replaced with (LT x <const+1>) and similarly
9271 for GE, GEU, and LEU.
9273 If the condition cannot be understood, or is an inequality floating-point
9274 comparison which needs to be reversed, 0 will be returned.
9276 If REVERSE is nonzero, then reverse the condition prior to canonizing it.
9278 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9279 insn used in locating the condition was found. If a replacement test
9280 of the condition is desired, it should be placed in front of that
9281 insn and we will be sure that the inputs are still valid.
9283 If WANT_REG is nonzero, we wish the condition to be relative to that
9284 register, if possible. Therefore, do not canonicalize the condition
9285 further. */
9288 canonicalize_condition (insn, cond, reverse, earliest, want_reg)
9289 rtx insn;
9290 rtx cond;
9291 int reverse;
9292 rtx *earliest;
9293 rtx want_reg;
9295 enum rtx_code code;
9296 rtx prev = insn;
9297 rtx set;
9298 rtx tem;
9299 rtx op0, op1;
9300 int reverse_code = 0;
9301 enum machine_mode mode;
9303 code = GET_CODE (cond);
9304 mode = GET_MODE (cond);
9305 op0 = XEXP (cond, 0);
9306 op1 = XEXP (cond, 1);
9308 if (reverse)
9309 code = reversed_comparison_code (cond, insn);
9310 if (code == UNKNOWN)
9311 return 0;
9313 if (earliest)
9314 *earliest = insn;
9316 /* If we are comparing a register with zero, see if the register is set
9317 in the previous insn to a COMPARE or a comparison operation. Perform
9318 the same tests as a function of STORE_FLAG_VALUE as find_comparison_args
9319 in cse.c */
9321 while (GET_RTX_CLASS (code) == '<'
9322 && op1 == CONST0_RTX (GET_MODE (op0))
9323 && op0 != want_reg)
9325 /* Set nonzero when we find something of interest. */
9326 rtx x = 0;
9328 #ifdef HAVE_cc0
9329 /* If comparison with cc0, import actual comparison from compare
9330 insn. */
9331 if (op0 == cc0_rtx)
9333 if ((prev = prev_nonnote_insn (prev)) == 0
9334 || GET_CODE (prev) != INSN
9335 || (set = single_set (prev)) == 0
9336 || SET_DEST (set) != cc0_rtx)
9337 return 0;
9339 op0 = SET_SRC (set);
9340 op1 = CONST0_RTX (GET_MODE (op0));
9341 if (earliest)
9342 *earliest = prev;
9344 #endif
9346 /* If this is a COMPARE, pick up the two things being compared. */
9347 if (GET_CODE (op0) == COMPARE)
9349 op1 = XEXP (op0, 1);
9350 op0 = XEXP (op0, 0);
9351 continue;
9353 else if (GET_CODE (op0) != REG)
9354 break;
9356 /* Go back to the previous insn. Stop if it is not an INSN. We also
9357 stop if it isn't a single set or if it has a REG_INC note because
9358 we don't want to bother dealing with it. */
9360 if ((prev = prev_nonnote_insn (prev)) == 0
9361 || GET_CODE (prev) != INSN
9362 || FIND_REG_INC_NOTE (prev, NULL_RTX))
9363 break;
9365 set = set_of (op0, prev);
9367 if (set
9368 && (GET_CODE (set) != SET
9369 || !rtx_equal_p (SET_DEST (set), op0)))
9370 break;
9372 /* If this is setting OP0, get what it sets it to if it looks
9373 relevant. */
9374 if (set)
9376 enum machine_mode inner_mode = GET_MODE (SET_DEST (set));
9377 #ifdef FLOAT_STORE_FLAG_VALUE
9378 REAL_VALUE_TYPE fsfv;
9379 #endif
9381 /* ??? We may not combine comparisons done in a CCmode with
9382 comparisons not done in a CCmode. This is to aid targets
9383 like Alpha that have an IEEE compliant EQ instruction, and
9384 a non-IEEE compliant BEQ instruction. The use of CCmode is
9385 actually artificial, simply to prevent the combination, but
9386 should not affect other platforms.
9388 However, we must allow VOIDmode comparisons to match either
9389 CCmode or non-CCmode comparison, because some ports have
9390 modeless comparisons inside branch patterns.
9392 ??? This mode check should perhaps look more like the mode check
9393 in simplify_comparison in combine. */
9395 if ((GET_CODE (SET_SRC (set)) == COMPARE
9396 || (((code == NE
9397 || (code == LT
9398 && GET_MODE_CLASS (inner_mode) == MODE_INT
9399 && (GET_MODE_BITSIZE (inner_mode)
9400 <= HOST_BITS_PER_WIDE_INT)
9401 && (STORE_FLAG_VALUE
9402 & ((HOST_WIDE_INT) 1
9403 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9404 #ifdef FLOAT_STORE_FLAG_VALUE
9405 || (code == LT
9406 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9407 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9408 REAL_VALUE_NEGATIVE (fsfv)))
9409 #endif
9411 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'))
9412 && (((GET_MODE_CLASS (mode) == MODE_CC)
9413 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9414 || mode == VOIDmode || inner_mode == VOIDmode))
9415 x = SET_SRC (set);
9416 else if (((code == EQ
9417 || (code == GE
9418 && (GET_MODE_BITSIZE (inner_mode)
9419 <= HOST_BITS_PER_WIDE_INT)
9420 && GET_MODE_CLASS (inner_mode) == MODE_INT
9421 && (STORE_FLAG_VALUE
9422 & ((HOST_WIDE_INT) 1
9423 << (GET_MODE_BITSIZE (inner_mode) - 1))))
9424 #ifdef FLOAT_STORE_FLAG_VALUE
9425 || (code == GE
9426 && GET_MODE_CLASS (inner_mode) == MODE_FLOAT
9427 && (fsfv = FLOAT_STORE_FLAG_VALUE (inner_mode),
9428 REAL_VALUE_NEGATIVE (fsfv)))
9429 #endif
9431 && GET_RTX_CLASS (GET_CODE (SET_SRC (set))) == '<'
9432 && (((GET_MODE_CLASS (mode) == MODE_CC)
9433 == (GET_MODE_CLASS (inner_mode) == MODE_CC))
9434 || mode == VOIDmode || inner_mode == VOIDmode))
9437 reverse_code = 1;
9438 x = SET_SRC (set);
9440 else
9441 break;
9444 else if (reg_set_p (op0, prev))
9445 /* If this sets OP0, but not directly, we have to give up. */
9446 break;
9448 if (x)
9450 if (GET_RTX_CLASS (GET_CODE (x)) == '<')
9451 code = GET_CODE (x);
9452 if (reverse_code)
9454 code = reversed_comparison_code (x, prev);
9455 if (code == UNKNOWN)
9456 return 0;
9457 reverse_code = 0;
9460 op0 = XEXP (x, 0), op1 = XEXP (x, 1);
9461 if (earliest)
9462 *earliest = prev;
9466 /* If constant is first, put it last. */
9467 if (CONSTANT_P (op0))
9468 code = swap_condition (code), tem = op0, op0 = op1, op1 = tem;
9470 /* If OP0 is the result of a comparison, we weren't able to find what
9471 was really being compared, so fail. */
9472 if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
9473 return 0;
9475 /* Canonicalize any ordered comparison with integers involving equality
9476 if we can do computations in the relevant mode and we do not
9477 overflow. */
9479 if (GET_CODE (op1) == CONST_INT
9480 && GET_MODE (op0) != VOIDmode
9481 && GET_MODE_BITSIZE (GET_MODE (op0)) <= HOST_BITS_PER_WIDE_INT)
9483 HOST_WIDE_INT const_val = INTVAL (op1);
9484 unsigned HOST_WIDE_INT uconst_val = const_val;
9485 unsigned HOST_WIDE_INT max_val
9486 = (unsigned HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (op0));
9488 switch (code)
9490 case LE:
9491 if ((unsigned HOST_WIDE_INT) const_val != max_val >> 1)
9492 code = LT, op1 = gen_int_mode (const_val + 1, GET_MODE (op0));
9493 break;
9495 /* When cross-compiling, const_val might be sign-extended from
9496 BITS_PER_WORD to HOST_BITS_PER_WIDE_INT */
9497 case GE:
9498 if ((HOST_WIDE_INT) (const_val & max_val)
9499 != (((HOST_WIDE_INT) 1
9500 << (GET_MODE_BITSIZE (GET_MODE (op0)) - 1))))
9501 code = GT, op1 = gen_int_mode (const_val - 1, GET_MODE (op0));
9502 break;
9504 case LEU:
9505 if (uconst_val < max_val)
9506 code = LTU, op1 = gen_int_mode (uconst_val + 1, GET_MODE (op0));
9507 break;
9509 case GEU:
9510 if (uconst_val != 0)
9511 code = GTU, op1 = gen_int_mode (uconst_val - 1, GET_MODE (op0));
9512 break;
9514 default:
9515 break;
9519 /* Never return CC0; return zero instead. */
9520 if (CC0_P (op0))
9521 return 0;
9523 return gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
9526 /* Given a jump insn JUMP, return the condition that will cause it to branch
9527 to its JUMP_LABEL. If the condition cannot be understood, or is an
9528 inequality floating-point comparison which needs to be reversed, 0 will
9529 be returned.
9531 If EARLIEST is nonzero, it is a pointer to a place where the earliest
9532 insn used in locating the condition was found. If a replacement test
9533 of the condition is desired, it should be placed in front of that
9534 insn and we will be sure that the inputs are still valid. */
9537 get_condition (jump, earliest)
9538 rtx jump;
9539 rtx *earliest;
9541 rtx cond;
9542 int reverse;
9543 rtx set;
9545 /* If this is not a standard conditional jump, we can't parse it. */
9546 if (GET_CODE (jump) != JUMP_INSN
9547 || ! any_condjump_p (jump))
9548 return 0;
9549 set = pc_set (jump);
9551 cond = XEXP (SET_SRC (set), 0);
9553 /* If this branches to JUMP_LABEL when the condition is false, reverse
9554 the condition. */
9555 reverse
9556 = GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
9557 && XEXP (XEXP (SET_SRC (set), 2), 0) == JUMP_LABEL (jump);
9559 return canonicalize_condition (jump, cond, reverse, earliest, NULL_RTX);
9562 /* Similar to above routine, except that we also put an invariant last
9563 unless both operands are invariants. */
9566 get_condition_for_loop (loop, x)
9567 const struct loop *loop;
9568 rtx x;
9570 rtx comparison = get_condition (x, (rtx*) 0);
9572 if (comparison == 0
9573 || ! loop_invariant_p (loop, XEXP (comparison, 0))
9574 || loop_invariant_p (loop, XEXP (comparison, 1)))
9575 return comparison;
9577 return gen_rtx_fmt_ee (swap_condition (GET_CODE (comparison)), VOIDmode,
9578 XEXP (comparison, 1), XEXP (comparison, 0));
9581 /* Scan the function and determine whether it has indirect (computed) jumps.
9583 This is taken mostly from flow.c; similar code exists elsewhere
9584 in the compiler. It may be useful to put this into rtlanal.c. */
9585 static int
9586 indirect_jump_in_function_p (start)
9587 rtx start;
9589 rtx insn;
9591 for (insn = start; insn; insn = NEXT_INSN (insn))
9592 if (computed_jump_p (insn))
9593 return 1;
9595 return 0;
9598 /* Add MEM to the LOOP_MEMS array, if appropriate. See the
9599 documentation for LOOP_MEMS for the definition of `appropriate'.
9600 This function is called from prescan_loop via for_each_rtx. */
9602 static int
9603 insert_loop_mem (mem, data)
9604 rtx *mem;
9605 void *data ATTRIBUTE_UNUSED;
9607 struct loop_info *loop_info = data;
9608 int i;
9609 rtx m = *mem;
9611 if (m == NULL_RTX)
9612 return 0;
9614 switch (GET_CODE (m))
9616 case MEM:
9617 break;
9619 case CLOBBER:
9620 /* We're not interested in MEMs that are only clobbered. */
9621 return -1;
9623 case CONST_DOUBLE:
9624 /* We're not interested in the MEM associated with a
9625 CONST_DOUBLE, so there's no need to traverse into this. */
9626 return -1;
9628 case EXPR_LIST:
9629 /* We're not interested in any MEMs that only appear in notes. */
9630 return -1;
9632 default:
9633 /* This is not a MEM. */
9634 return 0;
9637 /* See if we've already seen this MEM. */
9638 for (i = 0; i < loop_info->mems_idx; ++i)
9639 if (rtx_equal_p (m, loop_info->mems[i].mem))
9641 if (GET_MODE (m) != GET_MODE (loop_info->mems[i].mem))
9642 /* The modes of the two memory accesses are different. If
9643 this happens, something tricky is going on, and we just
9644 don't optimize accesses to this MEM. */
9645 loop_info->mems[i].optimize = 0;
9647 return 0;
9650 /* Resize the array, if necessary. */
9651 if (loop_info->mems_idx == loop_info->mems_allocated)
9653 if (loop_info->mems_allocated != 0)
9654 loop_info->mems_allocated *= 2;
9655 else
9656 loop_info->mems_allocated = 32;
9658 loop_info->mems = (loop_mem_info *)
9659 xrealloc (loop_info->mems,
9660 loop_info->mems_allocated * sizeof (loop_mem_info));
9663 /* Actually insert the MEM. */
9664 loop_info->mems[loop_info->mems_idx].mem = m;
9665 /* We can't hoist this MEM out of the loop if it's a BLKmode MEM
9666 because we can't put it in a register. We still store it in the
9667 table, though, so that if we see the same address later, but in a
9668 non-BLK mode, we'll not think we can optimize it at that point. */
9669 loop_info->mems[loop_info->mems_idx].optimize = (GET_MODE (m) != BLKmode);
9670 loop_info->mems[loop_info->mems_idx].reg = NULL_RTX;
9671 ++loop_info->mems_idx;
9673 return 0;
9677 /* Allocate REGS->ARRAY or reallocate it if it is too small.
9679 Increment REGS->ARRAY[I].SET_IN_LOOP at the index I of each
9680 register that is modified by an insn between FROM and TO. If the
9681 value of an element of REGS->array[I].SET_IN_LOOP becomes 127 or
9682 more, stop incrementing it, to avoid overflow.
9684 Store in REGS->ARRAY[I].SINGLE_USAGE the single insn in which
9685 register I is used, if it is only used once. Otherwise, it is set
9686 to 0 (for no uses) or const0_rtx for more than one use. This
9687 parameter may be zero, in which case this processing is not done.
9689 Set REGS->ARRAY[I].MAY_NOT_OPTIMIZE nonzero if we should not
9690 optimize register I. */
9692 static void
9693 loop_regs_scan (loop, extra_size)
9694 const struct loop *loop;
9695 int extra_size;
9697 struct loop_regs *regs = LOOP_REGS (loop);
9698 int old_nregs;
9699 /* last_set[n] is nonzero iff reg n has been set in the current
9700 basic block. In that case, it is the insn that last set reg n. */
9701 rtx *last_set;
9702 rtx insn;
9703 int i;
9705 old_nregs = regs->num;
9706 regs->num = max_reg_num ();
9708 /* Grow the regs array if not allocated or too small. */
9709 if (regs->num >= regs->size)
9711 regs->size = regs->num + extra_size;
9713 regs->array = (struct loop_reg *)
9714 xrealloc (regs->array, regs->size * sizeof (*regs->array));
9716 /* Zero the new elements. */
9717 memset (regs->array + old_nregs, 0,
9718 (regs->size - old_nregs) * sizeof (*regs->array));
9721 /* Clear previously scanned fields but do not clear n_times_set. */
9722 for (i = 0; i < old_nregs; i++)
9724 regs->array[i].set_in_loop = 0;
9725 regs->array[i].may_not_optimize = 0;
9726 regs->array[i].single_usage = NULL_RTX;
9729 last_set = (rtx *) xcalloc (regs->num, sizeof (rtx));
9731 /* Scan the loop, recording register usage. */
9732 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9733 insn = NEXT_INSN (insn))
9735 if (INSN_P (insn))
9737 /* Record registers that have exactly one use. */
9738 find_single_use_in_loop (regs, insn, PATTERN (insn));
9740 /* Include uses in REG_EQUAL notes. */
9741 if (REG_NOTES (insn))
9742 find_single_use_in_loop (regs, insn, REG_NOTES (insn));
9744 if (GET_CODE (PATTERN (insn)) == SET
9745 || GET_CODE (PATTERN (insn)) == CLOBBER)
9746 count_one_set (regs, insn, PATTERN (insn), last_set);
9747 else if (GET_CODE (PATTERN (insn)) == PARALLEL)
9749 int i;
9750 for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i--)
9751 count_one_set (regs, insn, XVECEXP (PATTERN (insn), 0, i),
9752 last_set);
9756 if (GET_CODE (insn) == CODE_LABEL || GET_CODE (insn) == JUMP_INSN)
9757 memset (last_set, 0, regs->num * sizeof (rtx));
9759 /* Invalidate all registers used for function argument passing.
9760 We check rtx_varies_p for the same reason as below, to allow
9761 optimizing PIC calculations. */
9762 if (GET_CODE (insn) == CALL_INSN)
9764 rtx link;
9765 for (link = CALL_INSN_FUNCTION_USAGE (insn);
9766 link;
9767 link = XEXP (link, 1))
9769 rtx op, reg;
9771 if (GET_CODE (op = XEXP (link, 0)) == USE
9772 && GET_CODE (reg = XEXP (op, 0)) == REG
9773 && rtx_varies_p (reg, 1))
9774 regs->array[REGNO (reg)].may_not_optimize = 1;
9779 /* Invalidate all hard registers clobbered by calls. With one exception:
9780 a call-clobbered PIC register is still function-invariant for our
9781 purposes, since we can hoist any PIC calculations out of the loop.
9782 Thus the call to rtx_varies_p. */
9783 if (LOOP_INFO (loop)->has_call)
9784 for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
9785 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, i)
9786 && rtx_varies_p (regno_reg_rtx[i], 1))
9788 regs->array[i].may_not_optimize = 1;
9789 regs->array[i].set_in_loop = 1;
9792 #ifdef AVOID_CCMODE_COPIES
9793 /* Don't try to move insns which set CC registers if we should not
9794 create CCmode register copies. */
9795 for (i = regs->num - 1; i >= FIRST_PSEUDO_REGISTER; i--)
9796 if (GET_MODE_CLASS (GET_MODE (regno_reg_rtx[i])) == MODE_CC)
9797 regs->array[i].may_not_optimize = 1;
9798 #endif
9800 /* Set regs->array[I].n_times_set for the new registers. */
9801 for (i = old_nregs; i < regs->num; i++)
9802 regs->array[i].n_times_set = regs->array[i].set_in_loop;
9804 free (last_set);
9807 /* Returns the number of real INSNs in the LOOP. */
9809 static int
9810 count_insns_in_loop (loop)
9811 const struct loop *loop;
9813 int count = 0;
9814 rtx insn;
9816 for (insn = loop->top ? loop->top : loop->start; insn != loop->end;
9817 insn = NEXT_INSN (insn))
9818 if (INSN_P (insn))
9819 ++count;
9821 return count;
9824 /* Move MEMs into registers for the duration of the loop. */
9826 static void
9827 load_mems (loop)
9828 const struct loop *loop;
9830 struct loop_info *loop_info = LOOP_INFO (loop);
9831 struct loop_regs *regs = LOOP_REGS (loop);
9832 int maybe_never = 0;
9833 int i;
9834 rtx p, prev_ebb_head;
9835 rtx label = NULL_RTX;
9836 rtx end_label;
9837 /* Nonzero if the next instruction may never be executed. */
9838 int next_maybe_never = 0;
9839 unsigned int last_max_reg = max_reg_num ();
9841 if (loop_info->mems_idx == 0)
9842 return;
9844 /* We cannot use next_label here because it skips over normal insns. */
9845 end_label = next_nonnote_insn (loop->end);
9846 if (end_label && GET_CODE (end_label) != CODE_LABEL)
9847 end_label = NULL_RTX;
9849 /* Check to see if it's possible that some instructions in the loop are
9850 never executed. Also check if there is a goto out of the loop other
9851 than right after the end of the loop. */
9852 for (p = next_insn_in_loop (loop, loop->scan_start);
9853 p != NULL_RTX;
9854 p = next_insn_in_loop (loop, p))
9856 if (GET_CODE (p) == CODE_LABEL)
9857 maybe_never = 1;
9858 else if (GET_CODE (p) == JUMP_INSN
9859 /* If we enter the loop in the middle, and scan
9860 around to the beginning, don't set maybe_never
9861 for that. This must be an unconditional jump,
9862 otherwise the code at the top of the loop might
9863 never be executed. Unconditional jumps are
9864 followed a by barrier then loop end. */
9865 && ! (GET_CODE (p) == JUMP_INSN
9866 && JUMP_LABEL (p) == loop->top
9867 && NEXT_INSN (NEXT_INSN (p)) == loop->end
9868 && any_uncondjump_p (p)))
9870 /* If this is a jump outside of the loop but not right
9871 after the end of the loop, we would have to emit new fixup
9872 sequences for each such label. */
9873 if (/* If we can't tell where control might go when this
9874 JUMP_INSN is executed, we must be conservative. */
9875 !JUMP_LABEL (p)
9876 || (JUMP_LABEL (p) != end_label
9877 && (INSN_UID (JUMP_LABEL (p)) >= max_uid_for_loop
9878 || INSN_LUID (JUMP_LABEL (p)) < INSN_LUID (loop->start)
9879 || INSN_LUID (JUMP_LABEL (p)) > INSN_LUID (loop->end))))
9880 return;
9882 if (!any_condjump_p (p))
9883 /* Something complicated. */
9884 maybe_never = 1;
9885 else
9886 /* If there are any more instructions in the loop, they
9887 might not be reached. */
9888 next_maybe_never = 1;
9890 else if (next_maybe_never)
9891 maybe_never = 1;
9894 /* Find start of the extended basic block that enters the loop. */
9895 for (p = loop->start;
9896 PREV_INSN (p) && GET_CODE (p) != CODE_LABEL;
9897 p = PREV_INSN (p))
9899 prev_ebb_head = p;
9901 cselib_init ();
9903 /* Build table of mems that get set to constant values before the
9904 loop. */
9905 for (; p != loop->start; p = NEXT_INSN (p))
9906 cselib_process_insn (p);
9908 /* Actually move the MEMs. */
9909 for (i = 0; i < loop_info->mems_idx; ++i)
9911 regset_head load_copies;
9912 regset_head store_copies;
9913 int written = 0;
9914 rtx reg;
9915 rtx mem = loop_info->mems[i].mem;
9916 rtx mem_list_entry;
9918 if (MEM_VOLATILE_P (mem)
9919 || loop_invariant_p (loop, XEXP (mem, 0)) != 1)
9920 /* There's no telling whether or not MEM is modified. */
9921 loop_info->mems[i].optimize = 0;
9923 /* Go through the MEMs written to in the loop to see if this
9924 one is aliased by one of them. */
9925 mem_list_entry = loop_info->store_mems;
9926 while (mem_list_entry)
9928 if (rtx_equal_p (mem, XEXP (mem_list_entry, 0)))
9929 written = 1;
9930 else if (true_dependence (XEXP (mem_list_entry, 0), VOIDmode,
9931 mem, rtx_varies_p))
9933 /* MEM is indeed aliased by this store. */
9934 loop_info->mems[i].optimize = 0;
9935 break;
9937 mem_list_entry = XEXP (mem_list_entry, 1);
9940 if (flag_float_store && written
9941 && GET_MODE_CLASS (GET_MODE (mem)) == MODE_FLOAT)
9942 loop_info->mems[i].optimize = 0;
9944 /* If this MEM is written to, we must be sure that there
9945 are no reads from another MEM that aliases this one. */
9946 if (loop_info->mems[i].optimize && written)
9948 int j;
9950 for (j = 0; j < loop_info->mems_idx; ++j)
9952 if (j == i)
9953 continue;
9954 else if (true_dependence (mem,
9955 VOIDmode,
9956 loop_info->mems[j].mem,
9957 rtx_varies_p))
9959 /* It's not safe to hoist loop_info->mems[i] out of
9960 the loop because writes to it might not be
9961 seen by reads from loop_info->mems[j]. */
9962 loop_info->mems[i].optimize = 0;
9963 break;
9968 if (maybe_never && may_trap_p (mem))
9969 /* We can't access the MEM outside the loop; it might
9970 cause a trap that wouldn't have happened otherwise. */
9971 loop_info->mems[i].optimize = 0;
9973 if (!loop_info->mems[i].optimize)
9974 /* We thought we were going to lift this MEM out of the
9975 loop, but later discovered that we could not. */
9976 continue;
9978 INIT_REG_SET (&load_copies);
9979 INIT_REG_SET (&store_copies);
9981 /* Allocate a pseudo for this MEM. We set REG_USERVAR_P in
9982 order to keep scan_loop from moving stores to this MEM
9983 out of the loop just because this REG is neither a
9984 user-variable nor used in the loop test. */
9985 reg = gen_reg_rtx (GET_MODE (mem));
9986 REG_USERVAR_P (reg) = 1;
9987 loop_info->mems[i].reg = reg;
9989 /* Now, replace all references to the MEM with the
9990 corresponding pseudos. */
9991 maybe_never = 0;
9992 for (p = next_insn_in_loop (loop, loop->scan_start);
9993 p != NULL_RTX;
9994 p = next_insn_in_loop (loop, p))
9996 if (INSN_P (p))
9998 rtx set;
10000 set = single_set (p);
10002 /* See if this copies the mem into a register that isn't
10003 modified afterwards. We'll try to do copy propagation
10004 a little further on. */
10005 if (set
10006 /* @@@ This test is _way_ too conservative. */
10007 && ! maybe_never
10008 && GET_CODE (SET_DEST (set)) == REG
10009 && REGNO (SET_DEST (set)) >= FIRST_PSEUDO_REGISTER
10010 && REGNO (SET_DEST (set)) < last_max_reg
10011 && regs->array[REGNO (SET_DEST (set))].n_times_set == 1
10012 && rtx_equal_p (SET_SRC (set), mem))
10013 SET_REGNO_REG_SET (&load_copies, REGNO (SET_DEST (set)));
10015 /* See if this copies the mem from a register that isn't
10016 modified afterwards. We'll try to remove the
10017 redundant copy later on by doing a little register
10018 renaming and copy propagation. This will help
10019 to untangle things for the BIV detection code. */
10020 if (set
10021 && ! maybe_never
10022 && GET_CODE (SET_SRC (set)) == REG
10023 && REGNO (SET_SRC (set)) >= FIRST_PSEUDO_REGISTER
10024 && REGNO (SET_SRC (set)) < last_max_reg
10025 && regs->array[REGNO (SET_SRC (set))].n_times_set == 1
10026 && rtx_equal_p (SET_DEST (set), mem))
10027 SET_REGNO_REG_SET (&store_copies, REGNO (SET_SRC (set)));
10029 /* If this is a call which uses / clobbers this memory
10030 location, we must not change the interface here. */
10031 if (GET_CODE (p) == CALL_INSN
10032 && reg_mentioned_p (loop_info->mems[i].mem,
10033 CALL_INSN_FUNCTION_USAGE (p)))
10035 cancel_changes (0);
10036 loop_info->mems[i].optimize = 0;
10037 break;
10039 else
10040 /* Replace the memory reference with the shadow register. */
10041 replace_loop_mems (p, loop_info->mems[i].mem,
10042 loop_info->mems[i].reg, written);
10045 if (GET_CODE (p) == CODE_LABEL
10046 || GET_CODE (p) == JUMP_INSN)
10047 maybe_never = 1;
10050 if (! loop_info->mems[i].optimize)
10051 ; /* We found we couldn't do the replacement, so do nothing. */
10052 else if (! apply_change_group ())
10053 /* We couldn't replace all occurrences of the MEM. */
10054 loop_info->mems[i].optimize = 0;
10055 else
10057 /* Load the memory immediately before LOOP->START, which is
10058 the NOTE_LOOP_BEG. */
10059 cselib_val *e = cselib_lookup (mem, VOIDmode, 0);
10060 rtx set;
10061 rtx best = mem;
10062 int j;
10063 struct elt_loc_list *const_equiv = 0;
10065 if (e)
10067 struct elt_loc_list *equiv;
10068 struct elt_loc_list *best_equiv = 0;
10069 for (equiv = e->locs; equiv; equiv = equiv->next)
10071 if (CONSTANT_P (equiv->loc))
10072 const_equiv = equiv;
10073 else if (GET_CODE (equiv->loc) == REG
10074 /* Extending hard register lifetimes causes crash
10075 on SRC targets. Doing so on non-SRC is
10076 probably also not good idea, since we most
10077 probably have pseudoregister equivalence as
10078 well. */
10079 && REGNO (equiv->loc) >= FIRST_PSEUDO_REGISTER)
10080 best_equiv = equiv;
10082 /* Use the constant equivalence if that is cheap enough. */
10083 if (! best_equiv)
10084 best_equiv = const_equiv;
10085 else if (const_equiv
10086 && (rtx_cost (const_equiv->loc, SET)
10087 <= rtx_cost (best_equiv->loc, SET)))
10089 best_equiv = const_equiv;
10090 const_equiv = 0;
10093 /* If best_equiv is nonzero, we know that MEM is set to a
10094 constant or register before the loop. We will use this
10095 knowledge to initialize the shadow register with that
10096 constant or reg rather than by loading from MEM. */
10097 if (best_equiv)
10098 best = copy_rtx (best_equiv->loc);
10101 set = gen_move_insn (reg, best);
10102 set = loop_insn_hoist (loop, set);
10103 if (REG_P (best))
10105 for (p = prev_ebb_head; p != loop->start; p = NEXT_INSN (p))
10106 if (REGNO_LAST_UID (REGNO (best)) == INSN_UID (p))
10108 REGNO_LAST_UID (REGNO (best)) = INSN_UID (set);
10109 break;
10113 if (const_equiv)
10114 set_unique_reg_note (set, REG_EQUAL, copy_rtx (const_equiv->loc));
10116 if (written)
10118 if (label == NULL_RTX)
10120 label = gen_label_rtx ();
10121 emit_label_after (label, loop->end);
10124 /* Store the memory immediately after END, which is
10125 the NOTE_LOOP_END. */
10126 set = gen_move_insn (copy_rtx (mem), reg);
10127 loop_insn_emit_after (loop, 0, label, set);
10130 if (loop_dump_stream)
10132 fprintf (loop_dump_stream, "Hoisted regno %d %s from ",
10133 REGNO (reg), (written ? "r/w" : "r/o"));
10134 print_rtl (loop_dump_stream, mem);
10135 fputc ('\n', loop_dump_stream);
10138 /* Attempt a bit of copy propagation. This helps untangle the
10139 data flow, and enables {basic,general}_induction_var to find
10140 more bivs/givs. */
10141 EXECUTE_IF_SET_IN_REG_SET
10142 (&load_copies, FIRST_PSEUDO_REGISTER, j,
10144 try_copy_prop (loop, reg, j);
10146 CLEAR_REG_SET (&load_copies);
10148 EXECUTE_IF_SET_IN_REG_SET
10149 (&store_copies, FIRST_PSEUDO_REGISTER, j,
10151 try_swap_copy_prop (loop, reg, j);
10153 CLEAR_REG_SET (&store_copies);
10157 if (label != NULL_RTX && end_label != NULL_RTX)
10159 /* Now, we need to replace all references to the previous exit
10160 label with the new one. */
10161 replace_label_data rr;
10162 rr.r1 = end_label;
10163 rr.r2 = label;
10164 rr.update_label_nuses = true;
10166 for (p = loop->start; p != loop->end; p = NEXT_INSN (p))
10168 for_each_rtx (&p, replace_label, &rr);
10172 cselib_finish ();
10175 /* For communication between note_reg_stored and its caller. */
10176 struct note_reg_stored_arg
10178 int set_seen;
10179 rtx reg;
10182 /* Called via note_stores, record in SET_SEEN whether X, which is written,
10183 is equal to ARG. */
10184 static void
10185 note_reg_stored (x, setter, arg)
10186 rtx x, setter ATTRIBUTE_UNUSED;
10187 void *arg;
10189 struct note_reg_stored_arg *t = (struct note_reg_stored_arg *) arg;
10190 if (t->reg == x)
10191 t->set_seen = 1;
10194 /* Try to replace every occurrence of pseudo REGNO with REPLACEMENT.
10195 There must be exactly one insn that sets this pseudo; it will be
10196 deleted if all replacements succeed and we can prove that the register
10197 is not used after the loop. */
10199 static void
10200 try_copy_prop (loop, replacement, regno)
10201 const struct loop *loop;
10202 rtx replacement;
10203 unsigned int regno;
10205 /* This is the reg that we are copying from. */
10206 rtx reg_rtx = regno_reg_rtx[regno];
10207 rtx init_insn = 0;
10208 rtx insn;
10209 /* These help keep track of whether we replaced all uses of the reg. */
10210 int replaced_last = 0;
10211 int store_is_first = 0;
10213 for (insn = next_insn_in_loop (loop, loop->scan_start);
10214 insn != NULL_RTX;
10215 insn = next_insn_in_loop (loop, insn))
10217 rtx set;
10219 /* Only substitute within one extended basic block from the initializing
10220 insn. */
10221 if (GET_CODE (insn) == CODE_LABEL && init_insn)
10222 break;
10224 if (! INSN_P (insn))
10225 continue;
10227 /* Is this the initializing insn? */
10228 set = single_set (insn);
10229 if (set
10230 && GET_CODE (SET_DEST (set)) == REG
10231 && REGNO (SET_DEST (set)) == regno)
10233 if (init_insn)
10234 abort ();
10236 init_insn = insn;
10237 if (REGNO_FIRST_UID (regno) == INSN_UID (insn))
10238 store_is_first = 1;
10241 /* Only substitute after seeing the initializing insn. */
10242 if (init_insn && insn != init_insn)
10244 struct note_reg_stored_arg arg;
10246 replace_loop_regs (insn, reg_rtx, replacement);
10247 if (REGNO_LAST_UID (regno) == INSN_UID (insn))
10248 replaced_last = 1;
10250 /* Stop replacing when REPLACEMENT is modified. */
10251 arg.reg = replacement;
10252 arg.set_seen = 0;
10253 note_stores (PATTERN (insn), note_reg_stored, &arg);
10254 if (arg.set_seen)
10256 rtx note = find_reg_note (insn, REG_EQUAL, NULL);
10258 /* It is possible that we've turned previously valid REG_EQUAL to
10259 invalid, as we change the REGNO to REPLACEMENT and unlike REGNO,
10260 REPLACEMENT is modified, we get different meaning. */
10261 if (note && reg_mentioned_p (replacement, XEXP (note, 0)))
10262 remove_note (insn, note);
10263 break;
10267 if (! init_insn)
10268 abort ();
10269 if (apply_change_group ())
10271 if (loop_dump_stream)
10272 fprintf (loop_dump_stream, " Replaced reg %d", regno);
10273 if (store_is_first && replaced_last)
10275 rtx first;
10276 rtx retval_note;
10278 /* Assume we're just deleting INIT_INSN. */
10279 first = init_insn;
10280 /* Look for REG_RETVAL note. If we're deleting the end of
10281 the libcall sequence, the whole sequence can go. */
10282 retval_note = find_reg_note (init_insn, REG_RETVAL, NULL_RTX);
10283 /* If we found a REG_RETVAL note, find the first instruction
10284 in the sequence. */
10285 if (retval_note)
10286 first = XEXP (retval_note, 0);
10288 /* Delete the instructions. */
10289 loop_delete_insns (first, init_insn);
10291 if (loop_dump_stream)
10292 fprintf (loop_dump_stream, ".\n");
10296 /* Replace all the instructions from FIRST up to and including LAST
10297 with NOTE_INSN_DELETED notes. */
10299 static void
10300 loop_delete_insns (first, last)
10301 rtx first;
10302 rtx last;
10304 while (1)
10306 if (loop_dump_stream)
10307 fprintf (loop_dump_stream, ", deleting init_insn (%d)",
10308 INSN_UID (first));
10309 delete_insn (first);
10311 /* If this was the LAST instructions we're supposed to delete,
10312 we're done. */
10313 if (first == last)
10314 break;
10316 first = NEXT_INSN (first);
10320 /* Try to replace occurrences of pseudo REGNO with REPLACEMENT within
10321 loop LOOP if the order of the sets of these registers can be
10322 swapped. There must be exactly one insn within the loop that sets
10323 this pseudo followed immediately by a move insn that sets
10324 REPLACEMENT with REGNO. */
10325 static void
10326 try_swap_copy_prop (loop, replacement, regno)
10327 const struct loop *loop;
10328 rtx replacement;
10329 unsigned int regno;
10331 rtx insn;
10332 rtx set = NULL_RTX;
10333 unsigned int new_regno;
10335 new_regno = REGNO (replacement);
10337 for (insn = next_insn_in_loop (loop, loop->scan_start);
10338 insn != NULL_RTX;
10339 insn = next_insn_in_loop (loop, insn))
10341 /* Search for the insn that copies REGNO to NEW_REGNO? */
10342 if (INSN_P (insn)
10343 && (set = single_set (insn))
10344 && GET_CODE (SET_DEST (set)) == REG
10345 && REGNO (SET_DEST (set)) == new_regno
10346 && GET_CODE (SET_SRC (set)) == REG
10347 && REGNO (SET_SRC (set)) == regno)
10348 break;
10351 if (insn != NULL_RTX)
10353 rtx prev_insn;
10354 rtx prev_set;
10356 /* Some DEF-USE info would come in handy here to make this
10357 function more general. For now, just check the previous insn
10358 which is the most likely candidate for setting REGNO. */
10360 prev_insn = PREV_INSN (insn);
10362 if (INSN_P (insn)
10363 && (prev_set = single_set (prev_insn))
10364 && GET_CODE (SET_DEST (prev_set)) == REG
10365 && REGNO (SET_DEST (prev_set)) == regno)
10367 /* We have:
10368 (set (reg regno) (expr))
10369 (set (reg new_regno) (reg regno))
10371 so try converting this to:
10372 (set (reg new_regno) (expr))
10373 (set (reg regno) (reg new_regno))
10375 The former construct is often generated when a global
10376 variable used for an induction variable is shadowed by a
10377 register (NEW_REGNO). The latter construct improves the
10378 chances of GIV replacement and BIV elimination. */
10380 validate_change (prev_insn, &SET_DEST (prev_set),
10381 replacement, 1);
10382 validate_change (insn, &SET_DEST (set),
10383 SET_SRC (set), 1);
10384 validate_change (insn, &SET_SRC (set),
10385 replacement, 1);
10387 if (apply_change_group ())
10389 if (loop_dump_stream)
10390 fprintf (loop_dump_stream,
10391 " Swapped set of reg %d at %d with reg %d at %d.\n",
10392 regno, INSN_UID (insn),
10393 new_regno, INSN_UID (prev_insn));
10395 /* Update first use of REGNO. */
10396 if (REGNO_FIRST_UID (regno) == INSN_UID (prev_insn))
10397 REGNO_FIRST_UID (regno) = INSN_UID (insn);
10399 /* Now perform copy propagation to hopefully
10400 remove all uses of REGNO within the loop. */
10401 try_copy_prop (loop, replacement, regno);
10407 /* Worker function for find_mem_in_note, called via for_each_rtx. */
10409 static int
10410 find_mem_in_note_1 (x, data)
10411 rtx *x;
10412 void *data;
10414 if (*x != NULL_RTX && GET_CODE (*x) == MEM)
10416 rtx *res = (rtx *) data;
10417 *res = *x;
10418 return 1;
10420 return 0;
10423 /* Returns the first MEM found in NOTE by depth-first search. */
10425 static rtx
10426 find_mem_in_note (note)
10427 rtx note;
10429 if (note && for_each_rtx (&note, find_mem_in_note_1, &note))
10430 return note;
10431 return NULL_RTX;
10434 /* Replace MEM with its associated pseudo register. This function is
10435 called from load_mems via for_each_rtx. DATA is actually a pointer
10436 to a structure describing the instruction currently being scanned
10437 and the MEM we are currently replacing. */
10439 static int
10440 replace_loop_mem (mem, data)
10441 rtx *mem;
10442 void *data;
10444 loop_replace_args *args = (loop_replace_args *) data;
10445 rtx m = *mem;
10447 if (m == NULL_RTX)
10448 return 0;
10450 switch (GET_CODE (m))
10452 case MEM:
10453 break;
10455 case CONST_DOUBLE:
10456 /* We're not interested in the MEM associated with a
10457 CONST_DOUBLE, so there's no need to traverse into one. */
10458 return -1;
10460 default:
10461 /* This is not a MEM. */
10462 return 0;
10465 if (!rtx_equal_p (args->match, m))
10466 /* This is not the MEM we are currently replacing. */
10467 return 0;
10469 /* Actually replace the MEM. */
10470 validate_change (args->insn, mem, args->replacement, 1);
10472 return 0;
10475 static void
10476 replace_loop_mems (insn, mem, reg, written)
10477 rtx insn;
10478 rtx mem;
10479 rtx reg;
10480 int written;
10482 loop_replace_args args;
10484 args.insn = insn;
10485 args.match = mem;
10486 args.replacement = reg;
10488 for_each_rtx (&insn, replace_loop_mem, &args);
10490 /* If we hoist a mem write out of the loop, then REG_EQUAL
10491 notes referring to the mem are no longer valid. */
10492 if (written)
10494 rtx note, sub;
10495 rtx *link;
10497 for (link = &REG_NOTES (insn); (note = *link); link = &XEXP (note, 1))
10499 if (REG_NOTE_KIND (note) == REG_EQUAL
10500 && (sub = find_mem_in_note (note))
10501 && true_dependence (mem, VOIDmode, sub, rtx_varies_p))
10503 /* Remove the note. */
10504 validate_change (NULL_RTX, link, XEXP (note, 1), 1);
10505 break;
10511 /* Replace one register with another. Called through for_each_rtx; PX points
10512 to the rtx being scanned. DATA is actually a pointer to
10513 a structure of arguments. */
10515 static int
10516 replace_loop_reg (px, data)
10517 rtx *px;
10518 void *data;
10520 rtx x = *px;
10521 loop_replace_args *args = (loop_replace_args *) data;
10523 if (x == NULL_RTX)
10524 return 0;
10526 if (x == args->match)
10527 validate_change (args->insn, px, args->replacement, 1);
10529 return 0;
10532 static void
10533 replace_loop_regs (insn, reg, replacement)
10534 rtx insn;
10535 rtx reg;
10536 rtx replacement;
10538 loop_replace_args args;
10540 args.insn = insn;
10541 args.match = reg;
10542 args.replacement = replacement;
10544 for_each_rtx (&insn, replace_loop_reg, &args);
10547 /* Emit insn for PATTERN after WHERE_INSN in basic block WHERE_BB
10548 (ignored in the interim). */
10550 static rtx
10551 loop_insn_emit_after (loop, where_bb, where_insn, pattern)
10552 const struct loop *loop ATTRIBUTE_UNUSED;
10553 basic_block where_bb ATTRIBUTE_UNUSED;
10554 rtx where_insn;
10555 rtx pattern;
10557 return emit_insn_after (pattern, where_insn);
10561 /* If WHERE_INSN is nonzero emit insn for PATTERN before WHERE_INSN
10562 in basic block WHERE_BB (ignored in the interim) within the loop
10563 otherwise hoist PATTERN into the loop pre-header. */
10566 loop_insn_emit_before (loop, where_bb, where_insn, pattern)
10567 const struct loop *loop;
10568 basic_block where_bb ATTRIBUTE_UNUSED;
10569 rtx where_insn;
10570 rtx pattern;
10572 if (! where_insn)
10573 return loop_insn_hoist (loop, pattern);
10574 return emit_insn_before (pattern, where_insn);
10578 /* Emit call insn for PATTERN before WHERE_INSN in basic block
10579 WHERE_BB (ignored in the interim) within the loop. */
10581 static rtx
10582 loop_call_insn_emit_before (loop, where_bb, where_insn, pattern)
10583 const struct loop *loop ATTRIBUTE_UNUSED;
10584 basic_block where_bb ATTRIBUTE_UNUSED;
10585 rtx where_insn;
10586 rtx pattern;
10588 return emit_call_insn_before (pattern, where_insn);
10592 /* Hoist insn for PATTERN into the loop pre-header. */
10595 loop_insn_hoist (loop, pattern)
10596 const struct loop *loop;
10597 rtx pattern;
10599 return loop_insn_emit_before (loop, 0, loop->start, pattern);
10603 /* Hoist call insn for PATTERN into the loop pre-header. */
10605 static rtx
10606 loop_call_insn_hoist (loop, pattern)
10607 const struct loop *loop;
10608 rtx pattern;
10610 return loop_call_insn_emit_before (loop, 0, loop->start, pattern);
10614 /* Sink insn for PATTERN after the loop end. */
10617 loop_insn_sink (loop, pattern)
10618 const struct loop *loop;
10619 rtx pattern;
10621 return loop_insn_emit_before (loop, 0, loop->sink, pattern);
10624 /* bl->final_value can be eighter general_operand or PLUS of general_operand
10625 and constant. Emit sequence of instructions to load it into REG. */
10626 static rtx
10627 gen_load_of_final_value (reg, final_value)
10628 rtx reg, final_value;
10630 rtx seq;
10631 start_sequence ();
10632 final_value = force_operand (final_value, reg);
10633 if (final_value != reg)
10634 emit_move_insn (reg, final_value);
10635 seq = get_insns ();
10636 end_sequence ();
10637 return seq;
10640 /* If the loop has multiple exits, emit insn for PATTERN before the
10641 loop to ensure that it will always be executed no matter how the
10642 loop exits. Otherwise, emit the insn for PATTERN after the loop,
10643 since this is slightly more efficient. */
10645 static rtx
10646 loop_insn_sink_or_swim (loop, pattern)
10647 const struct loop *loop;
10648 rtx pattern;
10650 if (loop->exit_count)
10651 return loop_insn_hoist (loop, pattern);
10652 else
10653 return loop_insn_sink (loop, pattern);
10656 static void
10657 loop_ivs_dump (loop, file, verbose)
10658 const struct loop *loop;
10659 FILE *file;
10660 int verbose;
10662 struct iv_class *bl;
10663 int iv_num = 0;
10665 if (! loop || ! file)
10666 return;
10668 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10669 iv_num++;
10671 fprintf (file, "Loop %d: %d IV classes\n", loop->num, iv_num);
10673 for (bl = LOOP_IVS (loop)->list; bl; bl = bl->next)
10675 loop_iv_class_dump (bl, file, verbose);
10676 fputc ('\n', file);
10681 static void
10682 loop_iv_class_dump (bl, file, verbose)
10683 const struct iv_class *bl;
10684 FILE *file;
10685 int verbose ATTRIBUTE_UNUSED;
10687 struct induction *v;
10688 rtx incr;
10689 int i;
10691 if (! bl || ! file)
10692 return;
10694 fprintf (file, "IV class for reg %d, benefit %d\n",
10695 bl->regno, bl->total_benefit);
10697 fprintf (file, " Init insn %d", INSN_UID (bl->init_insn));
10698 if (bl->initial_value)
10700 fprintf (file, ", init val: ");
10701 print_simple_rtl (file, bl->initial_value);
10703 if (bl->initial_test)
10705 fprintf (file, ", init test: ");
10706 print_simple_rtl (file, bl->initial_test);
10708 fputc ('\n', file);
10710 if (bl->final_value)
10712 fprintf (file, " Final val: ");
10713 print_simple_rtl (file, bl->final_value);
10714 fputc ('\n', file);
10717 if ((incr = biv_total_increment (bl)))
10719 fprintf (file, " Total increment: ");
10720 print_simple_rtl (file, incr);
10721 fputc ('\n', file);
10724 /* List the increments. */
10725 for (i = 0, v = bl->biv; v; v = v->next_iv, i++)
10727 fprintf (file, " Inc%d: insn %d, incr: ", i, INSN_UID (v->insn));
10728 print_simple_rtl (file, v->add_val);
10729 fputc ('\n', file);
10732 /* List the givs. */
10733 for (i = 0, v = bl->giv; v; v = v->next_iv, i++)
10735 fprintf (file, " Giv%d: insn %d, benefit %d, ",
10736 i, INSN_UID (v->insn), v->benefit);
10737 if (v->giv_type == DEST_ADDR)
10738 print_simple_rtl (file, v->mem);
10739 else
10740 print_simple_rtl (file, single_set (v->insn));
10741 fputc ('\n', file);
10746 static void
10747 loop_biv_dump (v, file, verbose)
10748 const struct induction *v;
10749 FILE *file;
10750 int verbose;
10752 if (! v || ! file)
10753 return;
10755 fprintf (file,
10756 "Biv %d: insn %d",
10757 REGNO (v->dest_reg), INSN_UID (v->insn));
10758 fprintf (file, " const ");
10759 print_simple_rtl (file, v->add_val);
10761 if (verbose && v->final_value)
10763 fputc ('\n', file);
10764 fprintf (file, " final ");
10765 print_simple_rtl (file, v->final_value);
10768 fputc ('\n', file);
10772 static void
10773 loop_giv_dump (v, file, verbose)
10774 const struct induction *v;
10775 FILE *file;
10776 int verbose;
10778 if (! v || ! file)
10779 return;
10781 if (v->giv_type == DEST_REG)
10782 fprintf (file, "Giv %d: insn %d",
10783 REGNO (v->dest_reg), INSN_UID (v->insn));
10784 else
10785 fprintf (file, "Dest address: insn %d",
10786 INSN_UID (v->insn));
10788 fprintf (file, " src reg %d benefit %d",
10789 REGNO (v->src_reg), v->benefit);
10790 fprintf (file, " lifetime %d",
10791 v->lifetime);
10793 if (v->replaceable)
10794 fprintf (file, " replaceable");
10796 if (v->no_const_addval)
10797 fprintf (file, " ncav");
10799 if (v->ext_dependent)
10801 switch (GET_CODE (v->ext_dependent))
10803 case SIGN_EXTEND:
10804 fprintf (file, " ext se");
10805 break;
10806 case ZERO_EXTEND:
10807 fprintf (file, " ext ze");
10808 break;
10809 case TRUNCATE:
10810 fprintf (file, " ext tr");
10811 break;
10812 default:
10813 abort ();
10817 fputc ('\n', file);
10818 fprintf (file, " mult ");
10819 print_simple_rtl (file, v->mult_val);
10821 fputc ('\n', file);
10822 fprintf (file, " add ");
10823 print_simple_rtl (file, v->add_val);
10825 if (verbose && v->final_value)
10827 fputc ('\n', file);
10828 fprintf (file, " final ");
10829 print_simple_rtl (file, v->final_value);
10832 fputc ('\n', file);
10836 void
10837 debug_ivs (loop)
10838 const struct loop *loop;
10840 loop_ivs_dump (loop, stderr, 1);
10844 void
10845 debug_iv_class (bl)
10846 const struct iv_class *bl;
10848 loop_iv_class_dump (bl, stderr, 1);
10852 void
10853 debug_biv (v)
10854 const struct induction *v;
10856 loop_biv_dump (v, stderr, 1);
10860 void
10861 debug_giv (v)
10862 const struct induction *v;
10864 loop_giv_dump (v, stderr, 1);
10868 #define LOOP_BLOCK_NUM_1(INSN) \
10869 ((INSN) ? (BLOCK_FOR_INSN (INSN) ? BLOCK_NUM (INSN) : - 1) : -1)
10871 /* The notes do not have an assigned block, so look at the next insn. */
10872 #define LOOP_BLOCK_NUM(INSN) \
10873 ((INSN) ? (GET_CODE (INSN) == NOTE \
10874 ? LOOP_BLOCK_NUM_1 (next_nonnote_insn (INSN)) \
10875 : LOOP_BLOCK_NUM_1 (INSN)) \
10876 : -1)
10878 #define LOOP_INSN_UID(INSN) ((INSN) ? INSN_UID (INSN) : -1)
10880 static void
10881 loop_dump_aux (loop, file, verbose)
10882 const struct loop *loop;
10883 FILE *file;
10884 int verbose ATTRIBUTE_UNUSED;
10886 rtx label;
10888 if (! loop || ! file)
10889 return;
10891 /* Print diagnostics to compare our concept of a loop with
10892 what the loop notes say. */
10893 if (! PREV_INSN (loop->first->head)
10894 || GET_CODE (PREV_INSN (loop->first->head)) != NOTE
10895 || NOTE_LINE_NUMBER (PREV_INSN (loop->first->head))
10896 != NOTE_INSN_LOOP_BEG)
10897 fprintf (file, ";; No NOTE_INSN_LOOP_BEG at %d\n",
10898 INSN_UID (PREV_INSN (loop->first->head)));
10899 if (! NEXT_INSN (loop->last->end)
10900 || GET_CODE (NEXT_INSN (loop->last->end)) != NOTE
10901 || NOTE_LINE_NUMBER (NEXT_INSN (loop->last->end))
10902 != NOTE_INSN_LOOP_END)
10903 fprintf (file, ";; No NOTE_INSN_LOOP_END at %d\n",
10904 INSN_UID (NEXT_INSN (loop->last->end)));
10906 if (loop->start)
10908 fprintf (file,
10909 ";; start %d (%d), cont dom %d (%d), cont %d (%d), vtop %d (%d), end %d (%d)\n",
10910 LOOP_BLOCK_NUM (loop->start),
10911 LOOP_INSN_UID (loop->start),
10912 LOOP_BLOCK_NUM (loop->cont),
10913 LOOP_INSN_UID (loop->cont),
10914 LOOP_BLOCK_NUM (loop->cont),
10915 LOOP_INSN_UID (loop->cont),
10916 LOOP_BLOCK_NUM (loop->vtop),
10917 LOOP_INSN_UID (loop->vtop),
10918 LOOP_BLOCK_NUM (loop->end),
10919 LOOP_INSN_UID (loop->end));
10920 fprintf (file, ";; top %d (%d), scan start %d (%d)\n",
10921 LOOP_BLOCK_NUM (loop->top),
10922 LOOP_INSN_UID (loop->top),
10923 LOOP_BLOCK_NUM (loop->scan_start),
10924 LOOP_INSN_UID (loop->scan_start));
10925 fprintf (file, ";; exit_count %d", loop->exit_count);
10926 if (loop->exit_count)
10928 fputs (", labels:", file);
10929 for (label = loop->exit_labels; label; label = LABEL_NEXTREF (label))
10931 fprintf (file, " %d ",
10932 LOOP_INSN_UID (XEXP (label, 0)));
10935 fputs ("\n", file);
10937 /* This can happen when a marked loop appears as two nested loops,
10938 say from while (a || b) {}. The inner loop won't match
10939 the loop markers but the outer one will. */
10940 if (LOOP_BLOCK_NUM (loop->cont) != loop->latch->index)
10941 fprintf (file, ";; NOTE_INSN_LOOP_CONT not in loop latch\n");
10945 /* Call this function from the debugger to dump LOOP. */
10947 void
10948 debug_loop (loop)
10949 const struct loop *loop;
10951 flow_loop_dump (loop, stderr, loop_dump_aux, 1);
10954 /* Call this function from the debugger to dump LOOPS. */
10956 void
10957 debug_loops (loops)
10958 const struct loops *loops;
10960 flow_loops_dump (loops, stderr, loop_dump_aux, 1);