coretypes.h: Include hash-table.h and hash-set.h for host files.
[gcc.git] / gcc / tree-ssa-loop-prefetch.c
1 /* Array prefetching.
2 Copyright (C) 2005-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "input.h"
25 #include "alias.h"
26 #include "symtab.h"
27 #include "tree.h"
28 #include "fold-const.h"
29 #include "stor-layout.h"
30 #include "tm_p.h"
31 #include "predict.h"
32 #include "hard-reg-set.h"
33 #include "function.h"
34 #include "dominance.h"
35 #include "cfg.h"
36 #include "basic-block.h"
37 #include "tree-pretty-print.h"
38 #include "tree-ssa-alias.h"
39 #include "internal-fn.h"
40 #include "gimple-expr.h"
41 #include "is-a.h"
42 #include "gimple.h"
43 #include "gimplify.h"
44 #include "gimple-iterator.h"
45 #include "gimplify-me.h"
46 #include "gimple-ssa.h"
47 #include "tree-ssa-loop-ivopts.h"
48 #include "tree-ssa-loop-manip.h"
49 #include "tree-ssa-loop-niter.h"
50 #include "tree-ssa-loop.h"
51 #include "tree-into-ssa.h"
52 #include "cfgloop.h"
53 #include "tree-pass.h"
54 #include "insn-config.h"
55 #include "tree-chrec.h"
56 #include "tree-scalar-evolution.h"
57 #include "diagnostic-core.h"
58 #include "params.h"
59 #include "langhooks.h"
60 #include "tree-inline.h"
61 #include "tree-data-ref.h"
62
63
64 /* FIXME: Needed for optabs, but this should all be moved to a TBD interface
65 between the GIMPLE and RTL worlds. */
66 #include "rtl.h"
67 #include "flags.h"
68 #include "expmed.h"
69 #include "dojump.h"
70 #include "explow.h"
71 #include "calls.h"
72 #include "emit-rtl.h"
73 #include "varasm.h"
74 #include "stmt.h"
75 #include "expr.h"
76 #include "insn-codes.h"
77 #include "optabs.h"
78 #include "recog.h"
79
80 /* This pass inserts prefetch instructions to optimize cache usage during
81 accesses to arrays in loops. It processes loops sequentially and:
82
83 1) Gathers all memory references in the single loop.
84 2) For each of the references it decides when it is profitable to prefetch
85 it. To do it, we evaluate the reuse among the accesses, and determines
86 two values: PREFETCH_BEFORE (meaning that it only makes sense to do
87 prefetching in the first PREFETCH_BEFORE iterations of the loop) and
88 PREFETCH_MOD (meaning that it only makes sense to prefetch in the
89 iterations of the loop that are zero modulo PREFETCH_MOD). For example
90 (assuming cache line size is 64 bytes, char has size 1 byte and there
91 is no hardware sequential prefetch):
92
93 char *a;
94 for (i = 0; i < max; i++)
95 {
96 a[255] = ...; (0)
97 a[i] = ...; (1)
98 a[i + 64] = ...; (2)
99 a[16*i] = ...; (3)
100 a[187*i] = ...; (4)
101 a[187*i + 50] = ...; (5)
102 }
103
104 (0) obviously has PREFETCH_BEFORE 1
105 (1) has PREFETCH_BEFORE 64, since (2) accesses the same memory
106 location 64 iterations before it, and PREFETCH_MOD 64 (since
107 it hits the same cache line otherwise).
108 (2) has PREFETCH_MOD 64
109 (3) has PREFETCH_MOD 4
110 (4) has PREFETCH_MOD 1. We do not set PREFETCH_BEFORE here, since
111 the cache line accessed by (5) is the same with probability only
112 7/32.
113 (5) has PREFETCH_MOD 1 as well.
114
115 Additionally, we use data dependence analysis to determine for each
116 reference the distance till the first reuse; this information is used
117 to determine the temporality of the issued prefetch instruction.
118
119 3) We determine how much ahead we need to prefetch. The number of
120 iterations needed is time to fetch / time spent in one iteration of
121 the loop. The problem is that we do not know either of these values,
122 so we just make a heuristic guess based on a magic (possibly)
123 target-specific constant and size of the loop.
124
125 4) Determine which of the references we prefetch. We take into account
126 that there is a maximum number of simultaneous prefetches (provided
127 by machine description). We prefetch as many prefetches as possible
128 while still within this bound (starting with those with lowest
129 prefetch_mod, since they are responsible for most of the cache
130 misses).
131
132 5) We unroll and peel loops so that we are able to satisfy PREFETCH_MOD
133 and PREFETCH_BEFORE requirements (within some bounds), and to avoid
134 prefetching nonaccessed memory.
135 TODO -- actually implement peeling.
136
137 6) We actually emit the prefetch instructions. ??? Perhaps emit the
138 prefetch instructions with guards in cases where 5) was not sufficient
139 to satisfy the constraints?
140
141 A cost model is implemented to determine whether or not prefetching is
142 profitable for a given loop. The cost model has three heuristics:
143
144 1. Function trip_count_to_ahead_ratio_too_small_p implements a
145 heuristic that determines whether or not the loop has too few
146 iterations (compared to ahead). Prefetching is not likely to be
147 beneficial if the trip count to ahead ratio is below a certain
148 minimum.
149
150 2. Function mem_ref_count_reasonable_p implements a heuristic that
151 determines whether the given loop has enough CPU ops that can be
152 overlapped with cache missing memory ops. If not, the loop
153 won't benefit from prefetching. In the implementation,
154 prefetching is not considered beneficial if the ratio between
155 the instruction count and the mem ref count is below a certain
156 minimum.
157
158 3. Function insn_to_prefetch_ratio_too_small_p implements a
159 heuristic that disables prefetching in a loop if the prefetching
160 cost is above a certain limit. The relative prefetching cost is
161 estimated by taking the ratio between the prefetch count and the
162 total intruction count (this models the I-cache cost).
163
164 The limits used in these heuristics are defined as parameters with
165 reasonable default values. Machine-specific default values will be
166 added later.
167
168 Some other TODO:
169 -- write and use more general reuse analysis (that could be also used
170 in other cache aimed loop optimizations)
171 -- make it behave sanely together with the prefetches given by user
172 (now we just ignore them; at the very least we should avoid
173 optimizing loops in that user put his own prefetches)
174 -- we assume cache line size alignment of arrays; this could be
175 improved. */
176
177 /* Magic constants follow. These should be replaced by machine specific
178 numbers. */
179
180 /* True if write can be prefetched by a read prefetch. */
181
182 #ifndef WRITE_CAN_USE_READ_PREFETCH
183 #define WRITE_CAN_USE_READ_PREFETCH 1
184 #endif
185
186 /* True if read can be prefetched by a write prefetch. */
187
188 #ifndef READ_CAN_USE_WRITE_PREFETCH
189 #define READ_CAN_USE_WRITE_PREFETCH 0
190 #endif
191
192 /* The size of the block loaded by a single prefetch. Usually, this is
193 the same as cache line size (at the moment, we only consider one level
194 of cache hierarchy). */
195
196 #ifndef PREFETCH_BLOCK
197 #define PREFETCH_BLOCK L1_CACHE_LINE_SIZE
198 #endif
199
200 /* Do we have a forward hardware sequential prefetching? */
201
202 #ifndef HAVE_FORWARD_PREFETCH
203 #define HAVE_FORWARD_PREFETCH 0
204 #endif
205
206 /* Do we have a backward hardware sequential prefetching? */
207
208 #ifndef HAVE_BACKWARD_PREFETCH
209 #define HAVE_BACKWARD_PREFETCH 0
210 #endif
211
212 /* In some cases we are only able to determine that there is a certain
213 probability that the two accesses hit the same cache line. In this
214 case, we issue the prefetches for both of them if this probability
215 is less then (1000 - ACCEPTABLE_MISS_RATE) per thousand. */
216
217 #ifndef ACCEPTABLE_MISS_RATE
218 #define ACCEPTABLE_MISS_RATE 50
219 #endif
220
221 #ifndef HAVE_prefetch
222 #define HAVE_prefetch 0
223 #endif
224
225 #define L1_CACHE_SIZE_BYTES ((unsigned) (L1_CACHE_SIZE * 1024))
226 #define L2_CACHE_SIZE_BYTES ((unsigned) (L2_CACHE_SIZE * 1024))
227
228 /* We consider a memory access nontemporal if it is not reused sooner than
229 after L2_CACHE_SIZE_BYTES of memory are accessed. However, we ignore
230 accesses closer than L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
231 so that we use nontemporal prefetches e.g. if single memory location
232 is accessed several times in a single iteration of the loop. */
233 #define NONTEMPORAL_FRACTION 16
234
235 /* In case we have to emit a memory fence instruction after the loop that
236 uses nontemporal stores, this defines the builtin to use. */
237
238 #ifndef FENCE_FOLLOWING_MOVNT
239 #define FENCE_FOLLOWING_MOVNT NULL_TREE
240 #endif
241
242 /* It is not profitable to prefetch when the trip count is not at
243 least TRIP_COUNT_TO_AHEAD_RATIO times the prefetch ahead distance.
244 For example, in a loop with a prefetch ahead distance of 10,
245 supposing that TRIP_COUNT_TO_AHEAD_RATIO is equal to 4, it is
246 profitable to prefetch when the trip count is greater or equal to
247 40. In that case, 30 out of the 40 iterations will benefit from
248 prefetching. */
249
250 #ifndef TRIP_COUNT_TO_AHEAD_RATIO
251 #define TRIP_COUNT_TO_AHEAD_RATIO 4
252 #endif
253
254 /* The group of references between that reuse may occur. */
255
256 struct mem_ref_group
257 {
258 tree base; /* Base of the reference. */
259 tree step; /* Step of the reference. */
260 struct mem_ref *refs; /* References in the group. */
261 struct mem_ref_group *next; /* Next group of references. */
262 };
263
264 /* Assigned to PREFETCH_BEFORE when all iterations are to be prefetched. */
265
266 #define PREFETCH_ALL (~(unsigned HOST_WIDE_INT) 0)
267
268 /* Do not generate a prefetch if the unroll factor is significantly less
269 than what is required by the prefetch. This is to avoid redundant
270 prefetches. For example, when prefetch_mod is 16 and unroll_factor is
271 2, prefetching requires unrolling the loop 16 times, but
272 the loop is actually unrolled twice. In this case (ratio = 8),
273 prefetching is not likely to be beneficial. */
274
275 #ifndef PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO
276 #define PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO 4
277 #endif
278
279 /* Some of the prefetch computations have quadratic complexity. We want to
280 avoid huge compile times and, therefore, want to limit the amount of
281 memory references per loop where we consider prefetching. */
282
283 #ifndef PREFETCH_MAX_MEM_REFS_PER_LOOP
284 #define PREFETCH_MAX_MEM_REFS_PER_LOOP 200
285 #endif
286
287 /* The memory reference. */
288
289 struct mem_ref
290 {
291 gimple stmt; /* Statement in that the reference appears. */
292 tree mem; /* The reference. */
293 HOST_WIDE_INT delta; /* Constant offset of the reference. */
294 struct mem_ref_group *group; /* The group of references it belongs to. */
295 unsigned HOST_WIDE_INT prefetch_mod;
296 /* Prefetch only each PREFETCH_MOD-th
297 iteration. */
298 unsigned HOST_WIDE_INT prefetch_before;
299 /* Prefetch only first PREFETCH_BEFORE
300 iterations. */
301 unsigned reuse_distance; /* The amount of data accessed before the first
302 reuse of this value. */
303 struct mem_ref *next; /* The next reference in the group. */
304 unsigned write_p : 1; /* Is it a write? */
305 unsigned independent_p : 1; /* True if the reference is independent on
306 all other references inside the loop. */
307 unsigned issue_prefetch_p : 1; /* Should we really issue the prefetch? */
308 unsigned storent_p : 1; /* True if we changed the store to a
309 nontemporal one. */
310 };
311
312 /* Dumps information about memory reference */
313 static void
314 dump_mem_details (FILE *file, tree base, tree step,
315 HOST_WIDE_INT delta, bool write_p)
316 {
317 fprintf (file, "(base ");
318 print_generic_expr (file, base, TDF_SLIM);
319 fprintf (file, ", step ");
320 if (cst_and_fits_in_hwi (step))
321 fprintf (file, HOST_WIDE_INT_PRINT_DEC, int_cst_value (step));
322 else
323 print_generic_expr (file, step, TDF_TREE);
324 fprintf (file, ")\n");
325 fprintf (file, " delta ");
326 fprintf (file, HOST_WIDE_INT_PRINT_DEC, delta);
327 fprintf (file, "\n");
328 fprintf (file, " %s\n", write_p ? "write" : "read");
329 fprintf (file, "\n");
330 }
331
332 /* Dumps information about reference REF to FILE. */
333
334 static void
335 dump_mem_ref (FILE *file, struct mem_ref *ref)
336 {
337 fprintf (file, "Reference %p:\n", (void *) ref);
338
339 fprintf (file, " group %p ", (void *) ref->group);
340
341 dump_mem_details (file, ref->group->base, ref->group->step, ref->delta,
342 ref->write_p);
343 }
344
345 /* Finds a group with BASE and STEP in GROUPS, or creates one if it does not
346 exist. */
347
348 static struct mem_ref_group *
349 find_or_create_group (struct mem_ref_group **groups, tree base, tree step)
350 {
351 struct mem_ref_group *group;
352
353 for (; *groups; groups = &(*groups)->next)
354 {
355 if (operand_equal_p ((*groups)->step, step, 0)
356 && operand_equal_p ((*groups)->base, base, 0))
357 return *groups;
358
359 /* If step is an integer constant, keep the list of groups sorted
360 by decreasing step. */
361 if (cst_and_fits_in_hwi ((*groups)->step) && cst_and_fits_in_hwi (step)
362 && int_cst_value ((*groups)->step) < int_cst_value (step))
363 break;
364 }
365
366 group = XNEW (struct mem_ref_group);
367 group->base = base;
368 group->step = step;
369 group->refs = NULL;
370 group->next = *groups;
371 *groups = group;
372
373 return group;
374 }
375
376 /* Records a memory reference MEM in GROUP with offset DELTA and write status
377 WRITE_P. The reference occurs in statement STMT. */
378
379 static void
380 record_ref (struct mem_ref_group *group, gimple stmt, tree mem,
381 HOST_WIDE_INT delta, bool write_p)
382 {
383 struct mem_ref **aref;
384
385 /* Do not record the same address twice. */
386 for (aref = &group->refs; *aref; aref = &(*aref)->next)
387 {
388 /* It does not have to be possible for write reference to reuse the read
389 prefetch, or vice versa. */
390 if (!WRITE_CAN_USE_READ_PREFETCH
391 && write_p
392 && !(*aref)->write_p)
393 continue;
394 if (!READ_CAN_USE_WRITE_PREFETCH
395 && !write_p
396 && (*aref)->write_p)
397 continue;
398
399 if ((*aref)->delta == delta)
400 return;
401 }
402
403 (*aref) = XNEW (struct mem_ref);
404 (*aref)->stmt = stmt;
405 (*aref)->mem = mem;
406 (*aref)->delta = delta;
407 (*aref)->write_p = write_p;
408 (*aref)->prefetch_before = PREFETCH_ALL;
409 (*aref)->prefetch_mod = 1;
410 (*aref)->reuse_distance = 0;
411 (*aref)->issue_prefetch_p = false;
412 (*aref)->group = group;
413 (*aref)->next = NULL;
414 (*aref)->independent_p = false;
415 (*aref)->storent_p = false;
416
417 if (dump_file && (dump_flags & TDF_DETAILS))
418 dump_mem_ref (dump_file, *aref);
419 }
420
421 /* Release memory references in GROUPS. */
422
423 static void
424 release_mem_refs (struct mem_ref_group *groups)
425 {
426 struct mem_ref_group *next_g;
427 struct mem_ref *ref, *next_r;
428
429 for (; groups; groups = next_g)
430 {
431 next_g = groups->next;
432 for (ref = groups->refs; ref; ref = next_r)
433 {
434 next_r = ref->next;
435 free (ref);
436 }
437 free (groups);
438 }
439 }
440
441 /* A structure used to pass arguments to idx_analyze_ref. */
442
443 struct ar_data
444 {
445 struct loop *loop; /* Loop of the reference. */
446 gimple stmt; /* Statement of the reference. */
447 tree *step; /* Step of the memory reference. */
448 HOST_WIDE_INT *delta; /* Offset of the memory reference. */
449 };
450
451 /* Analyzes a single INDEX of a memory reference to obtain information
452 described at analyze_ref. Callback for for_each_index. */
453
454 static bool
455 idx_analyze_ref (tree base, tree *index, void *data)
456 {
457 struct ar_data *ar_data = (struct ar_data *) data;
458 tree ibase, step, stepsize;
459 HOST_WIDE_INT idelta = 0, imult = 1;
460 affine_iv iv;
461
462 if (!simple_iv (ar_data->loop, loop_containing_stmt (ar_data->stmt),
463 *index, &iv, true))
464 return false;
465 ibase = iv.base;
466 step = iv.step;
467
468 if (TREE_CODE (ibase) == POINTER_PLUS_EXPR
469 && cst_and_fits_in_hwi (TREE_OPERAND (ibase, 1)))
470 {
471 idelta = int_cst_value (TREE_OPERAND (ibase, 1));
472 ibase = TREE_OPERAND (ibase, 0);
473 }
474 if (cst_and_fits_in_hwi (ibase))
475 {
476 idelta += int_cst_value (ibase);
477 ibase = build_int_cst (TREE_TYPE (ibase), 0);
478 }
479
480 if (TREE_CODE (base) == ARRAY_REF)
481 {
482 stepsize = array_ref_element_size (base);
483 if (!cst_and_fits_in_hwi (stepsize))
484 return false;
485 imult = int_cst_value (stepsize);
486 step = fold_build2 (MULT_EXPR, sizetype,
487 fold_convert (sizetype, step),
488 fold_convert (sizetype, stepsize));
489 idelta *= imult;
490 }
491
492 if (*ar_data->step == NULL_TREE)
493 *ar_data->step = step;
494 else
495 *ar_data->step = fold_build2 (PLUS_EXPR, sizetype,
496 fold_convert (sizetype, *ar_data->step),
497 fold_convert (sizetype, step));
498 *ar_data->delta += idelta;
499 *index = ibase;
500
501 return true;
502 }
503
504 /* Tries to express REF_P in shape &BASE + STEP * iter + DELTA, where DELTA and
505 STEP are integer constants and iter is number of iterations of LOOP. The
506 reference occurs in statement STMT. Strips nonaddressable component
507 references from REF_P. */
508
509 static bool
510 analyze_ref (struct loop *loop, tree *ref_p, tree *base,
511 tree *step, HOST_WIDE_INT *delta,
512 gimple stmt)
513 {
514 struct ar_data ar_data;
515 tree off;
516 HOST_WIDE_INT bit_offset;
517 tree ref = *ref_p;
518
519 *step = NULL_TREE;
520 *delta = 0;
521
522 /* First strip off the component references. Ignore bitfields.
523 Also strip off the real and imagine parts of a complex, so that
524 they can have the same base. */
525 if (TREE_CODE (ref) == REALPART_EXPR
526 || TREE_CODE (ref) == IMAGPART_EXPR
527 || (TREE_CODE (ref) == COMPONENT_REF
528 && DECL_NONADDRESSABLE_P (TREE_OPERAND (ref, 1))))
529 {
530 if (TREE_CODE (ref) == IMAGPART_EXPR)
531 *delta += int_size_in_bytes (TREE_TYPE (ref));
532 ref = TREE_OPERAND (ref, 0);
533 }
534
535 *ref_p = ref;
536
537 for (; TREE_CODE (ref) == COMPONENT_REF; ref = TREE_OPERAND (ref, 0))
538 {
539 off = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
540 bit_offset = TREE_INT_CST_LOW (off);
541 gcc_assert (bit_offset % BITS_PER_UNIT == 0);
542
543 *delta += bit_offset / BITS_PER_UNIT;
544 }
545
546 *base = unshare_expr (ref);
547 ar_data.loop = loop;
548 ar_data.stmt = stmt;
549 ar_data.step = step;
550 ar_data.delta = delta;
551 return for_each_index (base, idx_analyze_ref, &ar_data);
552 }
553
554 /* Record a memory reference REF to the list REFS. The reference occurs in
555 LOOP in statement STMT and it is write if WRITE_P. Returns true if the
556 reference was recorded, false otherwise. */
557
558 static bool
559 gather_memory_references_ref (struct loop *loop, struct mem_ref_group **refs,
560 tree ref, bool write_p, gimple stmt)
561 {
562 tree base, step;
563 HOST_WIDE_INT delta;
564 struct mem_ref_group *agrp;
565
566 if (get_base_address (ref) == NULL)
567 return false;
568
569 if (!analyze_ref (loop, &ref, &base, &step, &delta, stmt))
570 return false;
571 /* If analyze_ref fails the default is a NULL_TREE. We can stop here. */
572 if (step == NULL_TREE)
573 return false;
574
575 /* Stop if the address of BASE could not be taken. */
576 if (may_be_nonaddressable_p (base))
577 return false;
578
579 /* Limit non-constant step prefetching only to the innermost loops and
580 only when the step is loop invariant in the entire loop nest. */
581 if (!cst_and_fits_in_hwi (step))
582 {
583 if (loop->inner != NULL)
584 {
585 if (dump_file && (dump_flags & TDF_DETAILS))
586 {
587 fprintf (dump_file, "Memory expression %p\n",(void *) ref );
588 print_generic_expr (dump_file, ref, TDF_TREE);
589 fprintf (dump_file,":");
590 dump_mem_details (dump_file, base, step, delta, write_p);
591 fprintf (dump_file,
592 "Ignoring %p, non-constant step prefetching is "
593 "limited to inner most loops \n",
594 (void *) ref);
595 }
596 return false;
597 }
598 else
599 {
600 if (!expr_invariant_in_loop_p (loop_outermost (loop), step))
601 {
602 if (dump_file && (dump_flags & TDF_DETAILS))
603 {
604 fprintf (dump_file, "Memory expression %p\n",(void *) ref );
605 print_generic_expr (dump_file, ref, TDF_TREE);
606 fprintf (dump_file,":");
607 dump_mem_details (dump_file, base, step, delta, write_p);
608 fprintf (dump_file,
609 "Not prefetching, ignoring %p due to "
610 "loop variant step\n",
611 (void *) ref);
612 }
613 return false;
614 }
615 }
616 }
617
618 /* Now we know that REF = &BASE + STEP * iter + DELTA, where DELTA and STEP
619 are integer constants. */
620 agrp = find_or_create_group (refs, base, step);
621 record_ref (agrp, stmt, ref, delta, write_p);
622
623 return true;
624 }
625
626 /* Record the suitable memory references in LOOP. NO_OTHER_REFS is set to
627 true if there are no other memory references inside the loop. */
628
629 static struct mem_ref_group *
630 gather_memory_references (struct loop *loop, bool *no_other_refs, unsigned *ref_count)
631 {
632 basic_block *body = get_loop_body_in_dom_order (loop);
633 basic_block bb;
634 unsigned i;
635 gimple_stmt_iterator bsi;
636 gimple stmt;
637 tree lhs, rhs;
638 struct mem_ref_group *refs = NULL;
639
640 *no_other_refs = true;
641 *ref_count = 0;
642
643 /* Scan the loop body in order, so that the former references precede the
644 later ones. */
645 for (i = 0; i < loop->num_nodes; i++)
646 {
647 bb = body[i];
648 if (bb->loop_father != loop)
649 continue;
650
651 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
652 {
653 stmt = gsi_stmt (bsi);
654
655 if (gimple_code (stmt) != GIMPLE_ASSIGN)
656 {
657 if (gimple_vuse (stmt)
658 || (is_gimple_call (stmt)
659 && !(gimple_call_flags (stmt) & ECF_CONST)))
660 *no_other_refs = false;
661 continue;
662 }
663
664 lhs = gimple_assign_lhs (stmt);
665 rhs = gimple_assign_rhs1 (stmt);
666
667 if (REFERENCE_CLASS_P (rhs))
668 {
669 *no_other_refs &= gather_memory_references_ref (loop, &refs,
670 rhs, false, stmt);
671 *ref_count += 1;
672 }
673 if (REFERENCE_CLASS_P (lhs))
674 {
675 *no_other_refs &= gather_memory_references_ref (loop, &refs,
676 lhs, true, stmt);
677 *ref_count += 1;
678 }
679 }
680 }
681 free (body);
682
683 return refs;
684 }
685
686 /* Prune the prefetch candidate REF using the self-reuse. */
687
688 static void
689 prune_ref_by_self_reuse (struct mem_ref *ref)
690 {
691 HOST_WIDE_INT step;
692 bool backward;
693
694 /* If the step size is non constant, we cannot calculate prefetch_mod. */
695 if (!cst_and_fits_in_hwi (ref->group->step))
696 return;
697
698 step = int_cst_value (ref->group->step);
699
700 backward = step < 0;
701
702 if (step == 0)
703 {
704 /* Prefetch references to invariant address just once. */
705 ref->prefetch_before = 1;
706 return;
707 }
708
709 if (backward)
710 step = -step;
711
712 if (step > PREFETCH_BLOCK)
713 return;
714
715 if ((backward && HAVE_BACKWARD_PREFETCH)
716 || (!backward && HAVE_FORWARD_PREFETCH))
717 {
718 ref->prefetch_before = 1;
719 return;
720 }
721
722 ref->prefetch_mod = PREFETCH_BLOCK / step;
723 }
724
725 /* Divides X by BY, rounding down. */
726
727 static HOST_WIDE_INT
728 ddown (HOST_WIDE_INT x, unsigned HOST_WIDE_INT by)
729 {
730 gcc_assert (by > 0);
731
732 if (x >= 0)
733 return x / by;
734 else
735 return (x + by - 1) / by;
736 }
737
738 /* Given a CACHE_LINE_SIZE and two inductive memory references
739 with a common STEP greater than CACHE_LINE_SIZE and an address
740 difference DELTA, compute the probability that they will fall
741 in different cache lines. Return true if the computed miss rate
742 is not greater than the ACCEPTABLE_MISS_RATE. DISTINCT_ITERS is the
743 number of distinct iterations after which the pattern repeats itself.
744 ALIGN_UNIT is the unit of alignment in bytes. */
745
746 static bool
747 is_miss_rate_acceptable (unsigned HOST_WIDE_INT cache_line_size,
748 HOST_WIDE_INT step, HOST_WIDE_INT delta,
749 unsigned HOST_WIDE_INT distinct_iters,
750 int align_unit)
751 {
752 unsigned align, iter;
753 int total_positions, miss_positions, max_allowed_miss_positions;
754 int address1, address2, cache_line1, cache_line2;
755
756 /* It always misses if delta is greater than or equal to the cache
757 line size. */
758 if (delta >= (HOST_WIDE_INT) cache_line_size)
759 return false;
760
761 miss_positions = 0;
762 total_positions = (cache_line_size / align_unit) * distinct_iters;
763 max_allowed_miss_positions = (ACCEPTABLE_MISS_RATE * total_positions) / 1000;
764
765 /* Iterate through all possible alignments of the first
766 memory reference within its cache line. */
767 for (align = 0; align < cache_line_size; align += align_unit)
768
769 /* Iterate through all distinct iterations. */
770 for (iter = 0; iter < distinct_iters; iter++)
771 {
772 address1 = align + step * iter;
773 address2 = address1 + delta;
774 cache_line1 = address1 / cache_line_size;
775 cache_line2 = address2 / cache_line_size;
776 if (cache_line1 != cache_line2)
777 {
778 miss_positions += 1;
779 if (miss_positions > max_allowed_miss_positions)
780 return false;
781 }
782 }
783 return true;
784 }
785
786 /* Prune the prefetch candidate REF using the reuse with BY.
787 If BY_IS_BEFORE is true, BY is before REF in the loop. */
788
789 static void
790 prune_ref_by_group_reuse (struct mem_ref *ref, struct mem_ref *by,
791 bool by_is_before)
792 {
793 HOST_WIDE_INT step;
794 bool backward;
795 HOST_WIDE_INT delta_r = ref->delta, delta_b = by->delta;
796 HOST_WIDE_INT delta = delta_b - delta_r;
797 HOST_WIDE_INT hit_from;
798 unsigned HOST_WIDE_INT prefetch_before, prefetch_block;
799 HOST_WIDE_INT reduced_step;
800 unsigned HOST_WIDE_INT reduced_prefetch_block;
801 tree ref_type;
802 int align_unit;
803
804 /* If the step is non constant we cannot calculate prefetch_before. */
805 if (!cst_and_fits_in_hwi (ref->group->step)) {
806 return;
807 }
808
809 step = int_cst_value (ref->group->step);
810
811 backward = step < 0;
812
813
814 if (delta == 0)
815 {
816 /* If the references has the same address, only prefetch the
817 former. */
818 if (by_is_before)
819 ref->prefetch_before = 0;
820
821 return;
822 }
823
824 if (!step)
825 {
826 /* If the reference addresses are invariant and fall into the
827 same cache line, prefetch just the first one. */
828 if (!by_is_before)
829 return;
830
831 if (ddown (ref->delta, PREFETCH_BLOCK)
832 != ddown (by->delta, PREFETCH_BLOCK))
833 return;
834
835 ref->prefetch_before = 0;
836 return;
837 }
838
839 /* Only prune the reference that is behind in the array. */
840 if (backward)
841 {
842 if (delta > 0)
843 return;
844
845 /* Transform the data so that we may assume that the accesses
846 are forward. */
847 delta = - delta;
848 step = -step;
849 delta_r = PREFETCH_BLOCK - 1 - delta_r;
850 delta_b = PREFETCH_BLOCK - 1 - delta_b;
851 }
852 else
853 {
854 if (delta < 0)
855 return;
856 }
857
858 /* Check whether the two references are likely to hit the same cache
859 line, and how distant the iterations in that it occurs are from
860 each other. */
861
862 if (step <= PREFETCH_BLOCK)
863 {
864 /* The accesses are sure to meet. Let us check when. */
865 hit_from = ddown (delta_b, PREFETCH_BLOCK) * PREFETCH_BLOCK;
866 prefetch_before = (hit_from - delta_r + step - 1) / step;
867
868 /* Do not reduce prefetch_before if we meet beyond cache size. */
869 if (prefetch_before > absu_hwi (L2_CACHE_SIZE_BYTES / step))
870 prefetch_before = PREFETCH_ALL;
871 if (prefetch_before < ref->prefetch_before)
872 ref->prefetch_before = prefetch_before;
873
874 return;
875 }
876
877 /* A more complicated case with step > prefetch_block. First reduce
878 the ratio between the step and the cache line size to its simplest
879 terms. The resulting denominator will then represent the number of
880 distinct iterations after which each address will go back to its
881 initial location within the cache line. This computation assumes
882 that PREFETCH_BLOCK is a power of two. */
883 prefetch_block = PREFETCH_BLOCK;
884 reduced_prefetch_block = prefetch_block;
885 reduced_step = step;
886 while ((reduced_step & 1) == 0
887 && reduced_prefetch_block > 1)
888 {
889 reduced_step >>= 1;
890 reduced_prefetch_block >>= 1;
891 }
892
893 prefetch_before = delta / step;
894 delta %= step;
895 ref_type = TREE_TYPE (ref->mem);
896 align_unit = TYPE_ALIGN (ref_type) / 8;
897 if (is_miss_rate_acceptable (prefetch_block, step, delta,
898 reduced_prefetch_block, align_unit))
899 {
900 /* Do not reduce prefetch_before if we meet beyond cache size. */
901 if (prefetch_before > L2_CACHE_SIZE_BYTES / PREFETCH_BLOCK)
902 prefetch_before = PREFETCH_ALL;
903 if (prefetch_before < ref->prefetch_before)
904 ref->prefetch_before = prefetch_before;
905
906 return;
907 }
908
909 /* Try also the following iteration. */
910 prefetch_before++;
911 delta = step - delta;
912 if (is_miss_rate_acceptable (prefetch_block, step, delta,
913 reduced_prefetch_block, align_unit))
914 {
915 if (prefetch_before < ref->prefetch_before)
916 ref->prefetch_before = prefetch_before;
917
918 return;
919 }
920
921 /* The ref probably does not reuse by. */
922 return;
923 }
924
925 /* Prune the prefetch candidate REF using the reuses with other references
926 in REFS. */
927
928 static void
929 prune_ref_by_reuse (struct mem_ref *ref, struct mem_ref *refs)
930 {
931 struct mem_ref *prune_by;
932 bool before = true;
933
934 prune_ref_by_self_reuse (ref);
935
936 for (prune_by = refs; prune_by; prune_by = prune_by->next)
937 {
938 if (prune_by == ref)
939 {
940 before = false;
941 continue;
942 }
943
944 if (!WRITE_CAN_USE_READ_PREFETCH
945 && ref->write_p
946 && !prune_by->write_p)
947 continue;
948 if (!READ_CAN_USE_WRITE_PREFETCH
949 && !ref->write_p
950 && prune_by->write_p)
951 continue;
952
953 prune_ref_by_group_reuse (ref, prune_by, before);
954 }
955 }
956
957 /* Prune the prefetch candidates in GROUP using the reuse analysis. */
958
959 static void
960 prune_group_by_reuse (struct mem_ref_group *group)
961 {
962 struct mem_ref *ref_pruned;
963
964 for (ref_pruned = group->refs; ref_pruned; ref_pruned = ref_pruned->next)
965 {
966 prune_ref_by_reuse (ref_pruned, group->refs);
967
968 if (dump_file && (dump_flags & TDF_DETAILS))
969 {
970 fprintf (dump_file, "Reference %p:", (void *) ref_pruned);
971
972 if (ref_pruned->prefetch_before == PREFETCH_ALL
973 && ref_pruned->prefetch_mod == 1)
974 fprintf (dump_file, " no restrictions");
975 else if (ref_pruned->prefetch_before == 0)
976 fprintf (dump_file, " do not prefetch");
977 else if (ref_pruned->prefetch_before <= ref_pruned->prefetch_mod)
978 fprintf (dump_file, " prefetch once");
979 else
980 {
981 if (ref_pruned->prefetch_before != PREFETCH_ALL)
982 {
983 fprintf (dump_file, " prefetch before ");
984 fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
985 ref_pruned->prefetch_before);
986 }
987 if (ref_pruned->prefetch_mod != 1)
988 {
989 fprintf (dump_file, " prefetch mod ");
990 fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
991 ref_pruned->prefetch_mod);
992 }
993 }
994 fprintf (dump_file, "\n");
995 }
996 }
997 }
998
999 /* Prune the list of prefetch candidates GROUPS using the reuse analysis. */
1000
1001 static void
1002 prune_by_reuse (struct mem_ref_group *groups)
1003 {
1004 for (; groups; groups = groups->next)
1005 prune_group_by_reuse (groups);
1006 }
1007
1008 /* Returns true if we should issue prefetch for REF. */
1009
1010 static bool
1011 should_issue_prefetch_p (struct mem_ref *ref)
1012 {
1013 /* For now do not issue prefetches for only first few of the
1014 iterations. */
1015 if (ref->prefetch_before != PREFETCH_ALL)
1016 {
1017 if (dump_file && (dump_flags & TDF_DETAILS))
1018 fprintf (dump_file, "Ignoring %p due to prefetch_before\n",
1019 (void *) ref);
1020 return false;
1021 }
1022
1023 /* Do not prefetch nontemporal stores. */
1024 if (ref->storent_p)
1025 {
1026 if (dump_file && (dump_flags & TDF_DETAILS))
1027 fprintf (dump_file, "Ignoring nontemporal store %p\n", (void *) ref);
1028 return false;
1029 }
1030
1031 return true;
1032 }
1033
1034 /* Decide which of the prefetch candidates in GROUPS to prefetch.
1035 AHEAD is the number of iterations to prefetch ahead (which corresponds
1036 to the number of simultaneous instances of one prefetch running at a
1037 time). UNROLL_FACTOR is the factor by that the loop is going to be
1038 unrolled. Returns true if there is anything to prefetch. */
1039
1040 static bool
1041 schedule_prefetches (struct mem_ref_group *groups, unsigned unroll_factor,
1042 unsigned ahead)
1043 {
1044 unsigned remaining_prefetch_slots, n_prefetches, prefetch_slots;
1045 unsigned slots_per_prefetch;
1046 struct mem_ref *ref;
1047 bool any = false;
1048
1049 /* At most SIMULTANEOUS_PREFETCHES should be running at the same time. */
1050 remaining_prefetch_slots = SIMULTANEOUS_PREFETCHES;
1051
1052 /* The prefetch will run for AHEAD iterations of the original loop, i.e.,
1053 AHEAD / UNROLL_FACTOR iterations of the unrolled loop. In each iteration,
1054 it will need a prefetch slot. */
1055 slots_per_prefetch = (ahead + unroll_factor / 2) / unroll_factor;
1056 if (dump_file && (dump_flags & TDF_DETAILS))
1057 fprintf (dump_file, "Each prefetch instruction takes %u prefetch slots.\n",
1058 slots_per_prefetch);
1059
1060 /* For now we just take memory references one by one and issue
1061 prefetches for as many as possible. The groups are sorted
1062 starting with the largest step, since the references with
1063 large step are more likely to cause many cache misses. */
1064
1065 for (; groups; groups = groups->next)
1066 for (ref = groups->refs; ref; ref = ref->next)
1067 {
1068 if (!should_issue_prefetch_p (ref))
1069 continue;
1070
1071 /* The loop is far from being sufficiently unrolled for this
1072 prefetch. Do not generate prefetch to avoid many redudant
1073 prefetches. */
1074 if (ref->prefetch_mod / unroll_factor > PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO)
1075 continue;
1076
1077 /* If we need to prefetch the reference each PREFETCH_MOD iterations,
1078 and we unroll the loop UNROLL_FACTOR times, we need to insert
1079 ceil (UNROLL_FACTOR / PREFETCH_MOD) instructions in each
1080 iteration. */
1081 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1082 / ref->prefetch_mod);
1083 prefetch_slots = n_prefetches * slots_per_prefetch;
1084
1085 /* If more than half of the prefetches would be lost anyway, do not
1086 issue the prefetch. */
1087 if (2 * remaining_prefetch_slots < prefetch_slots)
1088 continue;
1089
1090 ref->issue_prefetch_p = true;
1091
1092 if (remaining_prefetch_slots <= prefetch_slots)
1093 return true;
1094 remaining_prefetch_slots -= prefetch_slots;
1095 any = true;
1096 }
1097
1098 return any;
1099 }
1100
1101 /* Return TRUE if no prefetch is going to be generated in the given
1102 GROUPS. */
1103
1104 static bool
1105 nothing_to_prefetch_p (struct mem_ref_group *groups)
1106 {
1107 struct mem_ref *ref;
1108
1109 for (; groups; groups = groups->next)
1110 for (ref = groups->refs; ref; ref = ref->next)
1111 if (should_issue_prefetch_p (ref))
1112 return false;
1113
1114 return true;
1115 }
1116
1117 /* Estimate the number of prefetches in the given GROUPS.
1118 UNROLL_FACTOR is the factor by which LOOP was unrolled. */
1119
1120 static int
1121 estimate_prefetch_count (struct mem_ref_group *groups, unsigned unroll_factor)
1122 {
1123 struct mem_ref *ref;
1124 unsigned n_prefetches;
1125 int prefetch_count = 0;
1126
1127 for (; groups; groups = groups->next)
1128 for (ref = groups->refs; ref; ref = ref->next)
1129 if (should_issue_prefetch_p (ref))
1130 {
1131 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1132 / ref->prefetch_mod);
1133 prefetch_count += n_prefetches;
1134 }
1135
1136 return prefetch_count;
1137 }
1138
1139 /* Issue prefetches for the reference REF into loop as decided before.
1140 HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR
1141 is the factor by which LOOP was unrolled. */
1142
1143 static void
1144 issue_prefetch_ref (struct mem_ref *ref, unsigned unroll_factor, unsigned ahead)
1145 {
1146 HOST_WIDE_INT delta;
1147 tree addr, addr_base, write_p, local, forward;
1148 gcall *prefetch;
1149 gimple_stmt_iterator bsi;
1150 unsigned n_prefetches, ap;
1151 bool nontemporal = ref->reuse_distance >= L2_CACHE_SIZE_BYTES;
1152
1153 if (dump_file && (dump_flags & TDF_DETAILS))
1154 fprintf (dump_file, "Issued%s prefetch for %p.\n",
1155 nontemporal ? " nontemporal" : "",
1156 (void *) ref);
1157
1158 bsi = gsi_for_stmt (ref->stmt);
1159
1160 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1161 / ref->prefetch_mod);
1162 addr_base = build_fold_addr_expr_with_type (ref->mem, ptr_type_node);
1163 addr_base = force_gimple_operand_gsi (&bsi, unshare_expr (addr_base),
1164 true, NULL, true, GSI_SAME_STMT);
1165 write_p = ref->write_p ? integer_one_node : integer_zero_node;
1166 local = nontemporal ? integer_zero_node : integer_three_node;
1167
1168 for (ap = 0; ap < n_prefetches; ap++)
1169 {
1170 if (cst_and_fits_in_hwi (ref->group->step))
1171 {
1172 /* Determine the address to prefetch. */
1173 delta = (ahead + ap * ref->prefetch_mod) *
1174 int_cst_value (ref->group->step);
1175 addr = fold_build_pointer_plus_hwi (addr_base, delta);
1176 addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true, NULL,
1177 true, GSI_SAME_STMT);
1178 }
1179 else
1180 {
1181 /* The step size is non-constant but loop-invariant. We use the
1182 heuristic to simply prefetch ahead iterations ahead. */
1183 forward = fold_build2 (MULT_EXPR, sizetype,
1184 fold_convert (sizetype, ref->group->step),
1185 fold_convert (sizetype, size_int (ahead)));
1186 addr = fold_build_pointer_plus (addr_base, forward);
1187 addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true,
1188 NULL, true, GSI_SAME_STMT);
1189 }
1190 /* Create the prefetch instruction. */
1191 prefetch = gimple_build_call (builtin_decl_explicit (BUILT_IN_PREFETCH),
1192 3, addr, write_p, local);
1193 gsi_insert_before (&bsi, prefetch, GSI_SAME_STMT);
1194 }
1195 }
1196
1197 /* Issue prefetches for the references in GROUPS into loop as decided before.
1198 HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR is the
1199 factor by that LOOP was unrolled. */
1200
1201 static void
1202 issue_prefetches (struct mem_ref_group *groups,
1203 unsigned unroll_factor, unsigned ahead)
1204 {
1205 struct mem_ref *ref;
1206
1207 for (; groups; groups = groups->next)
1208 for (ref = groups->refs; ref; ref = ref->next)
1209 if (ref->issue_prefetch_p)
1210 issue_prefetch_ref (ref, unroll_factor, ahead);
1211 }
1212
1213 /* Returns true if REF is a memory write for that a nontemporal store insn
1214 can be used. */
1215
1216 static bool
1217 nontemporal_store_p (struct mem_ref *ref)
1218 {
1219 machine_mode mode;
1220 enum insn_code code;
1221
1222 /* REF must be a write that is not reused. We require it to be independent
1223 on all other memory references in the loop, as the nontemporal stores may
1224 be reordered with respect to other memory references. */
1225 if (!ref->write_p
1226 || !ref->independent_p
1227 || ref->reuse_distance < L2_CACHE_SIZE_BYTES)
1228 return false;
1229
1230 /* Check that we have the storent instruction for the mode. */
1231 mode = TYPE_MODE (TREE_TYPE (ref->mem));
1232 if (mode == BLKmode)
1233 return false;
1234
1235 code = optab_handler (storent_optab, mode);
1236 return code != CODE_FOR_nothing;
1237 }
1238
1239 /* If REF is a nontemporal store, we mark the corresponding modify statement
1240 and return true. Otherwise, we return false. */
1241
1242 static bool
1243 mark_nontemporal_store (struct mem_ref *ref)
1244 {
1245 if (!nontemporal_store_p (ref))
1246 return false;
1247
1248 if (dump_file && (dump_flags & TDF_DETAILS))
1249 fprintf (dump_file, "Marked reference %p as a nontemporal store.\n",
1250 (void *) ref);
1251
1252 gimple_assign_set_nontemporal_move (ref->stmt, true);
1253 ref->storent_p = true;
1254
1255 return true;
1256 }
1257
1258 /* Issue a memory fence instruction after LOOP. */
1259
1260 static void
1261 emit_mfence_after_loop (struct loop *loop)
1262 {
1263 vec<edge> exits = get_loop_exit_edges (loop);
1264 edge exit;
1265 gcall *call;
1266 gimple_stmt_iterator bsi;
1267 unsigned i;
1268
1269 FOR_EACH_VEC_ELT (exits, i, exit)
1270 {
1271 call = gimple_build_call (FENCE_FOLLOWING_MOVNT, 0);
1272
1273 if (!single_pred_p (exit->dest)
1274 /* If possible, we prefer not to insert the fence on other paths
1275 in cfg. */
1276 && !(exit->flags & EDGE_ABNORMAL))
1277 split_loop_exit_edge (exit);
1278 bsi = gsi_after_labels (exit->dest);
1279
1280 gsi_insert_before (&bsi, call, GSI_NEW_STMT);
1281 }
1282
1283 exits.release ();
1284 update_ssa (TODO_update_ssa_only_virtuals);
1285 }
1286
1287 /* Returns true if we can use storent in loop, false otherwise. */
1288
1289 static bool
1290 may_use_storent_in_loop_p (struct loop *loop)
1291 {
1292 bool ret = true;
1293
1294 if (loop->inner != NULL)
1295 return false;
1296
1297 /* If we must issue a mfence insn after using storent, check that there
1298 is a suitable place for it at each of the loop exits. */
1299 if (FENCE_FOLLOWING_MOVNT != NULL_TREE)
1300 {
1301 vec<edge> exits = get_loop_exit_edges (loop);
1302 unsigned i;
1303 edge exit;
1304
1305 FOR_EACH_VEC_ELT (exits, i, exit)
1306 if ((exit->flags & EDGE_ABNORMAL)
1307 && exit->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1308 ret = false;
1309
1310 exits.release ();
1311 }
1312
1313 return ret;
1314 }
1315
1316 /* Marks nontemporal stores in LOOP. GROUPS contains the description of memory
1317 references in the loop. */
1318
1319 static void
1320 mark_nontemporal_stores (struct loop *loop, struct mem_ref_group *groups)
1321 {
1322 struct mem_ref *ref;
1323 bool any = false;
1324
1325 if (!may_use_storent_in_loop_p (loop))
1326 return;
1327
1328 for (; groups; groups = groups->next)
1329 for (ref = groups->refs; ref; ref = ref->next)
1330 any |= mark_nontemporal_store (ref);
1331
1332 if (any && FENCE_FOLLOWING_MOVNT != NULL_TREE)
1333 emit_mfence_after_loop (loop);
1334 }
1335
1336 /* Determines whether we can profitably unroll LOOP FACTOR times, and if
1337 this is the case, fill in DESC by the description of number of
1338 iterations. */
1339
1340 static bool
1341 should_unroll_loop_p (struct loop *loop, struct tree_niter_desc *desc,
1342 unsigned factor)
1343 {
1344 if (!can_unroll_loop_p (loop, factor, desc))
1345 return false;
1346
1347 /* We only consider loops without control flow for unrolling. This is not
1348 a hard restriction -- tree_unroll_loop works with arbitrary loops
1349 as well; but the unrolling/prefetching is usually more profitable for
1350 loops consisting of a single basic block, and we want to limit the
1351 code growth. */
1352 if (loop->num_nodes > 2)
1353 return false;
1354
1355 return true;
1356 }
1357
1358 /* Determine the coefficient by that unroll LOOP, from the information
1359 contained in the list of memory references REFS. Description of
1360 umber of iterations of LOOP is stored to DESC. NINSNS is the number of
1361 insns of the LOOP. EST_NITER is the estimated number of iterations of
1362 the loop, or -1 if no estimate is available. */
1363
1364 static unsigned
1365 determine_unroll_factor (struct loop *loop, struct mem_ref_group *refs,
1366 unsigned ninsns, struct tree_niter_desc *desc,
1367 HOST_WIDE_INT est_niter)
1368 {
1369 unsigned upper_bound;
1370 unsigned nfactor, factor, mod_constraint;
1371 struct mem_ref_group *agp;
1372 struct mem_ref *ref;
1373
1374 /* First check whether the loop is not too large to unroll. We ignore
1375 PARAM_MAX_UNROLL_TIMES, because for small loops, it prevented us
1376 from unrolling them enough to make exactly one cache line covered by each
1377 iteration. Also, the goal of PARAM_MAX_UNROLL_TIMES is to prevent
1378 us from unrolling the loops too many times in cases where we only expect
1379 gains from better scheduling and decreasing loop overhead, which is not
1380 the case here. */
1381 upper_bound = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / ninsns;
1382
1383 /* If we unrolled the loop more times than it iterates, the unrolled version
1384 of the loop would be never entered. */
1385 if (est_niter >= 0 && est_niter < (HOST_WIDE_INT) upper_bound)
1386 upper_bound = est_niter;
1387
1388 if (upper_bound <= 1)
1389 return 1;
1390
1391 /* Choose the factor so that we may prefetch each cache just once,
1392 but bound the unrolling by UPPER_BOUND. */
1393 factor = 1;
1394 for (agp = refs; agp; agp = agp->next)
1395 for (ref = agp->refs; ref; ref = ref->next)
1396 if (should_issue_prefetch_p (ref))
1397 {
1398 mod_constraint = ref->prefetch_mod;
1399 nfactor = least_common_multiple (mod_constraint, factor);
1400 if (nfactor <= upper_bound)
1401 factor = nfactor;
1402 }
1403
1404 if (!should_unroll_loop_p (loop, desc, factor))
1405 return 1;
1406
1407 return factor;
1408 }
1409
1410 /* Returns the total volume of the memory references REFS, taking into account
1411 reuses in the innermost loop and cache line size. TODO -- we should also
1412 take into account reuses across the iterations of the loops in the loop
1413 nest. */
1414
1415 static unsigned
1416 volume_of_references (struct mem_ref_group *refs)
1417 {
1418 unsigned volume = 0;
1419 struct mem_ref_group *gr;
1420 struct mem_ref *ref;
1421
1422 for (gr = refs; gr; gr = gr->next)
1423 for (ref = gr->refs; ref; ref = ref->next)
1424 {
1425 /* Almost always reuses another value? */
1426 if (ref->prefetch_before != PREFETCH_ALL)
1427 continue;
1428
1429 /* If several iterations access the same cache line, use the size of
1430 the line divided by this number. Otherwise, a cache line is
1431 accessed in each iteration. TODO -- in the latter case, we should
1432 take the size of the reference into account, rounding it up on cache
1433 line size multiple. */
1434 volume += L1_CACHE_LINE_SIZE / ref->prefetch_mod;
1435 }
1436 return volume;
1437 }
1438
1439 /* Returns the volume of memory references accessed across VEC iterations of
1440 loops, whose sizes are described in the LOOP_SIZES array. N is the number
1441 of the loops in the nest (length of VEC and LOOP_SIZES vectors). */
1442
1443 static unsigned
1444 volume_of_dist_vector (lambda_vector vec, unsigned *loop_sizes, unsigned n)
1445 {
1446 unsigned i;
1447
1448 for (i = 0; i < n; i++)
1449 if (vec[i] != 0)
1450 break;
1451
1452 if (i == n)
1453 return 0;
1454
1455 gcc_assert (vec[i] > 0);
1456
1457 /* We ignore the parts of the distance vector in subloops, since usually
1458 the numbers of iterations are much smaller. */
1459 return loop_sizes[i] * vec[i];
1460 }
1461
1462 /* Add the steps of ACCESS_FN multiplied by STRIDE to the array STRIDE
1463 at the position corresponding to the loop of the step. N is the depth
1464 of the considered loop nest, and, LOOP is its innermost loop. */
1465
1466 static void
1467 add_subscript_strides (tree access_fn, unsigned stride,
1468 HOST_WIDE_INT *strides, unsigned n, struct loop *loop)
1469 {
1470 struct loop *aloop;
1471 tree step;
1472 HOST_WIDE_INT astep;
1473 unsigned min_depth = loop_depth (loop) - n;
1474
1475 while (TREE_CODE (access_fn) == POLYNOMIAL_CHREC)
1476 {
1477 aloop = get_chrec_loop (access_fn);
1478 step = CHREC_RIGHT (access_fn);
1479 access_fn = CHREC_LEFT (access_fn);
1480
1481 if ((unsigned) loop_depth (aloop) <= min_depth)
1482 continue;
1483
1484 if (tree_fits_shwi_p (step))
1485 astep = tree_to_shwi (step);
1486 else
1487 astep = L1_CACHE_LINE_SIZE;
1488
1489 strides[n - 1 - loop_depth (loop) + loop_depth (aloop)] += astep * stride;
1490
1491 }
1492 }
1493
1494 /* Returns the volume of memory references accessed between two consecutive
1495 self-reuses of the reference DR. We consider the subscripts of DR in N
1496 loops, and LOOP_SIZES contains the volumes of accesses in each of the
1497 loops. LOOP is the innermost loop of the current loop nest. */
1498
1499 static unsigned
1500 self_reuse_distance (data_reference_p dr, unsigned *loop_sizes, unsigned n,
1501 struct loop *loop)
1502 {
1503 tree stride, access_fn;
1504 HOST_WIDE_INT *strides, astride;
1505 vec<tree> access_fns;
1506 tree ref = DR_REF (dr);
1507 unsigned i, ret = ~0u;
1508
1509 /* In the following example:
1510
1511 for (i = 0; i < N; i++)
1512 for (j = 0; j < N; j++)
1513 use (a[j][i]);
1514 the same cache line is accessed each N steps (except if the change from
1515 i to i + 1 crosses the boundary of the cache line). Thus, for self-reuse,
1516 we cannot rely purely on the results of the data dependence analysis.
1517
1518 Instead, we compute the stride of the reference in each loop, and consider
1519 the innermost loop in that the stride is less than cache size. */
1520
1521 strides = XCNEWVEC (HOST_WIDE_INT, n);
1522 access_fns = DR_ACCESS_FNS (dr);
1523
1524 FOR_EACH_VEC_ELT (access_fns, i, access_fn)
1525 {
1526 /* Keep track of the reference corresponding to the subscript, so that we
1527 know its stride. */
1528 while (handled_component_p (ref) && TREE_CODE (ref) != ARRAY_REF)
1529 ref = TREE_OPERAND (ref, 0);
1530
1531 if (TREE_CODE (ref) == ARRAY_REF)
1532 {
1533 stride = TYPE_SIZE_UNIT (TREE_TYPE (ref));
1534 if (tree_fits_uhwi_p (stride))
1535 astride = tree_to_uhwi (stride);
1536 else
1537 astride = L1_CACHE_LINE_SIZE;
1538
1539 ref = TREE_OPERAND (ref, 0);
1540 }
1541 else
1542 astride = 1;
1543
1544 add_subscript_strides (access_fn, astride, strides, n, loop);
1545 }
1546
1547 for (i = n; i-- > 0; )
1548 {
1549 unsigned HOST_WIDE_INT s;
1550
1551 s = strides[i] < 0 ? -strides[i] : strides[i];
1552
1553 if (s < (unsigned) L1_CACHE_LINE_SIZE
1554 && (loop_sizes[i]
1555 > (unsigned) (L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)))
1556 {
1557 ret = loop_sizes[i];
1558 break;
1559 }
1560 }
1561
1562 free (strides);
1563 return ret;
1564 }
1565
1566 /* Determines the distance till the first reuse of each reference in REFS
1567 in the loop nest of LOOP. NO_OTHER_REFS is true if there are no other
1568 memory references in the loop. Return false if the analysis fails. */
1569
1570 static bool
1571 determine_loop_nest_reuse (struct loop *loop, struct mem_ref_group *refs,
1572 bool no_other_refs)
1573 {
1574 struct loop *nest, *aloop;
1575 vec<data_reference_p> datarefs = vNULL;
1576 vec<ddr_p> dependences = vNULL;
1577 struct mem_ref_group *gr;
1578 struct mem_ref *ref, *refb;
1579 vec<loop_p> vloops = vNULL;
1580 unsigned *loop_data_size;
1581 unsigned i, j, n;
1582 unsigned volume, dist, adist;
1583 HOST_WIDE_INT vol;
1584 data_reference_p dr;
1585 ddr_p dep;
1586
1587 if (loop->inner)
1588 return true;
1589
1590 /* Find the outermost loop of the loop nest of loop (we require that
1591 there are no sibling loops inside the nest). */
1592 nest = loop;
1593 while (1)
1594 {
1595 aloop = loop_outer (nest);
1596
1597 if (aloop == current_loops->tree_root
1598 || aloop->inner->next)
1599 break;
1600
1601 nest = aloop;
1602 }
1603
1604 /* For each loop, determine the amount of data accessed in each iteration.
1605 We use this to estimate whether the reference is evicted from the
1606 cache before its reuse. */
1607 find_loop_nest (nest, &vloops);
1608 n = vloops.length ();
1609 loop_data_size = XNEWVEC (unsigned, n);
1610 volume = volume_of_references (refs);
1611 i = n;
1612 while (i-- != 0)
1613 {
1614 loop_data_size[i] = volume;
1615 /* Bound the volume by the L2 cache size, since above this bound,
1616 all dependence distances are equivalent. */
1617 if (volume > L2_CACHE_SIZE_BYTES)
1618 continue;
1619
1620 aloop = vloops[i];
1621 vol = estimated_stmt_executions_int (aloop);
1622 if (vol == -1)
1623 vol = expected_loop_iterations (aloop);
1624 volume *= vol;
1625 }
1626
1627 /* Prepare the references in the form suitable for data dependence
1628 analysis. We ignore unanalyzable data references (the results
1629 are used just as a heuristics to estimate temporality of the
1630 references, hence we do not need to worry about correctness). */
1631 for (gr = refs; gr; gr = gr->next)
1632 for (ref = gr->refs; ref; ref = ref->next)
1633 {
1634 dr = create_data_ref (nest, loop_containing_stmt (ref->stmt),
1635 ref->mem, ref->stmt, !ref->write_p);
1636
1637 if (dr)
1638 {
1639 ref->reuse_distance = volume;
1640 dr->aux = ref;
1641 datarefs.safe_push (dr);
1642 }
1643 else
1644 no_other_refs = false;
1645 }
1646
1647 FOR_EACH_VEC_ELT (datarefs, i, dr)
1648 {
1649 dist = self_reuse_distance (dr, loop_data_size, n, loop);
1650 ref = (struct mem_ref *) dr->aux;
1651 if (ref->reuse_distance > dist)
1652 ref->reuse_distance = dist;
1653
1654 if (no_other_refs)
1655 ref->independent_p = true;
1656 }
1657
1658 if (!compute_all_dependences (datarefs, &dependences, vloops, true))
1659 return false;
1660
1661 FOR_EACH_VEC_ELT (dependences, i, dep)
1662 {
1663 if (DDR_ARE_DEPENDENT (dep) == chrec_known)
1664 continue;
1665
1666 ref = (struct mem_ref *) DDR_A (dep)->aux;
1667 refb = (struct mem_ref *) DDR_B (dep)->aux;
1668
1669 if (DDR_ARE_DEPENDENT (dep) == chrec_dont_know
1670 || DDR_NUM_DIST_VECTS (dep) == 0)
1671 {
1672 /* If the dependence cannot be analyzed, assume that there might be
1673 a reuse. */
1674 dist = 0;
1675
1676 ref->independent_p = false;
1677 refb->independent_p = false;
1678 }
1679 else
1680 {
1681 /* The distance vectors are normalized to be always lexicographically
1682 positive, hence we cannot tell just from them whether DDR_A comes
1683 before DDR_B or vice versa. However, it is not important,
1684 anyway -- if DDR_A is close to DDR_B, then it is either reused in
1685 DDR_B (and it is not nontemporal), or it reuses the value of DDR_B
1686 in cache (and marking it as nontemporal would not affect
1687 anything). */
1688
1689 dist = volume;
1690 for (j = 0; j < DDR_NUM_DIST_VECTS (dep); j++)
1691 {
1692 adist = volume_of_dist_vector (DDR_DIST_VECT (dep, j),
1693 loop_data_size, n);
1694
1695 /* If this is a dependence in the innermost loop (i.e., the
1696 distances in all superloops are zero) and it is not
1697 the trivial self-dependence with distance zero, record that
1698 the references are not completely independent. */
1699 if (lambda_vector_zerop (DDR_DIST_VECT (dep, j), n - 1)
1700 && (ref != refb
1701 || DDR_DIST_VECT (dep, j)[n-1] != 0))
1702 {
1703 ref->independent_p = false;
1704 refb->independent_p = false;
1705 }
1706
1707 /* Ignore accesses closer than
1708 L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
1709 so that we use nontemporal prefetches e.g. if single memory
1710 location is accessed several times in a single iteration of
1711 the loop. */
1712 if (adist < L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)
1713 continue;
1714
1715 if (adist < dist)
1716 dist = adist;
1717 }
1718 }
1719
1720 if (ref->reuse_distance > dist)
1721 ref->reuse_distance = dist;
1722 if (refb->reuse_distance > dist)
1723 refb->reuse_distance = dist;
1724 }
1725
1726 free_dependence_relations (dependences);
1727 free_data_refs (datarefs);
1728 free (loop_data_size);
1729
1730 if (dump_file && (dump_flags & TDF_DETAILS))
1731 {
1732 fprintf (dump_file, "Reuse distances:\n");
1733 for (gr = refs; gr; gr = gr->next)
1734 for (ref = gr->refs; ref; ref = ref->next)
1735 fprintf (dump_file, " ref %p distance %u\n",
1736 (void *) ref, ref->reuse_distance);
1737 }
1738
1739 return true;
1740 }
1741
1742 /* Determine whether or not the trip count to ahead ratio is too small based
1743 on prefitablility consideration.
1744 AHEAD: the iteration ahead distance,
1745 EST_NITER: the estimated trip count. */
1746
1747 static bool
1748 trip_count_to_ahead_ratio_too_small_p (unsigned ahead, HOST_WIDE_INT est_niter)
1749 {
1750 /* Assume trip count to ahead ratio is big enough if the trip count could not
1751 be estimated at compile time. */
1752 if (est_niter < 0)
1753 return false;
1754
1755 if (est_niter < (HOST_WIDE_INT) (TRIP_COUNT_TO_AHEAD_RATIO * ahead))
1756 {
1757 if (dump_file && (dump_flags & TDF_DETAILS))
1758 fprintf (dump_file,
1759 "Not prefetching -- loop estimated to roll only %d times\n",
1760 (int) est_niter);
1761 return true;
1762 }
1763
1764 return false;
1765 }
1766
1767 /* Determine whether or not the number of memory references in the loop is
1768 reasonable based on the profitablity and compilation time considerations.
1769 NINSNS: estimated number of instructions in the loop,
1770 MEM_REF_COUNT: total number of memory references in the loop. */
1771
1772 static bool
1773 mem_ref_count_reasonable_p (unsigned ninsns, unsigned mem_ref_count)
1774 {
1775 int insn_to_mem_ratio;
1776
1777 if (mem_ref_count == 0)
1778 return false;
1779
1780 /* Miss rate computation (is_miss_rate_acceptable) and dependence analysis
1781 (compute_all_dependences) have high costs based on quadratic complexity.
1782 To avoid huge compilation time, we give up prefetching if mem_ref_count
1783 is too large. */
1784 if (mem_ref_count > PREFETCH_MAX_MEM_REFS_PER_LOOP)
1785 return false;
1786
1787 /* Prefetching improves performance by overlapping cache missing
1788 memory accesses with CPU operations. If the loop does not have
1789 enough CPU operations to overlap with memory operations, prefetching
1790 won't give a significant benefit. One approximate way of checking
1791 this is to require the ratio of instructions to memory references to
1792 be above a certain limit. This approximation works well in practice.
1793 TODO: Implement a more precise computation by estimating the time
1794 for each CPU or memory op in the loop. Time estimates for memory ops
1795 should account for cache misses. */
1796 insn_to_mem_ratio = ninsns / mem_ref_count;
1797
1798 if (insn_to_mem_ratio < PREFETCH_MIN_INSN_TO_MEM_RATIO)
1799 {
1800 if (dump_file && (dump_flags & TDF_DETAILS))
1801 fprintf (dump_file,
1802 "Not prefetching -- instruction to memory reference ratio (%d) too small\n",
1803 insn_to_mem_ratio);
1804 return false;
1805 }
1806
1807 return true;
1808 }
1809
1810 /* Determine whether or not the instruction to prefetch ratio in the loop is
1811 too small based on the profitablity consideration.
1812 NINSNS: estimated number of instructions in the loop,
1813 PREFETCH_COUNT: an estimate of the number of prefetches,
1814 UNROLL_FACTOR: the factor to unroll the loop if prefetching. */
1815
1816 static bool
1817 insn_to_prefetch_ratio_too_small_p (unsigned ninsns, unsigned prefetch_count,
1818 unsigned unroll_factor)
1819 {
1820 int insn_to_prefetch_ratio;
1821
1822 /* Prefetching most likely causes performance degradation when the instruction
1823 to prefetch ratio is too small. Too many prefetch instructions in a loop
1824 may reduce the I-cache performance.
1825 (unroll_factor * ninsns) is used to estimate the number of instructions in
1826 the unrolled loop. This implementation is a bit simplistic -- the number
1827 of issued prefetch instructions is also affected by unrolling. So,
1828 prefetch_mod and the unroll factor should be taken into account when
1829 determining prefetch_count. Also, the number of insns of the unrolled
1830 loop will usually be significantly smaller than the number of insns of the
1831 original loop * unroll_factor (at least the induction variable increases
1832 and the exit branches will get eliminated), so it might be better to use
1833 tree_estimate_loop_size + estimated_unrolled_size. */
1834 insn_to_prefetch_ratio = (unroll_factor * ninsns) / prefetch_count;
1835 if (insn_to_prefetch_ratio < MIN_INSN_TO_PREFETCH_RATIO)
1836 {
1837 if (dump_file && (dump_flags & TDF_DETAILS))
1838 fprintf (dump_file,
1839 "Not prefetching -- instruction to prefetch ratio (%d) too small\n",
1840 insn_to_prefetch_ratio);
1841 return true;
1842 }
1843
1844 return false;
1845 }
1846
1847
1848 /* Issue prefetch instructions for array references in LOOP. Returns
1849 true if the LOOP was unrolled. */
1850
1851 static bool
1852 loop_prefetch_arrays (struct loop *loop)
1853 {
1854 struct mem_ref_group *refs;
1855 unsigned ahead, ninsns, time, unroll_factor;
1856 HOST_WIDE_INT est_niter;
1857 struct tree_niter_desc desc;
1858 bool unrolled = false, no_other_refs;
1859 unsigned prefetch_count;
1860 unsigned mem_ref_count;
1861
1862 if (optimize_loop_nest_for_size_p (loop))
1863 {
1864 if (dump_file && (dump_flags & TDF_DETAILS))
1865 fprintf (dump_file, " ignored (cold area)\n");
1866 return false;
1867 }
1868
1869 /* FIXME: the time should be weighted by the probabilities of the blocks in
1870 the loop body. */
1871 time = tree_num_loop_insns (loop, &eni_time_weights);
1872 if (time == 0)
1873 return false;
1874
1875 ahead = (PREFETCH_LATENCY + time - 1) / time;
1876 est_niter = estimated_stmt_executions_int (loop);
1877 if (est_niter == -1)
1878 est_niter = max_stmt_executions_int (loop);
1879
1880 /* Prefetching is not likely to be profitable if the trip count to ahead
1881 ratio is too small. */
1882 if (trip_count_to_ahead_ratio_too_small_p (ahead, est_niter))
1883 return false;
1884
1885 ninsns = tree_num_loop_insns (loop, &eni_size_weights);
1886
1887 /* Step 1: gather the memory references. */
1888 refs = gather_memory_references (loop, &no_other_refs, &mem_ref_count);
1889
1890 /* Give up prefetching if the number of memory references in the
1891 loop is not reasonable based on profitablity and compilation time
1892 considerations. */
1893 if (!mem_ref_count_reasonable_p (ninsns, mem_ref_count))
1894 goto fail;
1895
1896 /* Step 2: estimate the reuse effects. */
1897 prune_by_reuse (refs);
1898
1899 if (nothing_to_prefetch_p (refs))
1900 goto fail;
1901
1902 if (!determine_loop_nest_reuse (loop, refs, no_other_refs))
1903 goto fail;
1904
1905 /* Step 3: determine unroll factor. */
1906 unroll_factor = determine_unroll_factor (loop, refs, ninsns, &desc,
1907 est_niter);
1908
1909 /* Estimate prefetch count for the unrolled loop. */
1910 prefetch_count = estimate_prefetch_count (refs, unroll_factor);
1911 if (prefetch_count == 0)
1912 goto fail;
1913
1914 if (dump_file && (dump_flags & TDF_DETAILS))
1915 fprintf (dump_file, "Ahead %d, unroll factor %d, trip count "
1916 HOST_WIDE_INT_PRINT_DEC "\n"
1917 "insn count %d, mem ref count %d, prefetch count %d\n",
1918 ahead, unroll_factor, est_niter,
1919 ninsns, mem_ref_count, prefetch_count);
1920
1921 /* Prefetching is not likely to be profitable if the instruction to prefetch
1922 ratio is too small. */
1923 if (insn_to_prefetch_ratio_too_small_p (ninsns, prefetch_count,
1924 unroll_factor))
1925 goto fail;
1926
1927 mark_nontemporal_stores (loop, refs);
1928
1929 /* Step 4: what to prefetch? */
1930 if (!schedule_prefetches (refs, unroll_factor, ahead))
1931 goto fail;
1932
1933 /* Step 5: unroll the loop. TODO -- peeling of first and last few
1934 iterations so that we do not issue superfluous prefetches. */
1935 if (unroll_factor != 1)
1936 {
1937 tree_unroll_loop (loop, unroll_factor,
1938 single_dom_exit (loop), &desc);
1939 unrolled = true;
1940 }
1941
1942 /* Step 6: issue the prefetches. */
1943 issue_prefetches (refs, unroll_factor, ahead);
1944
1945 fail:
1946 release_mem_refs (refs);
1947 return unrolled;
1948 }
1949
1950 /* Issue prefetch instructions for array references in loops. */
1951
1952 unsigned int
1953 tree_ssa_prefetch_arrays (void)
1954 {
1955 struct loop *loop;
1956 bool unrolled = false;
1957 int todo_flags = 0;
1958
1959 if (!HAVE_prefetch
1960 /* It is possible to ask compiler for say -mtune=i486 -march=pentium4.
1961 -mtune=i486 causes us having PREFETCH_BLOCK 0, since this is part
1962 of processor costs and i486 does not have prefetch, but
1963 -march=pentium4 causes HAVE_prefetch to be true. Ugh. */
1964 || PREFETCH_BLOCK == 0)
1965 return 0;
1966
1967 if (dump_file && (dump_flags & TDF_DETAILS))
1968 {
1969 fprintf (dump_file, "Prefetching parameters:\n");
1970 fprintf (dump_file, " simultaneous prefetches: %d\n",
1971 SIMULTANEOUS_PREFETCHES);
1972 fprintf (dump_file, " prefetch latency: %d\n", PREFETCH_LATENCY);
1973 fprintf (dump_file, " prefetch block size: %d\n", PREFETCH_BLOCK);
1974 fprintf (dump_file, " L1 cache size: %d lines, %d kB\n",
1975 L1_CACHE_SIZE_BYTES / L1_CACHE_LINE_SIZE, L1_CACHE_SIZE);
1976 fprintf (dump_file, " L1 cache line size: %d\n", L1_CACHE_LINE_SIZE);
1977 fprintf (dump_file, " L2 cache size: %d kB\n", L2_CACHE_SIZE);
1978 fprintf (dump_file, " min insn-to-prefetch ratio: %d \n",
1979 MIN_INSN_TO_PREFETCH_RATIO);
1980 fprintf (dump_file, " min insn-to-mem ratio: %d \n",
1981 PREFETCH_MIN_INSN_TO_MEM_RATIO);
1982 fprintf (dump_file, "\n");
1983 }
1984
1985 initialize_original_copy_tables ();
1986
1987 if (!builtin_decl_explicit_p (BUILT_IN_PREFETCH))
1988 {
1989 tree type = build_function_type_list (void_type_node,
1990 const_ptr_type_node, NULL_TREE);
1991 tree decl = add_builtin_function ("__builtin_prefetch", type,
1992 BUILT_IN_PREFETCH, BUILT_IN_NORMAL,
1993 NULL, NULL_TREE);
1994 DECL_IS_NOVOPS (decl) = true;
1995 set_builtin_decl (BUILT_IN_PREFETCH, decl, false);
1996 }
1997
1998 /* We assume that size of cache line is a power of two, so verify this
1999 here. */
2000 gcc_assert ((PREFETCH_BLOCK & (PREFETCH_BLOCK - 1)) == 0);
2001
2002 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2003 {
2004 if (dump_file && (dump_flags & TDF_DETAILS))
2005 fprintf (dump_file, "Processing loop %d:\n", loop->num);
2006
2007 unrolled |= loop_prefetch_arrays (loop);
2008
2009 if (dump_file && (dump_flags & TDF_DETAILS))
2010 fprintf (dump_file, "\n\n");
2011 }
2012
2013 if (unrolled)
2014 {
2015 scev_reset ();
2016 todo_flags |= TODO_cleanup_cfg;
2017 }
2018
2019 free_original_copy_tables ();
2020 return todo_flags;
2021 }
2022
2023 /* Prefetching. */
2024
2025 namespace {
2026
2027 const pass_data pass_data_loop_prefetch =
2028 {
2029 GIMPLE_PASS, /* type */
2030 "aprefetch", /* name */
2031 OPTGROUP_LOOP, /* optinfo_flags */
2032 TV_TREE_PREFETCH, /* tv_id */
2033 ( PROP_cfg | PROP_ssa ), /* properties_required */
2034 0, /* properties_provided */
2035 0, /* properties_destroyed */
2036 0, /* todo_flags_start */
2037 0, /* todo_flags_finish */
2038 };
2039
2040 class pass_loop_prefetch : public gimple_opt_pass
2041 {
2042 public:
2043 pass_loop_prefetch (gcc::context *ctxt)
2044 : gimple_opt_pass (pass_data_loop_prefetch, ctxt)
2045 {}
2046
2047 /* opt_pass methods: */
2048 virtual bool gate (function *) { return flag_prefetch_loop_arrays > 0; }
2049 virtual unsigned int execute (function *);
2050
2051 }; // class pass_loop_prefetch
2052
2053 unsigned int
2054 pass_loop_prefetch::execute (function *fun)
2055 {
2056 if (number_of_loops (fun) <= 1)
2057 return 0;
2058
2059 return tree_ssa_prefetch_arrays ();
2060 }
2061
2062 } // anon namespace
2063
2064 gimple_opt_pass *
2065 make_pass_loop_prefetch (gcc::context *ctxt)
2066 {
2067 return new pass_loop_prefetch (ctxt);
2068 }
2069
2070