Debian Codegraph @

gcc/tree-ssa-loop-ivopts.cc

raw
1 /* Induction variable optimizations.
2 Copyright (C) 2003-2025 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 /* This pass tries to find the optimal set of induction variables for the loop.
21 It optimizes just the basic linear induction variables (although adding
22 support for other types should not be too hard). It includes the
23 optimizations commonly known as strength reduction, induction variable
24 coalescing and induction variable elimination. It does it in the
25 following steps:
26
27 1) The interesting uses of induction variables are found. This includes
28
29 -- uses of induction variables in non-linear expressions
30 -- addresses of arrays
31 -- comparisons of induction variables
32
33 Note the interesting uses are categorized and handled in group.
34 Generally, address type uses are grouped together if their iv bases
35 are different in constant offset.
36
37 2) Candidates for the induction variables are found. This includes
38
39 -- old induction variables
40 -- the variables defined by expressions derived from the "interesting
41 groups/uses" above
42
43 3) The optimal (w.r. to a cost function) set of variables is chosen. The
44 cost function assigns a cost to sets of induction variables and consists
45 of three parts:
46
47 -- The group/use costs. Each of the interesting groups/uses chooses
48 the best induction variable in the set and adds its cost to the sum.
49 The cost reflects the time spent on modifying the induction variables
50 value to be usable for the given purpose (adding base and offset for
51 arrays, etc.).
52 -- The variable costs. Each of the variables has a cost assigned that
53 reflects the costs associated with incrementing the value of the
54 variable. The original variables are somewhat preferred.
55 -- The set cost. Depending on the size of the set, extra cost may be
56 added to reflect register pressure.
57
58 All the costs are defined in a machine-specific way, using the target
59 hooks and machine descriptions to determine them.
60
61 4) The trees are transformed to use the new variables, the dead code is
62 removed.
63
64 All of this is done loop by loop. Doing it globally is theoretically
65 possible, it might give a better performance and it might enable us
66 to decide costs more precisely, but getting all the interactions right
67 would be complicated.
68
69 For the targets supporting low-overhead loops, IVOPTs has to take care of
70 the loops which will probably be transformed in RTL doloop optimization,
71 to try to make selected IV candidate set optimal. The process of doloop
72 support includes:
73
74 1) Analyze the current loop will be transformed to doloop or not, find and
75 mark its compare type IV use as doloop use (iv_group field doloop_p), and
76 set flag doloop_use_p of ivopts_data to notify subsequent processings on
77 doloop. See analyze_and_mark_doloop_use and its callees for the details.
78 The target hook predict_doloop_p can be used for target specific checks.
79
80 2) Add one doloop dedicated IV cand {(may_be_zero ? 1 : (niter + 1)), +, -1},
81 set flag doloop_p of iv_cand, step cost is set as zero and no extra cost
82 like biv. For cost determination between doloop IV cand and IV use, the
83 target hooks doloop_cost_for_generic and doloop_cost_for_address are
84 provided to add on extra costs for generic type and address type IV use.
85 Zero cost is assigned to the pair between doloop IV cand and doloop IV
86 use, and bound zero is set for IV elimination.
87
88 3) With the cost setting in step 2), the current cost model based IV
89 selection algorithm will process as usual, pick up doloop dedicated IV if
90 profitable. */
91
92 #include "config.h"
93 #include "system.h"
94 #include "coretypes.h"
95 #include "backend.h"
96 #include "rtl.h"
97 #include "tree.h"
98 #include "gimple.h"
99 #include "cfghooks.h"
100 #include "tree-pass.h"
101 #include "memmodel.h"
102 #include "tm_p.h"
103 #include "ssa.h"
104 #include "expmed.h"
105 #include "insn-config.h"
106 #include "emit-rtl.h"
107 #include "recog.h"
108 #include "cgraph.h"
109 #include "gimple-pretty-print.h"
110 #include "alias.h"
111 #include "fold-const.h"
112 #include "stor-layout.h"
113 #include "tree-eh.h"
114 #include "gimplify.h"
115 #include "gimple-iterator.h"
116 #include "gimplify-me.h"
117 #include "tree-cfg.h"
118 #include "tree-ssa-loop-ivopts.h"
119 #include "tree-ssa-loop-manip.h"
120 #include "tree-ssa-loop-niter.h"
121 #include "tree-ssa-loop.h"
122 #include "explow.h"
123 #include "expr.h"
124 #include "tree-dfa.h"
125 #include "tree-ssa.h"
126 #include "cfgloop.h"
127 #include "tree-scalar-evolution.h"
128 #include "tree-affine.h"
129 #include "tree-ssa-propagate.h"
130 #include "tree-ssa-address.h"
131 #include "builtins.h"
132 #include "tree-vectorizer.h"
133 #include "dbgcnt.h"
134 #include "cfganal.h"
135
136 /* For lang_hooks.types.type_for_mode. */
137 #include "langhooks.h"
138
139 /* FIXME: Expressions are expanded to RTL in this pass to determine the
140 cost of different addressing modes. This should be moved to a TBD
141 interface between the GIMPLE and RTL worlds. */
142
143 /* The infinite cost. */
144 #define INFTY 1000000000
145
146 /* Returns the expected number of loop iterations for LOOP.
147 The average trip count is computed from profile data if it
148 exists. */
149
150 static inline HOST_WIDE_INT
151 avg_loop_niter (class loop *loop)
152 {
153 HOST_WIDE_INT niter = estimated_stmt_executions_int (loop);
154 if (niter == -1)
155 {
156 niter = likely_max_stmt_executions_int (loop);
157
158 if (niter == -1 || niter > param_avg_loop_niter)
159 return param_avg_loop_niter;
160 }
161
162 return niter;
163 }
164
165 struct iv_use;
166
167 /* Representation of the induction variable. */
168 struct iv
169 {
170 tree base; /* Initial value of the iv. */
171 tree base_object; /* A memory object to that the induction variable points. */
172 tree step; /* Step of the iv (constant only). */
173 tree ssa_name; /* The ssa name with the value. */
174 struct iv_use *nonlin_use; /* The identifier in the use if it is the case. */
175 bool biv_p; /* Is it a biv? */
176 bool no_overflow; /* True if the iv doesn't overflow. */
177 bool have_address_use;/* For biv, indicate if it's used in any address
178 type use. */
179 };
180
181 /* Per-ssa version information (induction variable descriptions, etc.). */
182 struct version_info
183 {
184 tree name; /* The ssa name. */
185 struct iv *iv; /* Induction variable description. */
186 bool has_nonlin_use; /* For a loop-level invariant, whether it is used in
187 an expression that is not an induction variable. */
188 bool preserve_biv; /* For the original biv, whether to preserve it. */
189 unsigned inv_id; /* Id of an invariant. */
190 };
191
192 /* Types of uses. */
193 enum use_type
194 {
195 USE_NONLINEAR_EXPR, /* Use in a nonlinear expression. */
196 USE_REF_ADDRESS, /* Use is an address for an explicit memory
197 reference. */
198 USE_PTR_ADDRESS, /* Use is a pointer argument to a function in
199 cases where the expansion of the function
200 will turn the argument into a normal address. */
201 USE_COMPARE /* Use is a compare. */
202 };
203
204 /* Cost of a computation. */
205 class comp_cost
206 {
207 public:
208 comp_cost (): cost (0), complexity (0), scratch (0)
209 {}
210
211 comp_cost (int64_t cost, unsigned complexity, int64_t scratch = 0)
212 : cost (cost), complexity (complexity), scratch (scratch)
213 {}
214
215 /* Returns true if COST is infinite. */
216 bool infinite_cost_p ();
217
218 /* Adds costs COST1 and COST2. */
219 friend comp_cost operator+ (comp_cost cost1, comp_cost cost2);
220
221 /* Adds COST to the comp_cost. */
222 comp_cost operator+= (comp_cost cost);
223
224 /* Adds constant C to this comp_cost. */
225 comp_cost operator+= (HOST_WIDE_INT c);
226
227 /* Subtracts constant C to this comp_cost. */
228 comp_cost operator-= (HOST_WIDE_INT c);
229
230 /* Divide the comp_cost by constant C. */
231 comp_cost operator/= (HOST_WIDE_INT c);
232
233 /* Multiply the comp_cost by constant C. */
234 comp_cost operator*= (HOST_WIDE_INT c);
235
236 /* Subtracts costs COST1 and COST2. */
237 friend comp_cost operator- (comp_cost cost1, comp_cost cost2);
238
239 /* Subtracts COST from this comp_cost. */
240 comp_cost operator-= (comp_cost cost);
241
242 /* Returns true if COST1 is smaller than COST2. */
243 friend bool operator< (comp_cost cost1, comp_cost cost2);
244
245 /* Returns true if COST1 and COST2 are equal. */
246 friend bool operator== (comp_cost cost1, comp_cost cost2);
247
248 /* Returns true if COST1 is smaller or equal than COST2. */
249 friend bool operator<= (comp_cost cost1, comp_cost cost2);
250
251 int64_t cost; /* The runtime cost. */
252 unsigned complexity; /* The estimate of the complexity of the code for
253 the computation (in no concrete units --
254 complexity field should be larger for more
255 complex expressions and addressing modes). */
256 int64_t scratch; /* Scratch used during cost computation. */
257 };
258
259 static const comp_cost no_cost;
260 static const comp_cost infinite_cost (INFTY, 0, INFTY);
261
262 bool
263 comp_cost::infinite_cost_p ()
264 {
265 return cost == INFTY;
266 }
267
268 comp_cost
269 operator+ (comp_cost cost1, comp_cost cost2)
270 {
271 if (cost1.infinite_cost_p () || cost2.infinite_cost_p ())
272 return infinite_cost;
273
274 gcc_assert (cost1.cost + cost2.cost < infinite_cost.cost);
275 cost1.cost += cost2.cost;
276 cost1.complexity += cost2.complexity;
277
278 return cost1;
279 }
280
281 comp_cost
282 operator- (comp_cost cost1, comp_cost cost2)
283 {
284 if (cost1.infinite_cost_p ())
285 return infinite_cost;
286
287 gcc_assert (!cost2.infinite_cost_p ());
288 gcc_assert (cost1.cost - cost2.cost < infinite_cost.cost);
289
290 cost1.cost -= cost2.cost;
291 cost1.complexity -= cost2.complexity;
292
293 return cost1;
294 }
295
296 comp_cost
297 comp_cost::operator+= (comp_cost cost)
298 {
299 *this = *this + cost;
300 return *this;
301 }
302
303 comp_cost
304 comp_cost::operator+= (HOST_WIDE_INT c)
305 {
306 if (c >= INFTY)
307 this->cost = INFTY;
308
309 if (infinite_cost_p ())
310 return *this;
311
312 gcc_assert (this->cost + c < infinite_cost.cost);
313 this->cost += c;
314
315 return *this;
316 }
317
318 comp_cost
319 comp_cost::operator-= (HOST_WIDE_INT c)
320 {
321 if (infinite_cost_p ())
322 return *this;
323
324 gcc_assert (this->cost - c < infinite_cost.cost);
325 this->cost -= c;
326
327 return *this;
328 }
329
330 comp_cost
331 comp_cost::operator/= (HOST_WIDE_INT c)
332 {
333 gcc_assert (c != 0);
334 if (infinite_cost_p ())
335 return *this;
336
337 this->cost /= c;
338
339 return *this;
340 }
341
342 comp_cost
343 comp_cost::operator*= (HOST_WIDE_INT c)
344 {
345 if (infinite_cost_p ())
346 return *this;
347
348 gcc_assert (this->cost * c < infinite_cost.cost);
349 this->cost *= c;
350
351 return *this;
352 }
353
354 comp_cost
355 comp_cost::operator-= (comp_cost cost)
356 {
357 *this = *this - cost;
358 return *this;
359 }
360
361 bool
362 operator< (comp_cost cost1, comp_cost cost2)
363 {
364 if (cost1.cost == cost2.cost)
365 return cost1.complexity < cost2.complexity;
366
367 return cost1.cost < cost2.cost;
368 }
369
370 bool
371 operator== (comp_cost cost1, comp_cost cost2)
372 {
373 return cost1.cost == cost2.cost
374 && cost1.complexity == cost2.complexity;
375 }
376
377 bool
378 operator<= (comp_cost cost1, comp_cost cost2)
379 {
380 return cost1 < cost2 || cost1 == cost2;
381 }
382
383 struct iv_inv_expr_ent;
384
385 /* The candidate - cost pair. */
386 class cost_pair
387 {
388 public:
389 struct iv_cand *cand; /* The candidate. */
390 comp_cost cost; /* The cost. */
391 enum tree_code comp; /* For iv elimination, the comparison. */
392 bitmap inv_vars; /* The list of invariant ssa_vars that have to be
393 preserved when representing iv_use with iv_cand. */
394 bitmap inv_exprs; /* The list of newly created invariant expressions
395 when representing iv_use with iv_cand. */
396 tree value; /* For final value elimination, the expression for
397 the final value of the iv. For iv elimination,
398 the new bound to compare with. */
399 };
400
401 /* Use. */
402 struct iv_use
403 {
404 unsigned id; /* The id of the use. */
405 unsigned group_id; /* The group id the use belongs to. */
406 enum use_type type; /* Type of the use. */
407 tree mem_type; /* The memory type to use when testing whether an
408 address is legitimate, and what the address's
409 cost is. */
410 struct iv *iv; /* The induction variable it is based on. */
411 gimple *stmt; /* Statement in that it occurs. */
412 tree *op_p; /* The place where it occurs. */
413
414 tree addr_base; /* Base address with const offset stripped. */
415 poly_uint64 addr_offset;
416 /* Const offset stripped from base address. */
417 };
418
419 /* Group of uses. */
420 struct iv_group
421 {
422 /* The id of the group. */
423 unsigned id;
424 /* Uses of the group are of the same type. */
425 enum use_type type;
426 /* The set of "related" IV candidates, plus the important ones. */
427 bitmap related_cands;
428 /* Number of IV candidates in the cost_map. */
429 unsigned n_map_members;
430 /* The costs wrto the iv candidates. */
431 class cost_pair *cost_map;
432 /* The selected candidate for the group. */
433 struct iv_cand *selected;
434 /* To indicate this is a doloop use group. */
435 bool doloop_p;
436 /* Uses in the group. */
437 vec<struct iv_use *> vuses;
438 };
439
440 /* The position where the iv is computed. */
441 enum iv_position
442 {
443 IP_NORMAL, /* At the end, just before the exit condition. */
444 IP_END, /* At the end of the latch block. */
445 IP_BEFORE_USE, /* Immediately before a specific use. */
446 IP_AFTER_USE, /* Immediately after a specific use. */
447 IP_ORIGINAL /* The original biv. */
448 };
449
450 /* The induction variable candidate. */
451 struct iv_cand
452 {
453 unsigned id; /* The number of the candidate. */
454 bool important; /* Whether this is an "important" candidate, i.e. such
455 that it should be considered by all uses. */
456 bool involves_undefs; /* Whether the IV involves undefined values. */
457 ENUM_BITFIELD(iv_position) pos : 8; /* Where it is computed. */
458 gimple *incremented_at;/* For original biv, the statement where it is
459 incremented. */
460 tree var_before; /* The variable used for it before increment. */
461 tree var_after; /* The variable used for it after increment. */
462 struct iv *iv; /* The value of the candidate. NULL for
463 "pseudocandidate" used to indicate the possibility
464 to replace the final value of an iv by direct
465 computation of the value. */
466 unsigned cost; /* Cost of the candidate. */
467 unsigned cost_step; /* Cost of the candidate's increment operation. */
468 struct iv_use *ainc_use; /* For IP_{BEFORE,AFTER}_USE candidates, the place
469 where it is incremented. */
470 bitmap inv_vars; /* The list of invariant ssa_vars used in step of the
471 iv_cand. */
472 bitmap inv_exprs; /* If step is more complicated than a single ssa_var,
473 handle it as a new invariant expression which will
474 be hoisted out of loop. */
475 struct iv *orig_iv; /* The original iv if this cand is added from biv with
476 smaller type. */
477 bool doloop_p; /* Whether this is a doloop candidate. */
478 };
479
480 /* Hashtable entry for common candidate derived from iv uses. */
481 class iv_common_cand
482 {
483 public:
484 tree base;
485 tree step;
486 /* IV uses from which this common candidate is derived. */
487 auto_vec<struct iv_use *> uses;
488 hashval_t hash;
489 };
490
491 /* Hashtable helpers. */
492
493 struct iv_common_cand_hasher : delete_ptr_hash <iv_common_cand>
494 {
495 static inline hashval_t hash (const iv_common_cand *);
496 static inline bool equal (const iv_common_cand *, const iv_common_cand *);
497 };
498
499 /* Hash function for possible common candidates. */
500
501 inline hashval_t
502 iv_common_cand_hasher::hash (const iv_common_cand *ccand)
503 {
504 return ccand->hash;
505 }
506
507 /* Hash table equality function for common candidates. */
508
509 inline bool
510 iv_common_cand_hasher::equal (const iv_common_cand *ccand1,
511 const iv_common_cand *ccand2)
512 {
513 return (ccand1->hash == ccand2->hash
514 && operand_equal_p (ccand1->base, ccand2->base, 0)
515 && operand_equal_p (ccand1->step, ccand2->step, 0)
516 && (TYPE_PRECISION (TREE_TYPE (ccand1->base))
517 == TYPE_PRECISION (TREE_TYPE (ccand2->base))));
518 }
519
520 /* Loop invariant expression hashtable entry. */
521
522 struct iv_inv_expr_ent
523 {
524 /* Tree expression of the entry. */
525 tree expr;
526 /* Unique indentifier. */
527 int id;
528 /* Hash value. */
529 hashval_t hash;
530 };
531
532 /* Sort iv_inv_expr_ent pair A and B by id field. */
533
534 static int
535 sort_iv_inv_expr_ent (const void *a, const void *b)
536 {
537 const iv_inv_expr_ent * const *e1 = (const iv_inv_expr_ent * const *) (a);
538 const iv_inv_expr_ent * const *e2 = (const iv_inv_expr_ent * const *) (b);
539
540 unsigned id1 = (*e1)->id;
541 unsigned id2 = (*e2)->id;
542
543 if (id1 < id2)
544 return -1;
545 else if (id1 > id2)
546 return 1;
547 else
548 return 0;
549 }
550
551 /* Hashtable helpers. */
552
553 struct iv_inv_expr_hasher : free_ptr_hash <iv_inv_expr_ent>
554 {
555 static inline hashval_t hash (const iv_inv_expr_ent *);
556 static inline bool equal (const iv_inv_expr_ent *, const iv_inv_expr_ent *);
557 };
558
559 /* Return true if uses of type TYPE represent some form of address. */
560
561 inline bool
562 address_p (use_type type)
563 {
564 return type == USE_REF_ADDRESS || type == USE_PTR_ADDRESS;
565 }
566
567 /* Hash function for loop invariant expressions. */
568
569 inline hashval_t
570 iv_inv_expr_hasher::hash (const iv_inv_expr_ent *expr)
571 {
572 return expr->hash;
573 }
574
575 /* Hash table equality function for expressions. */
576
577 inline bool
578 iv_inv_expr_hasher::equal (const iv_inv_expr_ent *expr1,
579 const iv_inv_expr_ent *expr2)
580 {
581 return expr1->hash == expr2->hash
582 && operand_equal_p (expr1->expr, expr2->expr, 0);
583 }
584
585 struct ivopts_data
586 {
587 /* The currently optimized loop. */
588 class loop *current_loop;
589 location_t loop_loc;
590
591 /* Numbers of iterations for all exits of the current loop. */
592 hash_map<edge, tree_niter_desc *> *niters;
593
594 /* Number of registers used in it. */
595 unsigned regs_used;
596
597 /* The size of version_info array allocated. */
598 unsigned version_info_size;
599
600 /* The array of information for the ssa names. */
601 struct version_info *version_info;
602
603 /* The hashtable of loop invariant expressions created
604 by ivopt. */
605 hash_table<iv_inv_expr_hasher> *inv_expr_tab;
606
607 /* The bitmap of indices in version_info whose value was changed. */
608 bitmap relevant;
609
610 /* The uses of induction variables. */
611 vec<iv_group *> vgroups;
612
613 /* The candidates. */
614 vec<iv_cand *> vcands;
615
616 /* A bitmap of important candidates. */
617 bitmap important_candidates;
618
619 /* Cache used by tree_to_aff_combination_expand. */
620 hash_map<tree, name_expansion *> *name_expansion_cache;
621
622 /* The hashtable of common candidates derived from iv uses. */
623 hash_table<iv_common_cand_hasher> *iv_common_cand_tab;
624
625 /* The common candidates. */
626 vec<iv_common_cand *> iv_common_cands;
627
628 /* Hash map recording base object information of tree exp. */
629 hash_map<tree, tree> *base_object_map;
630
631 /* The maximum invariant variable id. */
632 unsigned max_inv_var_id;
633
634 /* The maximum invariant expression id. */
635 unsigned max_inv_expr_id;
636
637 /* Number of no_overflow BIVs which are not used in memory address. */
638 unsigned bivs_not_used_in_addr;
639
640 /* Obstack for iv structure. */
641 struct obstack iv_obstack;
642
643 /* Whether to consider just related and important candidates when replacing a
644 use. */
645 bool consider_all_candidates;
646
647 /* Are we optimizing for speed? */
648 bool speed;
649
650 /* Whether the loop body includes any function calls. */
651 bool body_includes_call;
652
653 /* Whether the loop body can only be exited via single exit. */
654 bool loop_single_exit_p;
655
656 /* Whether the loop has doloop comparison use. */
657 bool doloop_use_p;
658 };
659
660 /* An assignment of iv candidates to uses. */
661
662 class iv_ca
663 {
664 public:
665 /* The number of uses covered by the assignment. */
666 unsigned upto;
667
668 /* Number of uses that cannot be expressed by the candidates in the set. */
669 unsigned bad_groups;
670
671 /* Candidate assigned to a use, together with the related costs. */
672 class cost_pair **cand_for_group;
673
674 /* Number of times each candidate is used. */
675 unsigned *n_cand_uses;
676
677 /* The candidates used. */
678 bitmap cands;
679
680 /* The number of candidates in the set. */
681 unsigned n_cands;
682
683 /* The number of invariants needed, including both invariant variants and
684 invariant expressions. */
685 unsigned n_invs;
686
687 /* Total cost of expressing uses. */
688 comp_cost cand_use_cost;
689
690 /* Total cost of candidates. */
691 int64_t cand_cost;
692
693 /* Number of times each invariant variable is used. */
694 unsigned *n_inv_var_uses;
695
696 /* Number of times each invariant expression is used. */
697 unsigned *n_inv_expr_uses;
698
699 /* Total cost of the assignment. */
700 comp_cost cost;
701 };
702
703 /* Difference of two iv candidate assignments. */
704
705 struct iv_ca_delta
706 {
707 /* Changed group. */
708 struct iv_group *group;
709
710 /* An old assignment (for rollback purposes). */
711 class cost_pair *old_cp;
712
713 /* A new assignment. */
714 class cost_pair *new_cp;
715
716 /* Next change in the list. */
717 struct iv_ca_delta *next;
718 };
719
720 /* Bound on number of candidates below that all candidates are considered. */
721
722 #define CONSIDER_ALL_CANDIDATES_BOUND \
723 ((unsigned) param_iv_consider_all_candidates_bound)
724
725 /* If there are more iv occurrences, we just give up (it is quite unlikely that
726 optimizing such a loop would help, and it would take ages). */
727
728 #define MAX_CONSIDERED_GROUPS \
729 ((unsigned) param_iv_max_considered_uses)
730
731 /* If there are at most this number of ivs in the set, try removing unnecessary
732 ivs from the set always. */
733
734 #define ALWAYS_PRUNE_CAND_SET_BOUND \
735 ((unsigned) param_iv_always_prune_cand_set_bound)
736
737 /* The list of trees for that the decl_rtl field must be reset is stored
738 here. */
739
740 static vec<tree> decl_rtl_to_reset;
741
742 static comp_cost force_expr_to_var_cost (tree, bool);
743
744 /* The single loop exit if it dominates the latch, NULL otherwise. */
745
746 edge
747 single_dom_exit (class loop *loop)
748 {
749 edge exit = single_exit (loop);
750
751 if (!exit)
752 return NULL;
753
754 if (!just_once_each_iteration_p (loop, exit->src))
755 return NULL;
756
757 return exit;
758 }
759
760 /* Dumps information about the induction variable IV to FILE. Don't dump
761 variable's name if DUMP_NAME is FALSE. The information is dumped with
762 preceding spaces indicated by INDENT_LEVEL. */
763
764 void
765 dump_iv (FILE *file, struct iv *iv, bool dump_name, unsigned indent_level)
766 {
767 const char *p;
768 const char spaces[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
769
770 if (indent_level > 4)
771 indent_level = 4;
772 p = spaces + 8 - (indent_level << 1);
773
774 fprintf (file, "%sIV struct:\n", p);
775 if (iv->ssa_name && dump_name)
776 {
777 fprintf (file, "%s SSA_NAME:\t", p);
778 print_generic_expr (file, iv->ssa_name, TDF_SLIM);
779 fprintf (file, "\n");
780 }
781
782 fprintf (file, "%s Type:\t", p);
783 print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
784 fprintf (file, "\n");
785
786 fprintf (file, "%s Base:\t", p);
787 print_generic_expr (file, iv->base, TDF_SLIM);
788 fprintf (file, "\n");
789
790 fprintf (file, "%s Step:\t", p);
791 print_generic_expr (file, iv->step, TDF_SLIM);
792 fprintf (file, "\n");
793
794 if (iv->base_object)
795 {
796 fprintf (file, "%s Object:\t", p);
797 print_generic_expr (file, iv->base_object, TDF_SLIM);
798 fprintf (file, "\n");
799 }
800
801 fprintf (file, "%s Biv:\t%c\n", p, iv->biv_p ? 'Y' : 'N');
802
803 fprintf (file, "%s Overflowness wrto loop niter:\t%s\n",
804 p, iv->no_overflow ? "No-overflow" : "Overflow");
805 }
806
807 /* Dumps information about the USE to FILE. */
808
809 void
810 dump_use (FILE *file, struct iv_use *use)
811 {
812 fprintf (file, " Use %d.%d:\n", use->group_id, use->id);
813 fprintf (file, " At stmt:\t");
814 print_gimple_stmt (file, use->stmt, 0);
815 fprintf (file, " At pos:\t");
816 if (use->op_p)
817 print_generic_expr (file, *use->op_p, TDF_SLIM);
818 fprintf (file, "\n");
819 dump_iv (file, use->iv, false, 2);
820 }
821
822 /* Dumps information about the uses to FILE. */
823
824 void
825 dump_groups (FILE *file, struct ivopts_data *data)
826 {
827 unsigned i, j;
828 struct iv_group *group;
829
830 for (i = 0; i < data->vgroups.length (); i++)
831 {
832 group = data->vgroups[i];
833 fprintf (file, "Group %d:\n", group->id);
834 if (group->type == USE_NONLINEAR_EXPR)
835 fprintf (file, " Type:\tGENERIC\n");
836 else if (group->type == USE_REF_ADDRESS)
837 fprintf (file, " Type:\tREFERENCE ADDRESS\n");
838 else if (group->type == USE_PTR_ADDRESS)
839 fprintf (file, " Type:\tPOINTER ARGUMENT ADDRESS\n");
840 else
841 {
842 gcc_assert (group->type == USE_COMPARE);
843 fprintf (file, " Type:\tCOMPARE\n");
844 }
845 for (j = 0; j < group->vuses.length (); j++)
846 dump_use (file, group->vuses[j]);
847 }
848 }
849
850 /* Dumps information about induction variable candidate CAND to FILE. */
851
852 void
853 dump_cand (FILE *file, struct iv_cand *cand)
854 {
855 struct iv *iv = cand->iv;
856
857 fprintf (file, "Candidate %d:\n", cand->id);
858 if (cand->inv_vars)
859 {
860 fprintf (file, " Depend on inv.vars: ");
861 dump_bitmap (file, cand->inv_vars);
862 }
863 if (cand->inv_exprs)
864 {
865 fprintf (file, " Depend on inv.exprs: ");
866 dump_bitmap (file, cand->inv_exprs);
867 }
868
869 if (cand->var_before)
870 {
871 fprintf (file, " Var befor: ");
872 print_generic_expr (file, cand->var_before, TDF_SLIM);
873 fprintf (file, "\n");
874 }
875 if (cand->var_after)
876 {
877 fprintf (file, " Var after: ");
878 print_generic_expr (file, cand->var_after, TDF_SLIM);
879 fprintf (file, "\n");
880 }
881
882 switch (cand->pos)
883 {
884 case IP_NORMAL:
885 fprintf (file, " Incr POS: before exit test\n");
886 break;
887
888 case IP_BEFORE_USE:
889 fprintf (file, " Incr POS: before use %d\n", cand->ainc_use->id);
890 break;
891
892 case IP_AFTER_USE:
893 fprintf (file, " Incr POS: after use %d\n", cand->ainc_use->id);
894 break;
895
896 case IP_END:
897 fprintf (file, " Incr POS: at end\n");
898 break;
899
900 case IP_ORIGINAL:
901 fprintf (file, " Incr POS: orig biv\n");
902 break;
903 }
904
905 dump_iv (file, iv, false, 1);
906 }
907
908 /* Returns the info for ssa version VER. */
909
910 static inline struct version_info *
911 ver_info (struct ivopts_data *data, unsigned ver)
912 {
913 return data->version_info + ver;
914 }
915
916 /* Returns the info for ssa name NAME. */
917
918 static inline struct version_info *
919 name_info (struct ivopts_data *data, tree name)
920 {
921 return ver_info (data, SSA_NAME_VERSION (name));
922 }
923
924 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
925 emitted in LOOP. */
926
927 static bool
928 stmt_after_ip_normal_pos (class loop *loop, gimple *stmt)
929 {
930 basic_block bb = ip_normal_pos (loop), sbb = gimple_bb (stmt);
931
932 gcc_assert (bb);
933
934 if (sbb == loop->latch)
935 return true;
936
937 if (sbb != bb)
938 return false;
939
940 return stmt == last_nondebug_stmt (bb);
941 }
942
943 /* Returns true if STMT if after the place where the original induction
944 variable CAND is incremented. If TRUE_IF_EQUAL is set, we return true
945 if the positions are identical. */
946
947 static bool
948 stmt_after_inc_pos (struct iv_cand *cand, gimple *stmt, bool true_if_equal)
949 {
950 basic_block cand_bb = gimple_bb (cand->incremented_at);
951 basic_block stmt_bb = gimple_bb (stmt);
952
953 if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
954 return false;
955
956 if (stmt_bb != cand_bb)
957 return true;
958
959 if (true_if_equal
960 && gimple_uid (stmt) == gimple_uid (cand->incremented_at))
961 return true;
962 return gimple_uid (stmt) > gimple_uid (cand->incremented_at);
963 }
964
965 /* Returns true if STMT if after the place where the induction variable
966 CAND is incremented in LOOP. */
967
968 static bool
969 stmt_after_increment (class loop *loop, struct iv_cand *cand, gimple *stmt)
970 {
971 switch (cand->pos)
972 {
973 case IP_END:
974 return false;
975
976 case IP_NORMAL:
977 return stmt_after_ip_normal_pos (loop, stmt);
978
979 case IP_ORIGINAL:
980 case IP_AFTER_USE:
981 return stmt_after_inc_pos (cand, stmt, false);
982
983 case IP_BEFORE_USE:
984 return stmt_after_inc_pos (cand, stmt, true);
985
986 default:
987 gcc_unreachable ();
988 }
989 }
990
991 /* walk_tree callback for contains_abnormal_ssa_name_p. */
992
993 static tree
994 contains_abnormal_ssa_name_p_1 (tree *tp, int *walk_subtrees, void *)
995 {
996 if (TREE_CODE (*tp) == SSA_NAME
997 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (*tp))
998 return *tp;
999
1000 if (!EXPR_P (*tp))
1001 *walk_subtrees = 0;
1002
1003 return NULL_TREE;
1004 }
1005
1006 /* Returns true if EXPR contains a ssa name that occurs in an
1007 abnormal phi node. */
1008
1009 bool
1010 contains_abnormal_ssa_name_p (tree expr)
1011 {
1012 return walk_tree_without_duplicates
1013 (&expr, contains_abnormal_ssa_name_p_1, NULL) != NULL_TREE;
1014 }
1015
1016 /* Returns the structure describing number of iterations determined from
1017 EXIT of DATA->current_loop, or NULL if something goes wrong. */
1018
1019 static class tree_niter_desc *
1020 niter_for_exit (struct ivopts_data *data, edge exit)
1021 {
1022 class tree_niter_desc *desc;
1023 tree_niter_desc **slot;
1024
1025 if (!data->niters)
1026 {
1027 data->niters = new hash_map<edge, tree_niter_desc *>;
1028 slot = NULL;
1029 }
1030 else
1031 slot = data->niters->get (exit);
1032
1033 if (!slot)
1034 {
1035 /* Try to determine number of iterations. We cannot safely work with ssa
1036 names that appear in phi nodes on abnormal edges, so that we do not
1037 create overlapping life ranges for them (PR 27283). */
1038 desc = XNEW (class tree_niter_desc);
1039 ::new (static_cast<void*> (desc)) tree_niter_desc ();
1040 if (!number_of_iterations_exit (data->current_loop,
1041 exit, desc, true)
1042 || contains_abnormal_ssa_name_p (desc->niter))
1043 {
1044 desc->~tree_niter_desc ();
1045 XDELETE (desc);
1046 desc = NULL;
1047 }
1048 data->niters->put (exit, desc);
1049 }
1050 else
1051 desc = *slot;
1052
1053 return desc;
1054 }
1055
1056 /* Returns the structure describing number of iterations determined from
1057 single dominating exit of DATA->current_loop, or NULL if something
1058 goes wrong. */
1059
1060 static class tree_niter_desc *
1061 niter_for_single_dom_exit (struct ivopts_data *data)
1062 {
1063 edge exit = single_dom_exit (data->current_loop);
1064
1065 if (!exit)
1066 return NULL;
1067
1068 return niter_for_exit (data, exit);
1069 }
1070
1071 /* Initializes data structures used by the iv optimization pass, stored
1072 in DATA. */
1073
1074 static void
1075 tree_ssa_iv_optimize_init (struct ivopts_data *data)
1076 {
1077 data->version_info_size = 2 * num_ssa_names;
1078 data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
1079 data->relevant = BITMAP_ALLOC (NULL);
1080 data->important_candidates = BITMAP_ALLOC (NULL);
1081 data->max_inv_var_id = 0;
1082 data->max_inv_expr_id = 0;
1083 data->niters = NULL;
1084 data->vgroups.create (20);
1085 data->vcands.create (20);
1086 data->inv_expr_tab = new hash_table<iv_inv_expr_hasher> (10);
1087 data->name_expansion_cache = NULL;
1088 data->base_object_map = NULL;
1089 data->iv_common_cand_tab = new hash_table<iv_common_cand_hasher> (10);
1090 data->iv_common_cands.create (20);
1091 decl_rtl_to_reset.create (20);
1092 gcc_obstack_init (&data->iv_obstack);
1093 }
1094
1095 /* walk_tree callback for determine_base_object. */
1096
1097 static tree
1098 determine_base_object_1 (tree *tp, int *walk_subtrees, void *wdata)
1099 {
1100 tree_code code = TREE_CODE (*tp);
1101 tree obj = NULL_TREE;
1102 if (code == ADDR_EXPR)
1103 {
1104 tree base = get_base_address (TREE_OPERAND (*tp, 0));
1105 if (!base)
1106 obj = *tp;
1107 else if (TREE_CODE (base) != MEM_REF)
1108 obj = fold_convert (ptr_type_node, build_fold_addr_expr (base));
1109 }
1110 else if (code == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (*tp)))
1111 obj = fold_convert (ptr_type_node, *tp);
1112
1113 if (!obj)
1114 {
1115 if (!EXPR_P (*tp))
1116 *walk_subtrees = 0;
1117
1118 return NULL_TREE;
1119 }
1120 /* Record special node for multiple base objects and stop. */
1121 if (*static_cast<tree *> (wdata))
1122 {
1123 *static_cast<tree *> (wdata) = integer_zero_node;
1124 return integer_zero_node;
1125 }
1126 /* Record the base object and continue looking. */
1127 *static_cast<tree *> (wdata) = obj;
1128 return NULL_TREE;
1129 }
1130
1131 /* Returns a memory object to that EXPR points with caching. Return NULL if we
1132 are able to determine that it does not point to any such object; specially
1133 return integer_zero_node if EXPR contains multiple base objects. */
1134
1135 static tree
1136 determine_base_object (struct ivopts_data *data, tree expr)
1137 {
1138 tree *slot, obj = NULL_TREE;
1139 if (data->base_object_map)
1140 {
1141 if ((slot = data->base_object_map->get(expr)) != NULL)
1142 return *slot;
1143 }
1144 else
1145 data->base_object_map = new hash_map<tree, tree>;
1146
1147 (void) walk_tree_without_duplicates (&expr, determine_base_object_1, &obj);
1148 data->base_object_map->put (expr, obj);
1149 return obj;
1150 }
1151
1152 /* Allocates an induction variable with given initial value BASE and step STEP
1153 for loop LOOP. NO_OVERFLOW implies the iv doesn't overflow. */
1154
1155 static struct iv *
1156 alloc_iv (struct ivopts_data *data, tree base, tree step,
1157 bool no_overflow = false)
1158 {
1159 tree expr = base;
1160 struct iv *iv = (struct iv*) obstack_alloc (&data->iv_obstack,
1161 sizeof (struct iv));
1162 gcc_assert (step != NULL_TREE);
1163
1164 /* Canonicalize the address expression in base if it were an unsigned
1165 computation. That leads to more equalities being detected and results in:
1166
1167 1) More accurate cost can be computed for address expressions;
1168 2) Duplicate candidates won't be created for bases in different
1169 forms, like &a[0] and &a.
1170 3) Duplicate candidates won't be created for IV expressions that differ
1171 only in their sign. */
1172 aff_tree comb;
1173 STRIP_NOPS (expr);
1174 expr = fold_convert (unsigned_type_for (TREE_TYPE (expr)), expr);
1175 tree_to_aff_combination (expr, TREE_TYPE (expr), &comb);
1176 base = fold_convert (TREE_TYPE (base), aff_combination_to_tree (&comb));
1177
1178 iv->base = base;
1179 iv->base_object = determine_base_object (data, base);
1180 iv->step = step;
1181 iv->biv_p = false;
1182 iv->nonlin_use = NULL;
1183 iv->ssa_name = NULL_TREE;
1184 if (!no_overflow
1185 && !iv_can_overflow_p (data->current_loop, TREE_TYPE (base),
1186 base, step))
1187 no_overflow = true;
1188 iv->no_overflow = no_overflow;
1189 iv->have_address_use = false;
1190
1191 return iv;
1192 }
1193
1194 /* Sets STEP and BASE for induction variable IV. NO_OVERFLOW implies the IV
1195 doesn't overflow. */
1196
1197 static void
1198 set_iv (struct ivopts_data *data, tree iv, tree base, tree step,
1199 bool no_overflow)
1200 {
1201 struct version_info *info = name_info (data, iv);
1202
1203 gcc_assert (!info->iv);
1204
1205 bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
1206 info->iv = alloc_iv (data, base, step, no_overflow);
1207 info->iv->ssa_name = iv;
1208 }
1209
1210 /* Finds induction variable declaration for VAR. */
1211
1212 static struct iv *
1213 get_iv (struct ivopts_data *data, tree var)
1214 {
1215 basic_block bb;
1216 tree type = TREE_TYPE (var);
1217
1218 if (!POINTER_TYPE_P (type)
1219 && !INTEGRAL_TYPE_P (type))
1220 return NULL;
1221
1222 if (!name_info (data, var)->iv)
1223 {
1224 bb = gimple_bb (SSA_NAME_DEF_STMT (var));
1225
1226 if (!bb
1227 || !flow_bb_inside_loop_p (data->current_loop, bb))
1228 {
1229 if (POINTER_TYPE_P (type))
1230 type = sizetype;
1231 set_iv (data, var, var, build_int_cst (type, 0), true);
1232 }
1233 }
1234
1235 return name_info (data, var)->iv;
1236 }
1237
1238 /* Return the first non-invariant ssa var found in EXPR. */
1239
1240 static tree
1241 extract_single_var_from_expr (tree expr)
1242 {
1243 int i, n;
1244 tree tmp;
1245 enum tree_code code;
1246
1247 if (!expr || is_gimple_min_invariant (expr))
1248 return NULL;
1249
1250 code = TREE_CODE (expr);
1251 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1252 {
1253 n = TREE_OPERAND_LENGTH (expr);
1254 for (i = 0; i < n; i++)
1255 {
1256 tmp = extract_single_var_from_expr (TREE_OPERAND (expr, i));
1257
1258 if (tmp)
1259 return tmp;
1260 }
1261 }
1262 return (TREE_CODE (expr) == SSA_NAME) ? expr : NULL;
1263 }
1264
1265 /* Finds basic ivs. */
1266
1267 static bool
1268 find_bivs (struct ivopts_data *data)
1269 {
1270 gphi *phi;
1271 affine_iv iv;
1272 tree step, type, base, stop;
1273 bool found = false;
1274 class loop *loop = data->current_loop;
1275 gphi_iterator psi;
1276
1277 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1278 {
1279 phi = psi.phi ();
1280
1281 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
1282 continue;
1283
1284 if (virtual_operand_p (PHI_RESULT (phi)))
1285 continue;
1286
1287 if (!simple_iv (loop, loop, PHI_RESULT (phi), &iv, true))
1288 continue;
1289
1290 if (integer_zerop (iv.step))
1291 continue;
1292
1293 step = iv.step;
1294 base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1295 /* Stop expanding iv base at the first ssa var referred by iv step.
1296 Ideally we should stop at any ssa var, because that's expensive
1297 and unusual to happen, we just do it on the first one.
1298
1299 See PR64705 for the rationale. */
1300 stop = extract_single_var_from_expr (step);
1301 base = expand_simple_operations (base, stop);
1302 if (contains_abnormal_ssa_name_p (base)
1303 || contains_abnormal_ssa_name_p (step))
1304 continue;
1305
1306 type = TREE_TYPE (PHI_RESULT (phi));
1307 base = fold_convert (type, base);
1308 if (step)
1309 {
1310 if (POINTER_TYPE_P (type))
1311 step = convert_to_ptrofftype (step);
1312 else
1313 step = fold_convert (type, step);
1314 }
1315
1316 set_iv (data, PHI_RESULT (phi), base, step, iv.no_overflow);
1317 found = true;
1318 }
1319
1320 return found;
1321 }
1322
1323 /* Marks basic ivs. */
1324
1325 static void
1326 mark_bivs (struct ivopts_data *data)
1327 {
1328 gphi *phi;
1329 gimple *def;
1330 tree var;
1331 struct iv *iv, *incr_iv;
1332 class loop *loop = data->current_loop;
1333 basic_block incr_bb;
1334 gphi_iterator psi;
1335
1336 data->bivs_not_used_in_addr = 0;
1337 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
1338 {
1339 phi = psi.phi ();
1340
1341 iv = get_iv (data, PHI_RESULT (phi));
1342 if (!iv)
1343 continue;
1344
1345 var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1346 def = SSA_NAME_DEF_STMT (var);
1347 /* Don't mark iv peeled from other one as biv. */
1348 if (def
1349 && gimple_code (def) == GIMPLE_PHI
1350 && gimple_bb (def) == loop->header)
1351 continue;
1352
1353 incr_iv = get_iv (data, var);
1354 if (!incr_iv)
1355 continue;
1356
1357 /* If the increment is in the subloop, ignore it. */
1358 incr_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
1359 if (incr_bb->loop_father != data->current_loop
1360 || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
1361 continue;
1362
1363 iv->biv_p = true;
1364 incr_iv->biv_p = true;
1365 if (iv->no_overflow)
1366 data->bivs_not_used_in_addr++;
1367 if (incr_iv->no_overflow)
1368 data->bivs_not_used_in_addr++;
1369 }
1370 }
1371
1372 /* Checks whether STMT defines a linear induction variable and stores its
1373 parameters to IV. */
1374
1375 static bool
1376 find_givs_in_stmt_scev (struct ivopts_data *data, gimple *stmt, affine_iv *iv)
1377 {
1378 tree lhs, stop;
1379 class loop *loop = data->current_loop;
1380
1381 iv->base = NULL_TREE;
1382 iv->step = NULL_TREE;
1383
1384 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1385 return false;
1386
1387 lhs = gimple_assign_lhs (stmt);
1388 if (TREE_CODE (lhs) != SSA_NAME)
1389 return false;
1390
1391 if (!simple_iv (loop, loop_containing_stmt (stmt), lhs, iv, true))
1392 return false;
1393
1394 /* Stop expanding iv base at the first ssa var referred by iv step.
1395 Ideally we should stop at any ssa var, because that's expensive
1396 and unusual to happen, we just do it on the first one.
1397
1398 See PR64705 for the rationale. */
1399 stop = extract_single_var_from_expr (iv->step);
1400 iv->base = expand_simple_operations (iv->base, stop);
1401 if (contains_abnormal_ssa_name_p (iv->base)
1402 || contains_abnormal_ssa_name_p (iv->step))
1403 return false;
1404
1405 /* If STMT could throw, then do not consider STMT as defining a GIV.
1406 While this will suppress optimizations, we cannot safely delete this
1407 GIV and associated statements, even if it appears it is not used. */
1408 if (stmt_could_throw_p (cfun, stmt))
1409 return false;
1410
1411 return true;
1412 }
1413
1414 /* Finds general ivs in statement STMT. */
1415
1416 static void
1417 find_givs_in_stmt (struct ivopts_data *data, gimple *stmt)
1418 {
1419 affine_iv iv;
1420
1421 if (!find_givs_in_stmt_scev (data, stmt, &iv))
1422 return;
1423
1424 set_iv (data, gimple_assign_lhs (stmt), iv.base, iv.step, iv.no_overflow);
1425 }
1426
1427 /* Finds general ivs in basic block BB. */
1428
1429 static void
1430 find_givs_in_bb (struct ivopts_data *data, basic_block bb)
1431 {
1432 gimple_stmt_iterator bsi;
1433
1434 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1435 if (!is_gimple_debug (gsi_stmt (bsi)))
1436 find_givs_in_stmt (data, gsi_stmt (bsi));
1437 }
1438
1439 /* Finds general ivs. */
1440
1441 static void
1442 find_givs (struct ivopts_data *data, basic_block *body)
1443 {
1444 class loop *loop = data->current_loop;
1445 unsigned i;
1446
1447 for (i = 0; i < loop->num_nodes; i++)
1448 find_givs_in_bb (data, body[i]);
1449 }
1450
1451 /* For each ssa name defined in LOOP determines whether it is an induction
1452 variable and if so, its initial value and step. */
1453
1454 static bool
1455 find_induction_variables (struct ivopts_data *data, basic_block *body)
1456 {
1457 unsigned i;
1458 bitmap_iterator bi;
1459
1460 if (!find_bivs (data))
1461 return false;
1462
1463 find_givs (data, body);
1464 mark_bivs (data);
1465
1466 if (dump_file && (dump_flags & TDF_DETAILS))
1467 {
1468 class tree_niter_desc *niter = niter_for_single_dom_exit (data);
1469
1470 if (niter)
1471 {
1472 fprintf (dump_file, " number of iterations ");
1473 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1474 if (!integer_zerop (niter->may_be_zero))
1475 {
1476 fprintf (dump_file, "; zero if ");
1477 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1478 }
1479 fprintf (dump_file, "\n");
1480 };
1481
1482 fprintf (dump_file, "\n<Induction Vars>:\n");
1483 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1484 {
1485 struct version_info *info = ver_info (data, i);
1486 if (info->iv && info->iv->step && !integer_zerop (info->iv->step))
1487 dump_iv (dump_file, ver_info (data, i)->iv, true, 0);
1488 }
1489 }
1490
1491 return true;
1492 }
1493
1494 /* Records a use of TYPE at *USE_P in STMT whose value is IV in GROUP.
1495 For address type use, ADDR_BASE is the stripped IV base, ADDR_OFFSET
1496 is the const offset stripped from IV base and MEM_TYPE is the type
1497 of the memory being addressed. For uses of other types, ADDR_BASE
1498 and ADDR_OFFSET are zero by default and MEM_TYPE is NULL_TREE. */
1499
1500 static struct iv_use *
1501 record_use (struct iv_group *group, tree *use_p, struct iv *iv,
1502 gimple *stmt, enum use_type type, tree mem_type,
1503 tree addr_base, poly_uint64 addr_offset)
1504 {
1505 struct iv_use *use = XCNEW (struct iv_use);
1506
1507 use->id = group->vuses.length ();
1508 use->group_id = group->id;
1509 use->type = type;
1510 use->mem_type = mem_type;
1511 use->iv = iv;
1512 use->stmt = stmt;
1513 use->op_p = use_p;
1514 use->addr_base = addr_base;
1515 use->addr_offset = addr_offset;
1516
1517 group->vuses.safe_push (use);
1518 return use;
1519 }
1520
1521 /* Checks whether OP is a loop-level invariant and if so, records it.
1522 NONLINEAR_USE is true if the invariant is used in a way we do not
1523 handle specially. */
1524
1525 static void
1526 record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
1527 {
1528 basic_block bb;
1529 struct version_info *info;
1530
1531 if (TREE_CODE (op) != SSA_NAME
1532 || virtual_operand_p (op))
1533 return;
1534
1535 bb = gimple_bb (SSA_NAME_DEF_STMT (op));
1536 if (bb
1537 && flow_bb_inside_loop_p (data->current_loop, bb))
1538 return;
1539
1540 info = name_info (data, op);
1541 info->name = op;
1542 info->has_nonlin_use |= nonlinear_use;
1543 if (!info->inv_id)
1544 info->inv_id = ++data->max_inv_var_id;
1545 bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
1546 }
1547
1548 /* Record a group of TYPE. */
1549
1550 static struct iv_group *
1551 record_group (struct ivopts_data *data, enum use_type type)
1552 {
1553 struct iv_group *group = XCNEW (struct iv_group);
1554
1555 group->id = data->vgroups.length ();
1556 group->type = type;
1557 group->related_cands = BITMAP_ALLOC (NULL);
1558 group->vuses.create (1);
1559 group->doloop_p = false;
1560
1561 data->vgroups.safe_push (group);
1562 return group;
1563 }
1564
1565 /* Record a use of TYPE at *USE_P in STMT whose value is IV in a group.
1566 New group will be created if there is no existing group for the use.
1567 MEM_TYPE is the type of memory being addressed, or NULL if this
1568 isn't an address reference. */
1569
1570 static struct iv_use *
1571 record_group_use (struct ivopts_data *data, tree *use_p,
1572 struct iv *iv, gimple *stmt, enum use_type type,
1573 tree mem_type)
1574 {
1575 tree addr_base = NULL;
1576 struct iv_group *group = NULL;
1577 poly_uint64 addr_offset = 0;
1578
1579 /* Record non address type use in a new group. */
1580 if (address_p (type))
1581 {
1582 unsigned int i;
1583
1584 gcc_assert (POINTER_TYPE_P (TREE_TYPE (iv->base)));
1585 tree addr_toffset;
1586 split_constant_offset (iv->base, &addr_base, &addr_toffset);
1587 addr_offset = int_cst_value (addr_toffset);
1588 for (i = 0; i < data->vgroups.length (); i++)
1589 {
1590 struct iv_use *use;
1591
1592 group = data->vgroups[i];
1593 use = group->vuses[0];
1594 if (!address_p (use->type))
1595 continue;
1596
1597 /* Check if it has the same stripped base and step. */
1598 if (operand_equal_p (iv->base_object, use->iv->base_object, 0)
1599 && operand_equal_p (iv->step, use->iv->step, OEP_ASSUME_WRAPV)
1600 && operand_equal_p (addr_base, use->addr_base, OEP_ASSUME_WRAPV))
1601 break;
1602 }
1603 if (i == data->vgroups.length ())
1604 group = NULL;
1605 }
1606
1607 if (!group)
1608 group = record_group (data, type);
1609
1610 return record_use (group, use_p, iv, stmt, type, mem_type,
1611 addr_base, addr_offset);
1612 }
1613
1614 /* Checks whether the use OP is interesting and if so, records it. */
1615
1616 static struct iv_use *
1617 find_interesting_uses_op (struct ivopts_data *data, tree op)
1618 {
1619 struct iv *iv;
1620 gimple *stmt;
1621 struct iv_use *use;
1622
1623 if (TREE_CODE (op) != SSA_NAME)
1624 return NULL;
1625
1626 iv = get_iv (data, op);
1627 if (!iv)
1628 return NULL;
1629
1630 if (iv->nonlin_use)
1631 {
1632 gcc_assert (iv->nonlin_use->type == USE_NONLINEAR_EXPR);
1633 return iv->nonlin_use;
1634 }
1635
1636 if (integer_zerop (iv->step))
1637 {
1638 record_invariant (data, op, true);
1639 return NULL;
1640 }
1641
1642 stmt = SSA_NAME_DEF_STMT (op);
1643 gcc_assert (gimple_code (stmt) == GIMPLE_PHI || is_gimple_assign (stmt));
1644
1645 use = record_group_use (data, NULL, iv, stmt, USE_NONLINEAR_EXPR, NULL_TREE);
1646 iv->nonlin_use = use;
1647 return use;
1648 }
1649
1650 /* Indicate how compare type iv_use can be handled. */
1651 enum comp_iv_rewrite
1652 {
1653 COMP_IV_NA,
1654 /* We may rewrite compare type iv_use by expressing value of the iv_use. */
1655 COMP_IV_EXPR,
1656 /* We may rewrite compare type iv_uses on both sides of comparison by
1657 expressing value of each iv_use. */
1658 COMP_IV_EXPR_2,
1659 /* We may rewrite compare type iv_use by expressing value of the iv_use
1660 or by eliminating it with other iv_cand. */
1661 COMP_IV_ELIM
1662 };
1663
1664 /* Given a condition in statement STMT, checks whether it is a compare
1665 of an induction variable and an invariant. If this is the case,
1666 CONTROL_VAR is set to location of the iv, BOUND to the location of
1667 the invariant, IV_VAR and IV_BOUND are set to the corresponding
1668 induction variable descriptions, and true is returned. If this is not
1669 the case, CONTROL_VAR and BOUND are set to the arguments of the
1670 condition and false is returned. */
1671
1672 static enum comp_iv_rewrite
1673 extract_cond_operands (struct ivopts_data *data, gimple *stmt,
1674 tree **control_var, tree **bound,
1675 struct iv **iv_var, struct iv **iv_bound)
1676 {
1677 /* The objects returned when COND has constant operands. */
1678 static struct iv const_iv;
1679 static tree zero;
1680 tree *op0 = &zero, *op1 = &zero;
1681 struct iv *iv0 = &const_iv, *iv1 = &const_iv;
1682 enum comp_iv_rewrite rewrite_type = COMP_IV_NA;
1683
1684 if (gimple_code (stmt) == GIMPLE_COND)
1685 {
1686 gcond *cond_stmt = as_a <gcond *> (stmt);
1687 op0 = gimple_cond_lhs_ptr (cond_stmt);
1688 op1 = gimple_cond_rhs_ptr (cond_stmt);
1689 }
1690 else
1691 {
1692 op0 = gimple_assign_rhs1_ptr (stmt);
1693 op1 = gimple_assign_rhs2_ptr (stmt);
1694 }
1695
1696 zero = integer_zero_node;
1697 const_iv.step = integer_zero_node;
1698
1699 if (TREE_CODE (*op0) == SSA_NAME)
1700 iv0 = get_iv (data, *op0);
1701 if (TREE_CODE (*op1) == SSA_NAME)
1702 iv1 = get_iv (data, *op1);
1703
1704 /* If both sides of comparison are IVs. We can express ivs on both end. */
1705 if (iv0 && iv1 && !integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1706 {
1707 rewrite_type = COMP_IV_EXPR_2;
1708 goto end;
1709 }
1710
1711 /* If none side of comparison is IV. */
1712 if ((!iv0 || integer_zerop (iv0->step))
1713 && (!iv1 || integer_zerop (iv1->step)))
1714 goto end;
1715
1716 /* Control variable may be on the other side. */
1717 if (!iv0 || integer_zerop (iv0->step))
1718 {
1719 std::swap (op0, op1);
1720 std::swap (iv0, iv1);
1721 }
1722 /* If one side is IV and the other side isn't loop invariant. */
1723 if (!iv1)
1724 rewrite_type = COMP_IV_EXPR;
1725 /* If one side is IV and the other side is loop invariant. */
1726 else if (!integer_zerop (iv0->step) && integer_zerop (iv1->step))
1727 rewrite_type = COMP_IV_ELIM;
1728
1729 end:
1730 if (control_var)
1731 *control_var = op0;
1732 if (iv_var)
1733 *iv_var = iv0;
1734 if (bound)
1735 *bound = op1;
1736 if (iv_bound)
1737 *iv_bound = iv1;
1738
1739 return rewrite_type;
1740 }
1741
1742 /* Checks whether the condition in STMT is interesting and if so,
1743 records it. */
1744
1745 static void
1746 find_interesting_uses_cond (struct ivopts_data *data, gimple *stmt)
1747 {
1748 tree *var_p, *bound_p;
1749 struct iv *var_iv, *bound_iv;
1750 enum comp_iv_rewrite ret;
1751
1752 ret = extract_cond_operands (data, stmt,
1753 &var_p, &bound_p, &var_iv, &bound_iv);
1754 if (ret == COMP_IV_NA)
1755 {
1756 find_interesting_uses_op (data, *var_p);
1757 find_interesting_uses_op (data, *bound_p);
1758 return;
1759 }
1760
1761 record_group_use (data, var_p, var_iv, stmt, USE_COMPARE, NULL_TREE);
1762 /* Record compare type iv_use for iv on the other side of comparison. */
1763 if (ret == COMP_IV_EXPR_2)
1764 record_group_use (data, bound_p, bound_iv, stmt, USE_COMPARE, NULL_TREE);
1765 }
1766
1767 /* Returns the outermost loop EXPR is obviously invariant in
1768 relative to the loop LOOP, i.e. if all its operands are defined
1769 outside of the returned loop. Returns NULL if EXPR is not
1770 even obviously invariant in LOOP. */
1771
1772 class loop *
1773 outermost_invariant_loop_for_expr (class loop *loop, tree expr)
1774 {
1775 basic_block def_bb;
1776 unsigned i, len;
1777
1778 if (is_gimple_min_invariant (expr))
1779 return current_loops->tree_root;
1780
1781 if (TREE_CODE (expr) == SSA_NAME)
1782 {
1783 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
1784 if (def_bb)
1785 {
1786 if (flow_bb_inside_loop_p (loop, def_bb))
1787 return NULL;
1788 return superloop_at_depth (loop,
1789 loop_depth (def_bb->loop_father) + 1);
1790 }
1791
1792 return current_loops->tree_root;
1793 }
1794
1795 if (!EXPR_P (expr))
1796 return NULL;
1797
1798 unsigned maxdepth = 0;
1799 len = TREE_OPERAND_LENGTH (expr);
1800 for (i = 0; i < len; i++)
1801 {
1802 class loop *ivloop;
1803 if (!TREE_OPERAND (expr, i))
1804 continue;
1805
1806 ivloop = outermost_invariant_loop_for_expr (loop, TREE_OPERAND (expr, i));
1807 if (!ivloop)
1808 return NULL;
1809 maxdepth = MAX (maxdepth, loop_depth (ivloop));
1810 }
1811
1812 return superloop_at_depth (loop, maxdepth);
1813 }
1814
1815 /* Returns true if expression EXPR is obviously invariant in LOOP,
1816 i.e. if all its operands are defined outside of the LOOP. LOOP
1817 should not be the function body. */
1818
1819 bool
1820 expr_invariant_in_loop_p (class loop *loop, tree expr)
1821 {
1822 basic_block def_bb;
1823 unsigned i, len;
1824
1825 gcc_assert (loop_depth (loop) > 0);
1826
1827 if (is_gimple_min_invariant (expr))
1828 return true;
1829
1830 if (TREE_CODE (expr) == SSA_NAME)
1831 {
1832 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
1833 if (def_bb
1834 && flow_bb_inside_loop_p (loop, def_bb))
1835 return false;
1836
1837 return true;
1838 }
1839
1840 if (!EXPR_P (expr))
1841 return false;
1842
1843 len = TREE_OPERAND_LENGTH (expr);
1844 for (i = 0; i < len; i++)
1845 if (TREE_OPERAND (expr, i)
1846 && !expr_invariant_in_loop_p (loop, TREE_OPERAND (expr, i)))
1847 return false;
1848
1849 return true;
1850 }
1851
1852 /* Given expression EXPR which computes inductive values with respect
1853 to loop recorded in DATA, this function returns biv from which EXPR
1854 is derived by tracing definition chains of ssa variables in EXPR. */
1855
1856 static struct iv*
1857 find_deriving_biv_for_expr (struct ivopts_data *data, tree expr)
1858 {
1859 struct iv *iv;
1860 unsigned i, n;
1861 tree e2, e1;
1862 enum tree_code code;
1863 gimple *stmt;
1864
1865 if (expr == NULL_TREE)
1866 return NULL;
1867
1868 if (is_gimple_min_invariant (expr))
1869 return NULL;
1870
1871 code = TREE_CODE (expr);
1872 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1873 {
1874 n = TREE_OPERAND_LENGTH (expr);
1875 for (i = 0; i < n; i++)
1876 {
1877 iv = find_deriving_biv_for_expr (data, TREE_OPERAND (expr, i));
1878 if (iv)
1879 return iv;
1880 }
1881 }
1882
1883 /* Stop if it's not ssa name. */
1884 if (code != SSA_NAME)
1885 return NULL;
1886
1887 iv = get_iv (data, expr);
1888 if (!iv || integer_zerop (iv->step))
1889 return NULL;
1890 else if (iv->biv_p)
1891 return iv;
1892
1893 stmt = SSA_NAME_DEF_STMT (expr);
1894 if (gphi *phi = dyn_cast <gphi *> (stmt))
1895 {
1896 ssa_op_iter iter;
1897 use_operand_p use_p;
1898 basic_block phi_bb = gimple_bb (phi);
1899
1900 /* Skip loop header PHI that doesn't define biv. */
1901 if (phi_bb->loop_father == data->current_loop)
1902 return NULL;
1903
1904 if (virtual_operand_p (gimple_phi_result (phi)))
1905 return NULL;
1906
1907 FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
1908 {
1909 tree use = USE_FROM_PTR (use_p);
1910 iv = find_deriving_biv_for_expr (data, use);
1911 if (iv)
1912 return iv;
1913 }
1914 return NULL;
1915 }
1916 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1917 return NULL;
1918
1919 e1 = gimple_assign_rhs1 (stmt);
1920 code = gimple_assign_rhs_code (stmt);
1921 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1922 return find_deriving_biv_for_expr (data, e1);
1923
1924 switch (code)
1925 {
1926 case MULT_EXPR:
1927 case PLUS_EXPR:
1928 case MINUS_EXPR:
1929 case POINTER_PLUS_EXPR:
1930 /* Increments, decrements and multiplications by a constant
1931 are simple. */
1932 e2 = gimple_assign_rhs2 (stmt);
1933 iv = find_deriving_biv_for_expr (data, e2);
1934 if (iv)
1935 return iv;
1936 gcc_fallthrough ();
1937
1938 CASE_CONVERT:
1939 /* Casts are simple. */
1940 return find_deriving_biv_for_expr (data, e1);
1941
1942 default:
1943 break;
1944 }
1945
1946 return NULL;
1947 }
1948
1949 /* Record BIV, its predecessor and successor that they are used in
1950 address type uses. */
1951
1952 static void
1953 record_biv_for_address_use (struct ivopts_data *data, struct iv *biv)
1954 {
1955 unsigned i;
1956 tree type, base_1, base_2;
1957 bitmap_iterator bi;
1958
1959 if (!biv || !biv->biv_p || integer_zerop (biv->step)
1960 || biv->have_address_use || !biv->no_overflow)
1961 return;
1962
1963 type = TREE_TYPE (biv->base);
1964 if (!INTEGRAL_TYPE_P (type))
1965 return;
1966
1967 biv->have_address_use = true;
1968 data->bivs_not_used_in_addr--;
1969 base_1 = fold_build2 (PLUS_EXPR, type, biv->base, biv->step);
1970 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1971 {
1972 struct iv *iv = ver_info (data, i)->iv;
1973
1974 if (!iv || !iv->biv_p || integer_zerop (iv->step)
1975 || iv->have_address_use || !iv->no_overflow)
1976 continue;
1977
1978 if (type != TREE_TYPE (iv->base)
1979 || !INTEGRAL_TYPE_P (TREE_TYPE (iv->base)))
1980 continue;
1981
1982 if (!operand_equal_p (biv->step, iv->step, 0))
1983 continue;
1984
1985 base_2 = fold_build2 (PLUS_EXPR, type, iv->base, iv->step);
1986 if (operand_equal_p (base_1, iv->base, 0)
1987 || operand_equal_p (base_2, biv->base, 0))
1988 {
1989 iv->have_address_use = true;
1990 data->bivs_not_used_in_addr--;
1991 }
1992 }
1993 }
1994
1995 /* Cumulates the steps of indices into DATA and replaces their values with the
1996 initial ones. Returns false when the value of the index cannot be determined.
1997 Callback for for_each_index. */
1998
1999 struct ifs_ivopts_data
2000 {
2001 struct ivopts_data *ivopts_data;
2002 gimple *stmt;
2003 tree step;
2004 };
2005
2006 static bool
2007 idx_find_step (tree base, tree *idx, void *data)
2008 {
2009 struct ifs_ivopts_data *dta = (struct ifs_ivopts_data *) data;
2010 struct iv *iv;
2011 bool use_overflow_semantics = false;
2012 tree step, iv_base, iv_step, lbound, off;
2013 class loop *loop = dta->ivopts_data->current_loop;
2014
2015 /* If base is a component ref, require that the offset of the reference
2016 be invariant. */
2017 if (TREE_CODE (base) == COMPONENT_REF)
2018 {
2019 off = component_ref_field_offset (base);
2020 return expr_invariant_in_loop_p (loop, off);
2021 }
2022
2023 /* If base is array, first check whether we will be able to move the
2024 reference out of the loop (in order to take its address in strength
2025 reduction). In order for this to work we need both lower bound
2026 and step to be loop invariants. */
2027 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
2028 {
2029 /* Moreover, for a range, the size needs to be invariant as well. */
2030 if (TREE_CODE (base) == ARRAY_RANGE_REF
2031 && !expr_invariant_in_loop_p (loop, TYPE_SIZE (TREE_TYPE (base))))
2032 return false;
2033
2034 step = array_ref_element_size (base);
2035 lbound = array_ref_low_bound (base);
2036
2037 if (!expr_invariant_in_loop_p (loop, step)
2038 || !expr_invariant_in_loop_p (loop, lbound))
2039 return false;
2040 }
2041
2042 if (TREE_CODE (*idx) != SSA_NAME)
2043 return true;
2044
2045 iv = get_iv (dta->ivopts_data, *idx);
2046 if (!iv)
2047 return false;
2048
2049 /* XXX We produce for a base of *D42 with iv->base being &x[0]
2050 *&x[0], which is not folded and does not trigger the
2051 ARRAY_REF path below. */
2052 *idx = iv->base;
2053
2054 if (integer_zerop (iv->step))
2055 return true;
2056
2057 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
2058 {
2059 step = array_ref_element_size (base);
2060
2061 /* We only handle addresses whose step is an integer constant. */
2062 if (TREE_CODE (step) != INTEGER_CST)
2063 return false;
2064 }
2065 else
2066 /* The step for pointer arithmetics already is 1 byte. */
2067 step = size_one_node;
2068
2069 iv_base = iv->base;
2070 iv_step = iv->step;
2071 if (iv->no_overflow && nowrap_type_p (TREE_TYPE (iv_step)))
2072 use_overflow_semantics = true;
2073
2074 if (!convert_affine_scev (dta->ivopts_data->current_loop,
2075 sizetype, &iv_base, &iv_step, dta->stmt,
2076 use_overflow_semantics))
2077 {
2078 /* The index might wrap. */
2079 return false;
2080 }
2081
2082 step = fold_build2 (MULT_EXPR, sizetype, step, iv_step);
2083 dta->step = fold_build2 (PLUS_EXPR, sizetype, dta->step, step);
2084
2085 if (dta->ivopts_data->bivs_not_used_in_addr)
2086 {
2087 if (!iv->biv_p)
2088 iv = find_deriving_biv_for_expr (dta->ivopts_data, iv->ssa_name);
2089
2090 record_biv_for_address_use (dta->ivopts_data, iv);
2091 }
2092 return true;
2093 }
2094
2095 /* Records use in index IDX. Callback for for_each_index. Ivopts data
2096 object is passed to it in DATA. */
2097
2098 static bool
2099 idx_record_use (tree base, tree *idx,
2100 void *vdata)
2101 {
2102 struct ivopts_data *data = (struct ivopts_data *) vdata;
2103 find_interesting_uses_op (data, *idx);
2104 if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
2105 {
2106 if (TREE_OPERAND (base, 2))
2107 find_interesting_uses_op (data, TREE_OPERAND (base, 2));
2108 if (TREE_OPERAND (base, 3))
2109 find_interesting_uses_op (data, TREE_OPERAND (base, 3));
2110 }
2111 return true;
2112 }
2113
2114 /* If we can prove that TOP = cst * BOT for some constant cst,
2115 store cst to MUL and return true. Otherwise return false.
2116 The returned value is always sign-extended, regardless of the
2117 signedness of TOP and BOT. */
2118
2119 static bool
2120 constant_multiple_of (tree top, tree bot, widest_int *mul)
2121 {
2122 aff_tree aff_top, aff_bot;
2123 tree_to_aff_combination (top, TREE_TYPE (top), &aff_top);
2124 tree_to_aff_combination (bot, TREE_TYPE (bot), &aff_bot);
2125 poly_widest_int poly_mul;
2126 if (aff_combination_constant_multiple_p (&aff_top, &aff_bot, &poly_mul)
2127 && poly_mul.is_constant (mul))
2128 return true;
2129
2130 return false;
2131 }
2132
2133 /* Return true if memory reference REF with step STEP may be unaligned. */
2134
2135 static bool
2136 may_be_unaligned_p (tree ref, tree step)
2137 {
2138 /* TARGET_MEM_REFs are translated directly to valid MEMs on the target,
2139 thus they are not misaligned. */
2140 if (TREE_CODE (ref) == TARGET_MEM_REF)
2141 return false;
2142
2143 unsigned int align = TYPE_ALIGN (TREE_TYPE (ref));
2144 if (GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref))) > align)
2145 align = GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref)));
2146
2147 unsigned HOST_WIDE_INT bitpos;
2148 unsigned int ref_align;
2149 get_object_alignment_1 (ref, &ref_align, &bitpos);
2150 if (ref_align < align
2151 || (bitpos % align) != 0
2152 || (bitpos % BITS_PER_UNIT) != 0)
2153 return true;
2154
2155 unsigned int trailing_zeros = tree_ctz (step);
2156 if (trailing_zeros < HOST_BITS_PER_INT
2157 && (1U << trailing_zeros) * BITS_PER_UNIT < align)
2158 return true;
2159
2160 return false;
2161 }
2162
2163 /* Return true if EXPR may be non-addressable. */
2164
2165 bool
2166 may_be_nonaddressable_p (tree expr)
2167 {
2168 switch (TREE_CODE (expr))
2169 {
2170 case VAR_DECL:
2171 /* Check if it's a register variable. */
2172 return DECL_HARD_REGISTER (expr);
2173
2174 case TARGET_MEM_REF:
2175 /* TARGET_MEM_REFs are translated directly to valid MEMs on the
2176 target, thus they are always addressable. */
2177 return false;
2178
2179 case MEM_REF:
2180 /* Likewise for MEM_REFs, modulo the storage order. */
2181 return REF_REVERSE_STORAGE_ORDER (expr);
2182
2183 case BIT_FIELD_REF:
2184 if (REF_REVERSE_STORAGE_ORDER (expr))
2185 return true;
2186 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2187
2188 case COMPONENT_REF:
2189 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
2190 return true;
2191 return DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1))
2192 || may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2193
2194 case ARRAY_REF:
2195 case ARRAY_RANGE_REF:
2196 if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
2197 return true;
2198 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2199
2200 case VIEW_CONVERT_EXPR:
2201 /* This kind of view-conversions may wrap non-addressable objects
2202 and make them look addressable. After some processing the
2203 non-addressability may be uncovered again, causing ADDR_EXPRs
2204 of inappropriate objects to be built. */
2205 if (is_gimple_reg (TREE_OPERAND (expr, 0))
2206 || !is_gimple_addressable (TREE_OPERAND (expr, 0)))
2207 return true;
2208 return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
2209
2210 CASE_CONVERT:
2211 return true;
2212
2213 default:
2214 break;
2215 }
2216
2217 return false;
2218 }
2219
2220 /* Finds addresses in *OP_P inside STMT. */
2221
2222 static void
2223 find_interesting_uses_address (struct ivopts_data *data, gimple *stmt,
2224 tree *op_p)
2225 {
2226 tree base = *op_p, step = size_zero_node;
2227 struct iv *civ;
2228 struct ifs_ivopts_data ifs_ivopts_data;
2229
2230 /* Do not play with volatile memory references. A bit too conservative,
2231 perhaps, but safe. */
2232 if (gimple_has_volatile_ops (stmt))
2233 goto fail;
2234
2235 /* Ignore bitfields for now. Not really something terribly complicated
2236 to handle. TODO. */
2237 if (TREE_CODE (base) == BIT_FIELD_REF)
2238 goto fail;
2239
2240 base = unshare_expr (base);
2241
2242 if (TREE_CODE (base) == TARGET_MEM_REF)
2243 {
2244 tree type = build_pointer_type (TREE_TYPE (base));
2245 tree astep;
2246
2247 if (TMR_BASE (base)
2248 && TREE_CODE (TMR_BASE (base)) == SSA_NAME)
2249 {
2250 civ = get_iv (data, TMR_BASE (base));
2251 if (!civ)
2252 goto fail;
2253
2254 TMR_BASE (base) = civ->base;
2255 step = civ->step;
2256 }
2257 if (TMR_INDEX2 (base)
2258 && TREE_CODE (TMR_INDEX2 (base)) == SSA_NAME)
2259 {
2260 civ = get_iv (data, TMR_INDEX2 (base));
2261 if (!civ)
2262 goto fail;
2263
2264 TMR_INDEX2 (base) = civ->base;
2265 step = civ->step;
2266 }
2267 if (TMR_INDEX (base)
2268 && TREE_CODE (TMR_INDEX (base)) == SSA_NAME)
2269 {
2270 civ = get_iv (data, TMR_INDEX (base));
2271 if (!civ)
2272 goto fail;
2273
2274 TMR_INDEX (base) = civ->base;
2275 astep = civ->step;
2276
2277 if (astep)
2278 {
2279 if (TMR_STEP (base))
2280 astep = fold_build2 (MULT_EXPR, type, TMR_STEP (base), astep);
2281
2282 step = fold_build2 (PLUS_EXPR, type, step, astep);
2283 }
2284 }
2285
2286 if (integer_zerop (step))
2287 goto fail;
2288 base = tree_mem_ref_addr (type, base);
2289 }
2290 else
2291 {
2292 ifs_ivopts_data.ivopts_data = data;
2293 ifs_ivopts_data.stmt = stmt;
2294 ifs_ivopts_data.step = size_zero_node;
2295 if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
2296 || integer_zerop (ifs_ivopts_data.step))
2297 goto fail;
2298 step = ifs_ivopts_data.step;
2299
2300 /* Check that the base expression is addressable. This needs
2301 to be done after substituting bases of IVs into it. */
2302 if (may_be_nonaddressable_p (base))
2303 goto fail;
2304
2305 /* Moreover, on strict alignment platforms, check that it is
2306 sufficiently aligned. */
2307 if (STRICT_ALIGNMENT && may_be_unaligned_p (base, step))
2308 goto fail;
2309
2310 base = build_fold_addr_expr (base);
2311
2312 /* Substituting bases of IVs into the base expression might
2313 have caused folding opportunities. */
2314 if (TREE_CODE (base) == ADDR_EXPR)
2315 {
2316 tree *ref = &TREE_OPERAND (base, 0);
2317 while (handled_component_p (*ref))
2318 ref = &TREE_OPERAND (*ref, 0);
2319 if (TREE_CODE (*ref) == MEM_REF)
2320 {
2321 tree tem = fold_binary (MEM_REF, TREE_TYPE (*ref),
2322 TREE_OPERAND (*ref, 0),
2323 TREE_OPERAND (*ref, 1));
2324 if (tem)
2325 *ref = tem;
2326 }
2327 }
2328 }
2329
2330 civ = alloc_iv (data, base, step);
2331 /* Fail if base object of this memory reference is unknown. */
2332 if (civ->base_object == NULL_TREE)
2333 goto fail;
2334
2335 record_group_use (data, op_p, civ, stmt, USE_REF_ADDRESS, TREE_TYPE (*op_p));
2336 return;
2337
2338 fail:
2339 for_each_index (op_p, idx_record_use, data);
2340 }
2341
2342 /* Finds and records invariants used in STMT. */
2343
2344 static void
2345 find_invariants_stmt (struct ivopts_data *data, gimple *stmt)
2346 {
2347 ssa_op_iter iter;
2348 use_operand_p use_p;
2349 tree op;
2350
2351 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2352 {
2353 op = USE_FROM_PTR (use_p);
2354 record_invariant (data, op, false);
2355 }
2356 }
2357
2358 /* CALL calls an internal function. If operand *OP_P will become an
2359 address when the call is expanded, return the type of the memory
2360 being addressed, otherwise return null. */
2361
2362 static tree
2363 get_mem_type_for_internal_fn (gcall *call, tree *op_p)
2364 {
2365 switch (gimple_call_internal_fn (call))
2366 {
2367 case IFN_MASK_LOAD:
2368 case IFN_MASK_LOAD_LANES:
2369 case IFN_MASK_LEN_LOAD_LANES:
2370 case IFN_LEN_LOAD:
2371 case IFN_MASK_LEN_LOAD:
2372 if (op_p == gimple_call_arg_ptr (call, 0))
2373 return TREE_TYPE (gimple_call_lhs (call));
2374 return NULL_TREE;
2375
2376 case IFN_MASK_STORE:
2377 case IFN_MASK_STORE_LANES:
2378 case IFN_MASK_LEN_STORE_LANES:
2379 case IFN_LEN_STORE:
2380 case IFN_MASK_LEN_STORE:
2381 {
2382 if (op_p == gimple_call_arg_ptr (call, 0))
2383 {
2384 internal_fn ifn = gimple_call_internal_fn (call);
2385 int index = internal_fn_stored_value_index (ifn);
2386 return TREE_TYPE (gimple_call_arg (call, index));
2387 }
2388 return NULL_TREE;
2389 }
2390
2391 default:
2392 return NULL_TREE;
2393 }
2394 }
2395
2396 /* IV is a (non-address) iv that describes operand *OP_P of STMT.
2397 Return true if the operand will become an address when STMT
2398 is expanded and record the associated address use if so. */
2399
2400 static bool
2401 find_address_like_use (struct ivopts_data *data, gimple *stmt, tree *op_p,
2402 struct iv *iv)
2403 {
2404 /* Fail if base object of this memory reference is unknown. */
2405 if (iv->base_object == NULL_TREE)
2406 return false;
2407
2408 tree mem_type = NULL_TREE;
2409 if (gcall *call = dyn_cast <gcall *> (stmt))
2410 if (gimple_call_internal_p (call))
2411 mem_type = get_mem_type_for_internal_fn (call, op_p);
2412 if (mem_type)
2413 {
2414 iv = alloc_iv (data, iv->base, iv->step);
2415 record_group_use (data, op_p, iv, stmt, USE_PTR_ADDRESS, mem_type);
2416 return true;
2417 }
2418 return false;
2419 }
2420
2421 /* Finds interesting uses of induction variables in the statement STMT. */
2422
2423 static void
2424 find_interesting_uses_stmt (struct ivopts_data *data, gimple *stmt)
2425 {
2426 struct iv *iv;
2427 tree op, *lhs, *rhs;
2428 ssa_op_iter iter;
2429 use_operand_p use_p;
2430 enum tree_code code;
2431
2432 find_invariants_stmt (data, stmt);
2433
2434 if (gimple_code (stmt) == GIMPLE_COND)
2435 {
2436 find_interesting_uses_cond (data, stmt);
2437 return;
2438 }
2439
2440 if (is_gimple_assign (stmt))
2441 {
2442 lhs = gimple_assign_lhs_ptr (stmt);
2443 rhs = gimple_assign_rhs1_ptr (stmt);
2444
2445 if (TREE_CODE (*lhs) == SSA_NAME)
2446 {
2447 /* If the statement defines an induction variable, the uses are not
2448 interesting by themselves. */
2449
2450 iv = get_iv (data, *lhs);
2451
2452 if (iv && !integer_zerop (iv->step))
2453 return;
2454 }
2455
2456 code = gimple_assign_rhs_code (stmt);
2457 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
2458 && (REFERENCE_CLASS_P (*rhs)
2459 || is_gimple_val (*rhs)))
2460 {
2461 if (REFERENCE_CLASS_P (*rhs))
2462 find_interesting_uses_address (data, stmt, rhs);
2463 else
2464 find_interesting_uses_op (data, *rhs);
2465
2466 if (REFERENCE_CLASS_P (*lhs))
2467 find_interesting_uses_address (data, stmt, lhs);
2468 return;
2469 }
2470 else if (TREE_CODE_CLASS (code) == tcc_comparison)
2471 {
2472 find_interesting_uses_cond (data, stmt);
2473 return;
2474 }
2475
2476 /* TODO -- we should also handle address uses of type
2477
2478 memory = call (whatever);
2479
2480 and
2481
2482 call (memory). */
2483 }
2484
2485 if (gimple_code (stmt) == GIMPLE_PHI
2486 && gimple_bb (stmt) == data->current_loop->header)
2487 {
2488 iv = get_iv (data, PHI_RESULT (stmt));
2489
2490 if (iv && !integer_zerop (iv->step))
2491 return;
2492 }
2493
2494 FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
2495 {
2496 op = USE_FROM_PTR (use_p);
2497
2498 if (TREE_CODE (op) != SSA_NAME)
2499 continue;
2500
2501 iv = get_iv (data, op);
2502 if (!iv)
2503 continue;
2504
2505 if (!find_address_like_use (data, stmt, use_p->use, iv))
2506 find_interesting_uses_op (data, op);
2507 }
2508 }
2509
2510 /* Finds interesting uses of induction variables outside of loops
2511 on loop exit edge EXIT. */
2512
2513 static void
2514 find_interesting_uses_outside (struct ivopts_data *data, edge exit)
2515 {
2516 gphi *phi;
2517 gphi_iterator psi;
2518 tree def;
2519
2520 for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
2521 {
2522 phi = psi.phi ();
2523 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2524 if (!virtual_operand_p (def))
2525 find_interesting_uses_op (data, def);
2526 }
2527 }
2528
2529 /* Return TRUE if OFFSET is within the range of [base + offset] addressing
2530 mode for memory reference represented by USE. */
2531
2532 static GTY (()) vec<rtx, va_gc> *addr_list;
2533
2534 static bool
2535 addr_offset_valid_p (struct iv_use *use, poly_int64 offset)
2536 {
2537 rtx reg, addr;
2538 unsigned list_index;
2539 addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
2540 machine_mode addr_mode, mem_mode = TYPE_MODE (use->mem_type);
2541
2542 list_index = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
2543 if (list_index >= vec_safe_length (addr_list))
2544 vec_safe_grow_cleared (addr_list, list_index + MAX_MACHINE_MODE, true);
2545
2546 addr = (*addr_list)[list_index];
2547 if (!addr)
2548 {
2549 addr_mode = targetm.addr_space.address_mode (as);
2550 reg = gen_raw_REG (addr_mode, LAST_VIRTUAL_REGISTER + 1);
2551 addr = gen_rtx_fmt_ee (PLUS, addr_mode, reg, NULL_RTX);
2552 (*addr_list)[list_index] = addr;
2553 }
2554 else
2555 addr_mode = GET_MODE (addr);
2556
2557 XEXP (addr, 1) = gen_int_mode (offset, addr_mode);
2558 return (memory_address_addr_space_p (mem_mode, addr, as));
2559 }
2560
2561 /* Comparison function to sort group in ascending order of addr_offset. */
2562
2563 static int
2564 group_compare_offset (const void *a, const void *b)
2565 {
2566 const struct iv_use *const *u1 = (const struct iv_use *const *) a;
2567 const struct iv_use *const *u2 = (const struct iv_use *const *) b;
2568
2569 return compare_sizes_for_sort ((*u1)->addr_offset, (*u2)->addr_offset);
2570 }
2571
2572 /* Check if small groups should be split. Return true if no group
2573 contains more than two uses with distinct addr_offsets. Return
2574 false otherwise. We want to split such groups because:
2575
2576 1) Small groups don't have much benefit and may interfer with
2577 general candidate selection.
2578 2) Size for problem with only small groups is usually small and
2579 general algorithm can handle it well.
2580
2581 TODO -- Above claim may not hold when we want to merge memory
2582 accesses with conseuctive addresses. */
2583
2584 static bool
2585 split_small_address_groups_p (struct ivopts_data *data)
2586 {
2587 unsigned int i, j, distinct = 1;
2588 struct iv_use *pre;
2589 struct iv_group *group;
2590
2591 for (i = 0; i < data->vgroups.length (); i++)
2592 {
2593 group = data->vgroups[i];
2594 if (group->vuses.length () == 1)
2595 continue;
2596
2597 gcc_assert (address_p (group->type));
2598 if (group->vuses.length () == 2)
2599 {
2600 if (compare_sizes_for_sort (group->vuses[0]->addr_offset,
2601 group->vuses[1]->addr_offset) > 0)
2602 std::swap (group->vuses[0], group->vuses[1]);
2603 }
2604 else
2605 group->vuses.qsort (group_compare_offset);
2606
2607 if (distinct > 2)
2608 continue;
2609
2610 distinct = 1;
2611 for (pre = group->vuses[0], j = 1; j < group->vuses.length (); j++)
2612 {
2613 if (maybe_ne (group->vuses[j]->addr_offset, pre->addr_offset))
2614 {
2615 pre = group->vuses[j];
2616 distinct++;
2617 }
2618
2619 if (distinct > 2)
2620 break;
2621 }
2622 }
2623
2624 return (distinct <= 2);
2625 }
2626
2627 /* For each group of address type uses, this function further groups
2628 these uses according to the maximum offset supported by target's
2629 [base + offset] addressing mode. */
2630
2631 static void
2632 split_address_groups (struct ivopts_data *data)
2633 {
2634 unsigned int i, j;
2635 /* Always split group. */
2636 bool split_p = split_small_address_groups_p (data);
2637
2638 for (i = 0; i < data->vgroups.length (); i++)
2639 {
2640 struct iv_group *new_group = NULL;
2641 struct iv_group *group = data->vgroups[i];
2642 struct iv_use *use = group->vuses[0];
2643
2644 use->id = 0;
2645 use->group_id = group->id;
2646 if (group->vuses.length () == 1)
2647 continue;
2648
2649 gcc_assert (address_p (use->type));
2650
2651 for (j = 1; j < group->vuses.length ();)
2652 {
2653 struct iv_use *next = group->vuses[j];
2654 poly_int64 offset = next->addr_offset - use->addr_offset;
2655
2656 /* Split group if aksed to, or the offset against the first
2657 use can't fit in offset part of addressing mode. IV uses
2658 having the same offset are still kept in one group. */
2659 if (maybe_ne (offset, 0)
2660 && (split_p || !addr_offset_valid_p (use, offset)))
2661 {
2662 if (!new_group)
2663 new_group = record_group (data, group->type);
2664 group->vuses.ordered_remove (j);
2665 new_group->vuses.safe_push (next);
2666 continue;
2667 }
2668
2669 next->id = j;
2670 next->group_id = group->id;
2671 j++;
2672 }
2673 }
2674 }
2675
2676 /* Finds uses of the induction variables that are interesting. */
2677
2678 static void
2679 find_interesting_uses (struct ivopts_data *data, basic_block *body)
2680 {
2681 basic_block bb;
2682 gimple_stmt_iterator bsi;
2683 unsigned i;
2684 edge e;
2685
2686 for (i = 0; i < data->current_loop->num_nodes; i++)
2687 {
2688 edge_iterator ei;
2689 bb = body[i];
2690
2691 FOR_EACH_EDGE (e, ei, bb->succs)
2692 if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
2693 && !flow_bb_inside_loop_p (data->current_loop, e->dest))
2694 find_interesting_uses_outside (data, e);
2695
2696 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2697 find_interesting_uses_stmt (data, gsi_stmt (bsi));
2698 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2699 if (!is_gimple_debug (gsi_stmt (bsi)))
2700 find_interesting_uses_stmt (data, gsi_stmt (bsi));
2701 }
2702
2703 split_address_groups (data);
2704
2705 if (dump_file && (dump_flags & TDF_DETAILS))
2706 {
2707 fprintf (dump_file, "\n<IV Groups>:\n");
2708 dump_groups (dump_file, data);
2709 fprintf (dump_file, "\n");
2710 }
2711 }
2712
2713 /* Strips constant offsets from EXPR and stores them to OFFSET. If INSIDE_ADDR
2714 is true, assume we are inside an address. If TOP_COMPREF is true, assume
2715 we are at the top-level of the processed address. */
2716
2717 static tree
2718 strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
2719 poly_int64 *offset)
2720 {
2721 tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
2722 enum tree_code code;
2723 tree type, orig_type = TREE_TYPE (expr);
2724 poly_int64 off0, off1;
2725 HOST_WIDE_INT st;
2726 tree orig_expr = expr;
2727
2728 STRIP_NOPS (expr);
2729
2730 type = TREE_TYPE (expr);
2731 code = TREE_CODE (expr);
2732 *offset = 0;
2733
2734 switch (code)
2735 {
2736 case POINTER_PLUS_EXPR:
2737 case PLUS_EXPR:
2738 case MINUS_EXPR:
2739 op0 = TREE_OPERAND (expr, 0);
2740 op1 = TREE_OPERAND (expr, 1);
2741
2742 op0 = strip_offset_1 (op0, false, false, &off0);
2743 op1 = strip_offset_1 (op1, false, false, &off1);
2744
2745 *offset = (code == MINUS_EXPR ? off0 - off1 : off0 + off1);
2746 if (op0 == TREE_OPERAND (expr, 0)
2747 && op1 == TREE_OPERAND (expr, 1))
2748 return orig_expr;
2749
2750 if (integer_zerop (op1))
2751 expr = op0;
2752 else if (integer_zerop (op0))
2753 {
2754 if (code == MINUS_EXPR)
2755 {
2756 if (TYPE_OVERFLOW_UNDEFINED (type))
2757 {
2758 type = unsigned_type_for (type);
2759 op1 = fold_convert (type, op1);
2760 }
2761 expr = fold_build1 (NEGATE_EXPR, type, op1);
2762 }
2763 else
2764 expr = op1;
2765 }
2766 else
2767 {
2768 if (TYPE_OVERFLOW_UNDEFINED (type))
2769 {
2770 type = unsigned_type_for (type);
2771 if (code == POINTER_PLUS_EXPR)
2772 code = PLUS_EXPR;
2773 op0 = fold_convert (type, op0);
2774 op1 = fold_convert (type, op1);
2775 }
2776 expr = fold_build2 (code, type, op0, op1);
2777 }
2778
2779 return fold_convert (orig_type, expr);
2780
2781 case MULT_EXPR:
2782 op1 = TREE_OPERAND (expr, 1);
2783 if (!cst_and_fits_in_hwi (op1))
2784 return orig_expr;
2785
2786 op0 = TREE_OPERAND (expr, 0);
2787 op0 = strip_offset_1 (op0, false, false, &off0);
2788 if (op0 == TREE_OPERAND (expr, 0))
2789 return orig_expr;
2790
2791 *offset = off0 * int_cst_value (op1);
2792 if (integer_zerop (op0))
2793 expr = op0;
2794 else
2795 {
2796 if (TYPE_OVERFLOW_UNDEFINED (type))
2797 {
2798 type = unsigned_type_for (type);
2799 op0 = fold_convert (type, op0);
2800 op1 = fold_convert (type, op1);
2801 }
2802 expr = fold_build2 (MULT_EXPR, type, op0, op1);
2803 }
2804
2805 return fold_convert (orig_type, expr);
2806
2807 case ARRAY_REF:
2808 case ARRAY_RANGE_REF:
2809 if (!inside_addr)
2810 return orig_expr;
2811
2812 step = array_ref_element_size (expr);
2813 if (!cst_and_fits_in_hwi (step))
2814 break;
2815
2816 st = int_cst_value (step);
2817 op1 = TREE_OPERAND (expr, 1);
2818 op1 = strip_offset_1 (op1, false, false, &off1);
2819 *offset = off1 * st;
2820
2821 if (top_compref
2822 && integer_zerop (op1))
2823 {
2824 /* Strip the component reference completely. */
2825 op0 = TREE_OPERAND (expr, 0);
2826 op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
2827 *offset += off0;
2828 return op0;
2829 }
2830 break;
2831
2832 case COMPONENT_REF:
2833 {
2834 tree field;
2835
2836 if (!inside_addr)
2837 return orig_expr;
2838
2839 tmp = component_ref_field_offset (expr);
2840 field = TREE_OPERAND (expr, 1);
2841 if (top_compref
2842 && cst_and_fits_in_hwi (tmp)
2843 && cst_and_fits_in_hwi (DECL_FIELD_BIT_OFFSET (field)))
2844 {
2845 HOST_WIDE_INT boffset, abs_off;
2846
2847 /* Strip the component reference completely. */
2848 op0 = TREE_OPERAND (expr, 0);
2849 op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
2850 boffset = int_cst_value (DECL_FIELD_BIT_OFFSET (field));
2851 abs_off = abs_hwi (boffset) / BITS_PER_UNIT;
2852 if (boffset < 0)
2853 abs_off = -abs_off;
2854
2855 *offset = off0 + int_cst_value (tmp) + abs_off;
2856 return op0;
2857 }
2858 }
2859 break;
2860
2861 case ADDR_EXPR:
2862 op0 = TREE_OPERAND (expr, 0);
2863 op0 = strip_offset_1 (op0, true, true, &off0);
2864 *offset += off0;
2865
2866 if (op0 == TREE_OPERAND (expr, 0))
2867 return orig_expr;
2868
2869 expr = build_fold_addr_expr (op0);
2870 return fold_convert (orig_type, expr);
2871
2872 case MEM_REF:
2873 /* ??? Offset operand? */
2874 inside_addr = false;
2875 break;
2876
2877 default:
2878 if (ptrdiff_tree_p (expr, offset) && maybe_ne (*offset, 0))
2879 return build_int_cst (orig_type, 0);
2880 return orig_expr;
2881 }
2882
2883 /* Default handling of expressions for that we want to recurse into
2884 the first operand. */
2885 op0 = TREE_OPERAND (expr, 0);
2886 op0 = strip_offset_1 (op0, inside_addr, false, &off0);
2887 *offset += off0;
2888
2889 if (op0 == TREE_OPERAND (expr, 0)
2890 && (!op1 || op1 == TREE_OPERAND (expr, 1)))
2891 return orig_expr;
2892
2893 expr = copy_node (expr);
2894 TREE_OPERAND (expr, 0) = op0;
2895 if (op1)
2896 TREE_OPERAND (expr, 1) = op1;
2897
2898 /* Inside address, we might strip the top level component references,
2899 thus changing type of the expression. Handling of ADDR_EXPR
2900 will fix that. */
2901 expr = fold_convert (orig_type, expr);
2902
2903 return expr;
2904 }
2905
2906 /* Strips constant offsets from EXPR and stores them to OFFSET. */
2907
2908 static tree
2909 strip_offset (tree expr, poly_uint64 *offset)
2910 {
2911 poly_int64 off;
2912 tree core = strip_offset_1 (expr, false, false, &off);
2913 *offset = off;
2914 return core;
2915 }
2916
2917 /* Returns variant of TYPE that can be used as base for different uses.
2918 We return unsigned type with the same precision, which avoids problems
2919 with overflows. */
2920
2921 static tree
2922 generic_type_for (tree type)
2923 {
2924 if (POINTER_TYPE_P (type))
2925 return unsigned_type_for (type);
2926
2927 if (TYPE_UNSIGNED (type))
2928 return type;
2929
2930 return unsigned_type_for (type);
2931 }
2932
2933 /* Private data for walk_tree. */
2934
2935 struct walk_tree_data
2936 {
2937 bitmap *inv_vars;
2938 struct ivopts_data *idata;
2939 };
2940
2941 /* Callback function for walk_tree, it records invariants and symbol
2942 reference in *EXPR_P. DATA is the structure storing result info. */
2943
2944 static tree
2945 find_inv_vars_cb (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
2946 {
2947 tree op = *expr_p;
2948 struct version_info *info;
2949 struct walk_tree_data *wdata = (struct walk_tree_data*) data;
2950
2951 if (TREE_CODE (op) != SSA_NAME)
2952 return NULL_TREE;
2953
2954 info = name_info (wdata->idata, op);
2955 /* Because we expand simple operations when finding IVs, loop invariant
2956 variable that isn't referred by the original loop could be used now.
2957 Record such invariant variables here. */
2958 if (!info->iv)
2959 {
2960 struct ivopts_data *idata = wdata->idata;
2961 basic_block bb = gimple_bb (SSA_NAME_DEF_STMT (op));
2962
2963 if (!bb || !flow_bb_inside_loop_p (idata->current_loop, bb))
2964 {
2965 tree steptype = TREE_TYPE (op);
2966 if (POINTER_TYPE_P (steptype))
2967 steptype = sizetype;
2968 set_iv (idata, op, op, build_int_cst (steptype, 0), true);
2969 record_invariant (idata, op, false);
2970 }
2971 }
2972 if (!info->inv_id || info->has_nonlin_use)
2973 return NULL_TREE;
2974
2975 if (!*wdata->inv_vars)
2976 *wdata->inv_vars = BITMAP_ALLOC (NULL);
2977 bitmap_set_bit (*wdata->inv_vars, info->inv_id);
2978
2979 return NULL_TREE;
2980 }
2981
2982 /* Records invariants in *EXPR_P. INV_VARS is the bitmap to that we should
2983 store it. */
2984
2985 static inline void
2986 find_inv_vars (struct ivopts_data *data, tree *expr_p, bitmap *inv_vars)
2987 {
2988 struct walk_tree_data wdata;
2989
2990 if (!inv_vars)
2991 return;
2992
2993 wdata.idata = data;
2994 wdata.inv_vars = inv_vars;
2995 walk_tree (expr_p, find_inv_vars_cb, &wdata, NULL);
2996 }
2997
2998 /* Get entry from invariant expr hash table for INV_EXPR. New entry
2999 will be recorded if it doesn't exist yet. Given below two exprs:
3000 inv_expr + cst1, inv_expr + cst2
3001 It's hard to make decision whether constant part should be stripped
3002 or not. We choose to not strip based on below facts:
3003 1) We need to count ADD cost for constant part if it's stripped,
3004 which isn't always trivial where this functions is called.
3005 2) Stripping constant away may be conflict with following loop
3006 invariant hoisting pass.
3007 3) Not stripping constant away results in more invariant exprs,
3008 which usually leads to decision preferring lower reg pressure. */
3009
3010 static iv_inv_expr_ent *
3011 get_loop_invariant_expr (struct ivopts_data *data, tree inv_expr)
3012 {
3013 STRIP_NOPS (inv_expr);
3014
3015 if (poly_int_tree_p (inv_expr)
3016 || TREE_CODE (inv_expr) == SSA_NAME)
3017 return NULL;
3018
3019 /* Don't strip constant part away as we used to. */
3020
3021 /* Stores EXPR in DATA->inv_expr_tab, return pointer to iv_inv_expr_ent. */
3022 struct iv_inv_expr_ent ent;
3023 ent.expr = inv_expr;
3024 ent.hash = iterative_hash_expr (inv_expr, 0);
3025 struct iv_inv_expr_ent **slot = data->inv_expr_tab->find_slot (&ent, INSERT);
3026
3027 if (!*slot)
3028 {
3029 *slot = XNEW (struct iv_inv_expr_ent);
3030 (*slot)->expr = inv_expr;
3031 (*slot)->hash = ent.hash;
3032 (*slot)->id = ++data->max_inv_expr_id;
3033 }
3034
3035 return *slot;
3036 }
3037
3038
3039 /* Return *TP if it is an SSA_NAME marked with TREE_VISITED, i.e., as
3040 unsuitable as ivopts candidates for potentially involving undefined
3041 behavior. */
3042
3043 static tree
3044 find_ssa_undef (tree *tp, int *walk_subtrees, void *bb_)
3045 {
3046 basic_block bb = (basic_block) bb_;
3047 if (TREE_CODE (*tp) == SSA_NAME
3048 && ssa_name_maybe_undef_p (*tp)
3049 && !ssa_name_any_use_dominates_bb_p (*tp, bb))
3050 return *tp;
3051 if (!EXPR_P (*tp))
3052 *walk_subtrees = 0;
3053 return NULL;
3054 }
3055
3056 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
3057 position to POS. If USE is not NULL, the candidate is set as related to
3058 it. If both BASE and STEP are NULL, we add a pseudocandidate for the
3059 replacement of the final value of the iv by a direct computation. */
3060
3061 static struct iv_cand *
3062 add_candidate_1 (struct ivopts_data *data, tree base, tree step, bool important,
3063 enum iv_position pos, struct iv_use *use,
3064 gimple *incremented_at, struct iv *orig_iv = NULL,
3065 bool doloop = false)
3066 {
3067 unsigned i;
3068 struct iv_cand *cand = NULL;
3069 tree type, orig_type;
3070
3071 gcc_assert (base && step);
3072
3073 /* -fkeep-gc-roots-live means that we have to keep a real pointer
3074 live, but the ivopts code may replace a real pointer with one
3075 pointing before or after the memory block that is then adjusted
3076 into the memory block during the loop. FIXME: It would likely be
3077 better to actually force the pointer live and still use ivopts;
3078 for example, it would be enough to write the pointer into memory
3079 and keep it there until after the loop. */
3080 if (flag_keep_gc_roots_live && POINTER_TYPE_P (TREE_TYPE (base)))
3081 return NULL;
3082
3083 /* If BASE contains undefined SSA names make sure we only record
3084 the original IV. */
3085 bool involves_undefs = false;
3086 if (walk_tree (&base, find_ssa_undef, data->current_loop->header, NULL))
3087 {
3088 if (pos != IP_ORIGINAL)
3089 return NULL;
3090 important = false;
3091 involves_undefs = true;
3092 }
3093
3094 /* For non-original variables, make sure their values are computed in a type
3095 that does not invoke undefined behavior on overflows (since in general,
3096 we cannot prove that these induction variables are non-wrapping). */
3097 if (pos != IP_ORIGINAL)
3098 {
3099 orig_type = TREE_TYPE (base);
3100 type = generic_type_for (orig_type);
3101 if (type != orig_type)
3102 {
3103 base = fold_convert (type, base);
3104 step = fold_convert (type, step);
3105 }
3106 }
3107
3108 for (i = 0; i < data->vcands.length (); i++)
3109 {
3110 cand = data->vcands[i];
3111
3112 if (cand->pos != pos)
3113 continue;
3114
3115 if (cand->incremented_at != incremented_at
3116 || ((pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
3117 && cand->ainc_use != use))
3118 continue;
3119
3120 if (operand_equal_p (base, cand->iv->base, 0)
3121 && operand_equal_p (step, cand->iv->step, 0)
3122 && (TYPE_PRECISION (TREE_TYPE (base))
3123 == TYPE_PRECISION (TREE_TYPE (cand->iv->base))))
3124 break;
3125 }
3126
3127 if (i == data->vcands.length ())
3128 {
3129 cand = XCNEW (struct iv_cand);
3130 cand->id = i;
3131 cand->iv = alloc_iv (data, base, step);
3132 cand->pos = pos;
3133 if (pos != IP_ORIGINAL)
3134 {
3135 if (doloop)
3136 cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "doloop");
3137 else
3138 cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
3139 cand->var_after = cand->var_before;
3140 }
3141 cand->important = important;
3142 cand->involves_undefs = involves_undefs;
3143 cand->incremented_at = incremented_at;
3144 cand->doloop_p = doloop;
3145 data->vcands.safe_push (cand);
3146
3147 if (!poly_int_tree_p (step))
3148 {
3149 find_inv_vars (data, &step, &cand->inv_vars);
3150
3151 iv_inv_expr_ent *inv_expr = get_loop_invariant_expr (data, step);
3152 /* Share bitmap between inv_vars and inv_exprs for cand. */
3153 if (inv_expr != NULL)
3154 {
3155 cand->inv_exprs = cand->inv_vars;
3156 cand->inv_vars = NULL;
3157 if (cand->inv_exprs)
3158 bitmap_clear (cand->inv_exprs);
3159 else
3160 cand->inv_exprs = BITMAP_ALLOC (NULL);
3161
3162 bitmap_set_bit (cand->inv_exprs, inv_expr->id);
3163 }
3164 }
3165
3166 if (pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
3167 cand->ainc_use = use;
3168 else
3169 cand->ainc_use = NULL;
3170
3171 cand->orig_iv = orig_iv;
3172 if (dump_file && (dump_flags & TDF_DETAILS))
3173 dump_cand (dump_file, cand);
3174 }
3175
3176 cand->important |= important;
3177 cand->doloop_p |= doloop;
3178
3179 /* Relate candidate to the group for which it is added. */
3180 if (use)
3181 bitmap_set_bit (data->vgroups[use->group_id]->related_cands, i);
3182
3183 return cand;
3184 }
3185
3186 /* Returns true if incrementing the induction variable at the end of the LOOP
3187 is allowed.
3188
3189 The purpose is to avoid splitting latch edge with a biv increment, thus
3190 creating a jump, possibly confusing other optimization passes and leaving
3191 less freedom to scheduler. So we allow IP_END only if IP_NORMAL is not
3192 available (so we do not have a better alternative), or if the latch edge
3193 is already nonempty. */
3194
3195 static bool
3196 allow_ip_end_pos_p (class loop *loop)
3197 {
3198 /* Do not allow IP_END when creating the IV would need to split the
3199 latch edge as that makes all IP_NORMAL invalid. */
3200 auto pos = gsi_last_bb (ip_end_pos (loop));
3201 if (!gsi_end_p (pos) && stmt_ends_bb_p (*pos))
3202 return false;
3203
3204 if (!ip_normal_pos (loop))
3205 return true;
3206
3207 if (!empty_block_p (ip_end_pos (loop)))
3208 return true;
3209
3210 return false;
3211 }
3212
3213 /* If possible, adds autoincrement candidates BASE + STEP * i based on use USE.
3214 Important field is set to IMPORTANT. */
3215
3216 static void
3217 add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
3218 bool important, struct iv_use *use)
3219 {
3220 basic_block use_bb = gimple_bb (use->stmt);
3221 machine_mode mem_mode;
3222 unsigned HOST_WIDE_INT cstepi;
3223
3224 /* If we insert the increment in any position other than the standard
3225 ones, we must ensure that it is incremented once per iteration.
3226 It must not be in an inner nested loop, or one side of an if
3227 statement. */
3228 if (use_bb->loop_father != data->current_loop
3229 || !dominated_by_p (CDI_DOMINATORS, data->current_loop->latch, use_bb)
3230 || stmt_can_throw_internal (cfun, use->stmt)
3231 || !cst_and_fits_in_hwi (step))
3232 return;
3233
3234 cstepi = int_cst_value (step);
3235
3236 mem_mode = TYPE_MODE (use->mem_type);
3237 if (((USE_LOAD_PRE_INCREMENT (mem_mode)
3238 || USE_STORE_PRE_INCREMENT (mem_mode))
3239 && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
3240 || ((USE_LOAD_PRE_DECREMENT (mem_mode)
3241 || USE_STORE_PRE_DECREMENT (mem_mode))
3242 && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
3243 {
3244 enum tree_code code = MINUS_EXPR;
3245 tree new_base;
3246 tree new_step = step;
3247
3248 if (POINTER_TYPE_P (TREE_TYPE (base)))
3249 {
3250 new_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
3251 code = POINTER_PLUS_EXPR;
3252 }
3253 else
3254 new_step = fold_convert (TREE_TYPE (base), new_step);
3255 new_base = fold_build2 (code, TREE_TYPE (base), base, new_step);
3256 add_candidate_1 (data, new_base, step, important, IP_BEFORE_USE, use,
3257 use->stmt);
3258 }
3259 if (((USE_LOAD_POST_INCREMENT (mem_mode)
3260 || USE_STORE_POST_INCREMENT (mem_mode))
3261 && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
3262 || ((USE_LOAD_POST_DECREMENT (mem_mode)
3263 || USE_STORE_POST_DECREMENT (mem_mode))
3264 && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
3265 {
3266 add_candidate_1 (data, base, step, important, IP_AFTER_USE, use,
3267 use->stmt);
3268 }
3269 }
3270
3271 /* Adds a candidate BASE + STEP * i. Important field is set to IMPORTANT and
3272 position to POS. If USE is not NULL, the candidate is set as related to
3273 it. The candidate computation is scheduled before exit condition and at
3274 the end of loop. */
3275
3276 static void
3277 add_candidate (struct ivopts_data *data, tree base, tree step, bool important,
3278 struct iv_use *use, struct iv *orig_iv = NULL,
3279 bool doloop = false)
3280 {
3281 if (ip_normal_pos (data->current_loop))
3282 add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL, orig_iv,
3283 doloop);
3284 /* Exclude doloop candidate here since it requires decrement then comparison
3285 and jump, the IP_END position doesn't match. */
3286 if (!doloop && ip_end_pos (data->current_loop)
3287 && allow_ip_end_pos_p (data->current_loop))
3288 add_candidate_1 (data, base, step, important, IP_END, use, NULL, orig_iv);
3289 }
3290
3291 /* Adds standard iv candidates. */
3292
3293 static void
3294 add_standard_iv_candidates (struct ivopts_data *data)
3295 {
3296 add_candidate (data, integer_zero_node, integer_one_node, true, NULL);
3297
3298 /* The same for a double-integer type if it is still fast enough. */
3299 if (TYPE_PRECISION
3300 (long_integer_type_node) > TYPE_PRECISION (integer_type_node)
3301 && TYPE_PRECISION (long_integer_type_node) <= BITS_PER_WORD)
3302 add_candidate (data, build_int_cst (long_integer_type_node, 0),
3303 build_int_cst (long_integer_type_node, 1), true, NULL);
3304
3305 /* The same for a double-integer type if it is still fast enough. */
3306 if (TYPE_PRECISION
3307 (long_long_integer_type_node) > TYPE_PRECISION (long_integer_type_node)
3308 && TYPE_PRECISION (long_long_integer_type_node) <= BITS_PER_WORD)
3309 add_candidate (data, build_int_cst (long_long_integer_type_node, 0),
3310 build_int_cst (long_long_integer_type_node, 1), true, NULL);
3311 }
3312
3313
3314 /* Adds candidates bases on the old induction variable IV. */
3315
3316 static void
3317 add_iv_candidate_for_biv (struct ivopts_data *data, struct iv *iv)
3318 {
3319 gimple *phi;
3320 tree def;
3321 struct iv_cand *cand;
3322
3323 /* Check if this biv is used in address type use. */
3324 if (iv->no_overflow && iv->have_address_use
3325 && INTEGRAL_TYPE_P (TREE_TYPE (iv->base))
3326 && TYPE_PRECISION (TREE_TYPE (iv->base)) < TYPE_PRECISION (sizetype))
3327 {
3328 tree base = fold_convert (sizetype, iv->base);
3329 tree step = fold_convert (sizetype, iv->step);
3330
3331 /* Add iv cand of same precision as index part in TARGET_MEM_REF. */
3332 add_candidate (data, base, step, true, NULL, iv);
3333 /* Add iv cand of the original type only if it has nonlinear use. */
3334 if (iv->nonlin_use)
3335 add_candidate (data, iv->base, iv->step, true, NULL);
3336 }
3337 else
3338 add_candidate (data, iv->base, iv->step, true, NULL);
3339
3340 /* The same, but with initial value zero. */
3341 if (POINTER_TYPE_P (TREE_TYPE (iv->base)))
3342 add_candidate (data, size_int (0), iv->step, true, NULL);
3343 else
3344 add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
3345 iv->step, true, NULL);
3346
3347 phi = SSA_NAME_DEF_STMT (iv->ssa_name);
3348 if (gimple_code (phi) == GIMPLE_PHI)
3349 {
3350 /* Additionally record the possibility of leaving the original iv
3351 untouched. */
3352 def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
3353 /* Don't add candidate if it's from another PHI node because
3354 it's an affine iv appearing in the form of PEELED_CHREC. */
3355 phi = SSA_NAME_DEF_STMT (def);
3356 if (gimple_code (phi) != GIMPLE_PHI)
3357 {
3358 cand = add_candidate_1 (data,
3359 iv->base, iv->step, true, IP_ORIGINAL, NULL,
3360 SSA_NAME_DEF_STMT (def));
3361 if (cand)
3362 {
3363 cand->var_before = iv->ssa_name;
3364 cand->var_after = def;
3365 }
3366 }
3367 else
3368 gcc_assert (gimple_bb (phi) == data->current_loop->header);
3369 }
3370 }
3371
3372 /* Adds candidates based on the old induction variables. */
3373
3374 static void
3375 add_iv_candidate_for_bivs (struct ivopts_data *data)
3376 {
3377 unsigned i;
3378 struct iv *iv;
3379 bitmap_iterator bi;
3380
3381 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
3382 {
3383 iv = ver_info (data, i)->iv;
3384 if (iv && iv->biv_p && !integer_zerop (iv->step))
3385 add_iv_candidate_for_biv (data, iv);
3386 }
3387 }
3388
3389 /* Record common candidate {BASE, STEP} derived from USE in hashtable. */
3390
3391 static void
3392 record_common_cand (struct ivopts_data *data, tree base,
3393 tree step, struct iv_use *use)
3394 {
3395 class iv_common_cand ent;
3396 class iv_common_cand **slot;
3397
3398 ent.base = base;
3399 ent.step = step;
3400 ent.hash = iterative_hash_expr (base, 0);
3401 ent.hash = iterative_hash_expr (step, ent.hash);
3402
3403 slot = data->iv_common_cand_tab->find_slot (&ent, INSERT);
3404 if (*slot == NULL)
3405 {
3406 *slot = new iv_common_cand ();
3407 (*slot)->base = base;
3408 (*slot)->step = step;
3409 (*slot)->uses.create (8);
3410 (*slot)->hash = ent.hash;
3411 data->iv_common_cands.safe_push ((*slot));
3412 }
3413
3414 gcc_assert (use != NULL);
3415 (*slot)->uses.safe_push (use);
3416 return;
3417 }
3418
3419 /* Comparison function used to sort common candidates. */
3420
3421 static int
3422 common_cand_cmp (const void *p1, const void *p2)
3423 {
3424 unsigned n1, n2;
3425 const class iv_common_cand *const *const ccand1
3426 = (const class iv_common_cand *const *)p1;
3427 const class iv_common_cand *const *const ccand2
3428 = (const class iv_common_cand *const *)p2;
3429
3430 n1 = (*ccand1)->uses.length ();
3431 n2 = (*ccand2)->uses.length ();
3432 return n2 - n1;
3433 }
3434
3435 /* Adds IV candidates based on common candidated recorded. */
3436
3437 static void
3438 add_iv_candidate_derived_from_uses (struct ivopts_data *data)
3439 {
3440 unsigned i, j;
3441 struct iv_cand *cand_1, *cand_2;
3442
3443 data->iv_common_cands.qsort (common_cand_cmp);
3444 for (i = 0; i < data->iv_common_cands.length (); i++)
3445 {
3446 class iv_common_cand *ptr = data->iv_common_cands[i];
3447
3448 /* Only add IV candidate if it's derived from multiple uses. */
3449 if (ptr->uses.length () <= 1)
3450 break;
3451
3452 cand_1 = NULL;
3453 cand_2 = NULL;
3454 if (ip_normal_pos (data->current_loop))
3455 cand_1 = add_candidate_1 (data, ptr->base, ptr->step,
3456 false, IP_NORMAL, NULL, NULL);
3457
3458 if (ip_end_pos (data->current_loop)
3459 && allow_ip_end_pos_p (data->current_loop))
3460 cand_2 = add_candidate_1 (data, ptr->base, ptr->step,
3461 false, IP_END, NULL, NULL);
3462
3463 /* Bind deriving uses and the new candidates. */
3464 for (j = 0; j < ptr->uses.length (); j++)
3465 {
3466 struct iv_group *group = data->vgroups[ptr->uses[j]->group_id];
3467 if (cand_1)
3468 bitmap_set_bit (group->related_cands, cand_1->id);
3469 if (cand_2)
3470 bitmap_set_bit (group->related_cands, cand_2->id);
3471 }
3472 }
3473
3474 /* Release data since it is useless from this point. */
3475 data->iv_common_cand_tab->empty ();
3476 data->iv_common_cands.truncate (0);
3477 }
3478
3479 /* Adds candidates based on the value of USE's iv. */
3480
3481 static void
3482 add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
3483 {
3484 poly_uint64 offset;
3485 tree base;
3486 struct iv *iv = use->iv;
3487 tree basetype = TREE_TYPE (iv->base);
3488
3489 /* Don't add candidate for iv_use with non integer, pointer or non-mode
3490 precision types, instead, add candidate for the corresponding scev in
3491 unsigned type with the same precision. See PR93674 for more info. */
3492 if ((TREE_CODE (basetype) != INTEGER_TYPE && !POINTER_TYPE_P (basetype))
3493 || !type_has_mode_precision_p (basetype))
3494 {
3495 basetype = lang_hooks.types.type_for_mode (TYPE_MODE (basetype),
3496 TYPE_UNSIGNED (basetype));
3497 add_candidate (data, fold_convert (basetype, iv->base),
3498 fold_convert (basetype, iv->step), false, NULL);
3499 return;
3500 }
3501
3502 add_candidate (data, iv->base, iv->step, false, use);
3503
3504 /* Record common candidate for use in case it can be shared by others. */
3505 record_common_cand (data, iv->base, iv->step, use);
3506
3507 /* Record common candidate with initial value zero. */
3508 basetype = TREE_TYPE (iv->base);
3509 if (POINTER_TYPE_P (basetype))
3510 basetype = sizetype;
3511 record_common_cand (data, build_int_cst (basetype, 0), iv->step, use);
3512
3513 /* Compare the cost of an address with an unscaled index with the cost of
3514 an address with a scaled index and add candidate if useful. */
3515 poly_int64 step;
3516 if (use != NULL
3517 && poly_int_tree_p (iv->step, &step)
3518 && address_p (use->type))
3519 {
3520 poly_int64 new_step;
3521 unsigned int fact = preferred_mem_scale_factor
3522 (use->iv->base,
3523 TYPE_MODE (use->mem_type),
3524 optimize_loop_for_speed_p (data->current_loop));
3525
3526 if (fact != 1
3527 && multiple_p (step, fact, &new_step))
3528 add_candidate (data, size_int (0),
3529 wide_int_to_tree (sizetype, new_step),
3530 true, NULL);
3531 }
3532
3533 /* Record common candidate with constant offset stripped in base.
3534 Like the use itself, we also add candidate directly for it. */
3535 base = strip_offset (iv->base, &offset);
3536 if (maybe_ne (offset, 0U) || base != iv->base)
3537 {
3538 record_common_cand (data, base, iv->step, use);
3539 add_candidate (data, base, iv->step, false, use);
3540 }
3541
3542 /* Record common candidate with base_object removed in base. */
3543 base = iv->base;
3544 STRIP_NOPS (base);
3545 if (iv->base_object != NULL && TREE_CODE (base) == POINTER_PLUS_EXPR)
3546 {
3547 tree step = iv->step;
3548
3549 STRIP_NOPS (step);
3550 base = TREE_OPERAND (base, 1);
3551 step = fold_convert (sizetype, step);
3552 record_common_cand (data, base, step, use);
3553 /* Also record common candidate with offset stripped. */
3554 tree alt_base, alt_offset;
3555 split_constant_offset (base, &alt_base, &alt_offset);
3556 if (!integer_zerop (alt_offset))
3557 record_common_cand (data, alt_base, step, use);
3558 }
3559
3560 /* At last, add auto-incremental candidates. Make such variables
3561 important since other iv uses with same base object may be based
3562 on it. */
3563 if (use != NULL && address_p (use->type))
3564 add_autoinc_candidates (data, iv->base, iv->step, true, use);
3565 }
3566
3567 /* Adds candidates based on the uses. */
3568
3569 static void
3570 add_iv_candidate_for_groups (struct ivopts_data *data)
3571 {
3572 unsigned i;
3573
3574 /* Only add candidate for the first use in group. */
3575 for (i = 0; i < data->vgroups.length (); i++)
3576 {
3577 struct iv_group *group = data->vgroups[i];
3578
3579 gcc_assert (group->vuses[0] != NULL);
3580 add_iv_candidate_for_use (data, group->vuses[0]);
3581 }
3582 add_iv_candidate_derived_from_uses (data);
3583 }
3584
3585 /* Record important candidates and add them to related_cands bitmaps. */
3586
3587 static void
3588 record_important_candidates (struct ivopts_data *data)
3589 {
3590 unsigned i;
3591 struct iv_group *group;
3592
3593 for (i = 0; i < data->vcands.length (); i++)
3594 {
3595 struct iv_cand *cand = data->vcands[i];
3596
3597 if (cand->important)
3598 bitmap_set_bit (data->important_candidates, i);
3599 }
3600
3601 data->consider_all_candidates = (data->vcands.length ()
3602 <= CONSIDER_ALL_CANDIDATES_BOUND);
3603
3604 /* Add important candidates to groups' related_cands bitmaps. */
3605 for (i = 0; i < data->vgroups.length (); i++)
3606 {
3607 group = data->vgroups[i];
3608 bitmap_ior_into (group->related_cands, data->important_candidates);
3609 }
3610 }
3611
3612 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
3613 If consider_all_candidates is true, we use a two-dimensional array, otherwise
3614 we allocate a simple list to every use. */
3615
3616 static void
3617 alloc_use_cost_map (struct ivopts_data *data)
3618 {
3619 unsigned i, size, s;
3620
3621 for (i = 0; i < data->vgroups.length (); i++)
3622 {
3623 struct iv_group *group = data->vgroups[i];
3624
3625 if (data->consider_all_candidates)
3626 size = data->vcands.length ();
3627 else
3628 {
3629 s = bitmap_count_bits (group->related_cands);
3630
3631 /* Round up to the power of two, so that moduling by it is fast. */
3632 size = s ? (1 << ceil_log2 (s)) : 1;
3633 }
3634
3635 group->n_map_members = size;
3636 group->cost_map = XCNEWVEC (class cost_pair, size);
3637 }
3638 }
3639
3640 /* Sets cost of (GROUP, CAND) pair to COST and record that it depends
3641 on invariants INV_VARS and that the value used in expressing it is
3642 VALUE, and in case of iv elimination the comparison operator is COMP. */
3643
3644 static void
3645 set_group_iv_cost (struct ivopts_data *data,
3646 struct iv_group *group, struct iv_cand *cand,
3647 comp_cost cost, bitmap inv_vars, tree value,
3648 enum tree_code comp, bitmap inv_exprs)
3649 {
3650 unsigned i, s;
3651
3652 if (cost.infinite_cost_p ())
3653 {
3654 BITMAP_FREE (inv_vars);
3655 BITMAP_FREE (inv_exprs);
3656 return;
3657 }
3658
3659 if (data->consider_all_candidates)
3660 {
3661 group->cost_map[cand->id].cand = cand;
3662 group->cost_map[cand->id].cost = cost;
3663 group->cost_map[cand->id].inv_vars = inv_vars;
3664 group->cost_map[cand->id].inv_exprs = inv_exprs;
3665 group->cost_map[cand->id].value = value;
3666 group->cost_map[cand->id].comp = comp;
3667 return;
3668 }
3669
3670 /* n_map_members is a power of two, so this computes modulo. */
3671 s = cand->id & (group->n_map_members - 1);
3672 for (i = s; i < group->n_map_members; i++)
3673 if (!group->cost_map[i].cand)
3674 goto found;
3675 for (i = 0; i < s; i++)
3676 if (!group->cost_map[i].cand)
3677 goto found;
3678
3679 gcc_unreachable ();
3680
3681 found:
3682 group->cost_map[i].cand = cand;
3683 group->cost_map[i].cost = cost;
3684 group->cost_map[i].inv_vars = inv_vars;
3685 group->cost_map[i].inv_exprs = inv_exprs;
3686 group->cost_map[i].value = value;
3687 group->cost_map[i].comp = comp;
3688 }
3689
3690 /* Gets cost of (GROUP, CAND) pair. */
3691
3692 static class cost_pair *
3693 get_group_iv_cost (struct ivopts_data *data, struct iv_group *group,
3694 struct iv_cand *cand)
3695 {
3696 unsigned i, s;
3697 class cost_pair *ret;
3698
3699 if (!cand)
3700 return NULL;
3701
3702 if (data->consider_all_candidates)
3703 {
3704 ret = group->cost_map + cand->id;
3705 if (!ret->cand)
3706 return NULL;
3707
3708 return ret;
3709 }
3710
3711 /* n_map_members is a power of two, so this computes modulo. */
3712 s = cand->id & (group->n_map_members - 1);
3713 for (i = s; i < group->n_map_members; i++)
3714 if (group->cost_map[i].cand == cand)
3715 return group->cost_map + i;
3716 else if (group->cost_map[i].cand == NULL)
3717 return NULL;
3718 for (i = 0; i < s; i++)
3719 if (group->cost_map[i].cand == cand)
3720 return group->cost_map + i;
3721 else if (group->cost_map[i].cand == NULL)
3722 return NULL;
3723
3724 return NULL;
3725 }
3726
3727 /* Produce DECL_RTL for object obj so it looks like it is stored in memory. */
3728 static rtx
3729 produce_memory_decl_rtl (tree obj, int *regno)
3730 {
3731 addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (obj));
3732 machine_mode address_mode = targetm.addr_space.address_mode (as);
3733 rtx x;
3734
3735 gcc_assert (obj);
3736 if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
3737 {
3738 const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
3739 x = gen_rtx_SYMBOL_REF (address_mode, name);
3740 SET_SYMBOL_REF_DECL (x, obj);
3741 x = gen_rtx_MEM (DECL_MODE (obj), x);
3742 set_mem_addr_space (x, as);
3743 targetm.encode_section_info (obj, x, true);
3744 }
3745 else
3746 {
3747 x = gen_raw_REG (address_mode, (*regno)++);
3748 x = gen_rtx_MEM (DECL_MODE (obj), x);
3749 set_mem_addr_space (x, as);
3750 }
3751
3752 return x;
3753 }
3754
3755 /* Prepares decl_rtl for variables referred in *EXPR_P. Callback for
3756 walk_tree. DATA contains the actual fake register number. */
3757
3758 static tree
3759 prepare_decl_rtl (tree *expr_p, int *ws, void *data)
3760 {
3761 tree obj = NULL_TREE;
3762 rtx x = NULL_RTX;
3763 int *regno = (int *) data;
3764
3765 switch (TREE_CODE (*expr_p))
3766 {
3767 case ADDR_EXPR:
3768 for (expr_p = &TREE_OPERAND (*expr_p, 0);
3769 handled_component_p (*expr_p);
3770 expr_p = &TREE_OPERAND (*expr_p, 0))
3771 continue;
3772 obj = *expr_p;
3773 if (DECL_P (obj) && HAS_RTL_P (obj) && !DECL_RTL_SET_P (obj))
3774 x = produce_memory_decl_rtl (obj, regno);
3775 break;
3776
3777 case SSA_NAME:
3778 *ws = 0;
3779 obj = SSA_NAME_VAR (*expr_p);
3780 /* Defer handling of anonymous SSA_NAMEs to the expander. */
3781 if (!obj)
3782 return NULL_TREE;
3783 if (!DECL_RTL_SET_P (obj))
3784 x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
3785 break;
3786
3787 case VAR_DECL:
3788 case PARM_DECL:
3789 case RESULT_DECL:
3790 *ws = 0;
3791 obj = *expr_p;
3792
3793 if (DECL_RTL_SET_P (obj))
3794 break;
3795
3796 if (DECL_MODE (obj) == BLKmode)
3797 x = produce_memory_decl_rtl (obj, regno);
3798 else
3799 x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
3800
3801 break;
3802
3803 default:
3804 break;
3805 }
3806
3807 if (x)
3808 {
3809 decl_rtl_to_reset.safe_push (obj);
3810 SET_DECL_RTL (obj, x);
3811 }
3812
3813 return NULL_TREE;
3814 }
3815
3816 /* Predict whether the given loop will be transformed in the RTL
3817 doloop_optimize pass. Attempt to duplicate some doloop_optimize checks.
3818 This is only for target independent checks, see targetm.predict_doloop_p
3819 for the target dependent ones.
3820
3821 Note that according to some initial investigation, some checks like costly
3822 niter check and invalid stmt scanning don't have much gains among general
3823 cases, so keep this as simple as possible first.
3824
3825 Some RTL specific checks seems unable to be checked in gimple, if any new
3826 checks or easy checks _are_ missing here, please add them. */
3827
3828 static bool
3829 generic_predict_doloop_p (struct ivopts_data *data)
3830 {
3831 class loop *loop = data->current_loop;
3832
3833 /* Call target hook for target dependent checks. */
3834 if (!targetm.predict_doloop_p (loop))
3835 {
3836 if (dump_file && (dump_flags & TDF_DETAILS))
3837 fprintf (dump_file, "Predict doloop failure due to"
3838 " target specific checks.\n");
3839 return false;
3840 }
3841
3842 /* Similar to doloop_optimize, check iteration description to know it's
3843 suitable or not. Keep it as simple as possible, feel free to extend it
3844 if you find any multiple exits cases matter. */
3845 edge exit = single_dom_exit (loop);
3846 class tree_niter_desc *niter_desc;
3847 if (!exit || !(niter_desc = niter_for_exit (data, exit)))
3848 {
3849 if (dump_file && (dump_flags & TDF_DETAILS))
3850 fprintf (dump_file, "Predict doloop failure due to"
3851 " unexpected niters.\n");
3852 return false;
3853 }
3854
3855 /* Similar to doloop_optimize, check whether iteration count too small
3856 and not profitable. */
3857 HOST_WIDE_INT est_niter = get_estimated_loop_iterations_int (loop);
3858 if (est_niter == -1)
3859 est_niter = get_likely_max_loop_iterations_int (loop);
3860 if (est_niter >= 0 && est_niter < 3)
3861 {
3862 if (dump_file && (dump_flags & TDF_DETAILS))
3863 fprintf (dump_file,
3864 "Predict doloop failure due to"
3865 " too few iterations (%u).\n",
3866 (unsigned int) est_niter);
3867 return false;
3868 }
3869
3870 return true;
3871 }
3872
3873 /* Determines cost of the computation of EXPR. */
3874
3875 static unsigned
3876 computation_cost (tree expr, bool speed)
3877 {
3878 rtx_insn *seq;
3879 rtx rslt;
3880 tree type = TREE_TYPE (expr);
3881 unsigned cost;
3882 /* Avoid using hard regs in ways which may be unsupported. */
3883 int regno = LAST_VIRTUAL_REGISTER + 1;
3884 struct cgraph_node *node = cgraph_node::get (current_function_decl);
3885 enum node_frequency real_frequency = node->frequency;
3886
3887 node->frequency = NODE_FREQUENCY_NORMAL;
3888 crtl->maybe_hot_insn_p = speed;
3889 walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
3890 start_sequence ();
3891 rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
3892 seq = get_insns ();
3893 end_sequence ();
3894 default_rtl_profile ();
3895 node->frequency = real_frequency;
3896
3897 cost = seq_cost (seq, speed);
3898 if (MEM_P (rslt))
3899 cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type),
3900 TYPE_ADDR_SPACE (type), speed);
3901 else if (!REG_P (rslt))
3902 cost += set_src_cost (rslt, TYPE_MODE (type), speed);
3903
3904 return cost;
3905 }
3906
3907 /* Returns variable containing the value of candidate CAND at statement AT. */
3908
3909 static tree
3910 var_at_stmt (class loop *loop, struct iv_cand *cand, gimple *stmt)
3911 {
3912 if (stmt_after_increment (loop, cand, stmt))
3913 return cand->var_after;
3914 else
3915 return cand->var_before;
3916 }
3917
3918 /* If A is (TYPE) BA and B is (TYPE) BB, and the types of BA and BB have the
3919 same precision that is at least as wide as the precision of TYPE, stores
3920 BA to A and BB to B, and returns the type of BA. Otherwise, returns the
3921 type of A and B. */
3922
3923 static tree
3924 determine_common_wider_type (tree *a, tree *b)
3925 {
3926 tree wider_type = NULL;
3927 tree suba, subb;
3928 tree atype = TREE_TYPE (*a);
3929
3930 if (CONVERT_EXPR_P (*a))
3931 {
3932 suba = TREE_OPERAND (*a, 0);
3933 wider_type = TREE_TYPE (suba);
3934 if (TYPE_PRECISION (wider_type) < TYPE_PRECISION (atype))
3935 return atype;
3936 }
3937 else
3938 return atype;
3939
3940 if (CONVERT_EXPR_P (*b))
3941 {
3942 subb = TREE_OPERAND (*b, 0);
3943 if (TYPE_PRECISION (wider_type) != TYPE_PRECISION (TREE_TYPE (subb)))
3944 return atype;
3945 }
3946 else
3947 return atype;
3948
3949 *a = suba;
3950 *b = subb;
3951 return wider_type;
3952 }
3953
3954 /* Determines the expression by that USE is expressed from induction variable
3955 CAND at statement AT in LOOP. The expression is stored in two parts in a
3956 decomposed form. The invariant part is stored in AFF_INV; while variant
3957 part in AFF_VAR. Store ratio of CAND.step over USE.step in PRAT if it's
3958 non-null. Returns false if USE cannot be expressed using CAND. */
3959
3960 static bool
3961 get_computation_aff_1 (class loop *loop, gimple *at, struct iv_use *use,
3962 struct iv_cand *cand, class aff_tree *aff_inv,
3963 class aff_tree *aff_var, widest_int *prat = NULL)
3964 {
3965 tree ubase = use->iv->base, ustep = use->iv->step;
3966 tree cbase = cand->iv->base, cstep = cand->iv->step;
3967 tree common_type, uutype, var, cstep_common;
3968 tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
3969 aff_tree aff_cbase;
3970 widest_int rat;
3971
3972 /* We must have a precision to express the values of use. */
3973 if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
3974 return false;
3975
3976 var = var_at_stmt (loop, cand, at);
3977 uutype = unsigned_type_for (utype);
3978
3979 /* If the conversion is not noop, perform it. */
3980 if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
3981 {
3982 if (cand->orig_iv != NULL && CONVERT_EXPR_P (cbase)
3983 && (CONVERT_EXPR_P (cstep) || poly_int_tree_p (cstep)))
3984 {
3985 tree inner_base, inner_step, inner_type;
3986 inner_base = TREE_OPERAND (cbase, 0);
3987 if (CONVERT_EXPR_P (cstep))
3988 inner_step = TREE_OPERAND (cstep, 0);
3989 else
3990 inner_step = cstep;
3991
3992 inner_type = TREE_TYPE (inner_base);
3993 /* If candidate is added from a biv whose type is smaller than
3994 ctype, we know both candidate and the biv won't overflow.
3995 In this case, it's safe to skip the convertion in candidate.
3996 As an example, (unsigned short)((unsigned long)A) equals to
3997 (unsigned short)A, if A has a type no larger than short. */
3998 if (TYPE_PRECISION (inner_type) <= TYPE_PRECISION (uutype))
3999 {
4000 cbase = inner_base;
4001 cstep = inner_step;
4002 }
4003 }
4004 cbase = fold_convert (uutype, cbase);
4005 cstep = fold_convert (uutype, cstep);
4006 var = fold_convert (uutype, var);
4007 }
4008
4009 /* Ratio is 1 when computing the value of biv cand by itself.
4010 We can't rely on constant_multiple_of in this case because the
4011 use is created after the original biv is selected. The call
4012 could fail because of inconsistent fold behavior. See PR68021
4013 for more information. */
4014 if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
4015 {
4016 gcc_assert (is_gimple_assign (use->stmt));
4017 gcc_assert (use->iv->ssa_name == cand->var_after);
4018 gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
4019 rat = 1;
4020 }
4021 else if (!constant_multiple_of (ustep, cstep, &rat))
4022 return false;
4023
4024 if (prat)
4025 *prat = rat;
4026
4027 /* In case both UBASE and CBASE are shortened to UUTYPE from some common
4028 type, we achieve better folding by computing their difference in this
4029 wider type, and cast the result to UUTYPE. We do not need to worry about
4030 overflows, as all the arithmetics will in the end be performed in UUTYPE
4031 anyway. */
4032 common_type = determine_common_wider_type (&ubase, &cbase);
4033
4034 /* use = ubase - ratio * cbase + ratio * var. */
4035 tree_to_aff_combination (ubase, common_type, aff_inv);
4036 tree_to_aff_combination (cbase, common_type, &aff_cbase);
4037 tree_to_aff_combination (var, uutype, aff_var);
4038
4039 /* We need to shift the value if we are after the increment. */
4040 if (stmt_after_increment (loop, cand, at))
4041 {
4042 aff_tree cstep_aff;
4043
4044 if (common_type != uutype)
4045 cstep_common = fold_convert (common_type, cstep);
4046 else
4047 cstep_common = cstep;
4048
4049 tree_to_aff_combination (cstep_common, common_type, &cstep_aff);
4050 aff_combination_add (&aff_cbase, &cstep_aff);
4051 }
4052
4053 aff_combination_scale (&aff_cbase, -rat);
4054 aff_combination_add (aff_inv, &aff_cbase);
4055 if (common_type != uutype)
4056 aff_combination_convert (aff_inv, uutype);
4057
4058 aff_combination_scale (aff_var, rat);
4059 return true;
4060 }
4061
4062 /* Determines the expression by that USE is expressed from induction variable
4063 CAND at statement AT in LOOP. The expression is stored in a decomposed
4064 form into AFF. Returns false if USE cannot be expressed using CAND. */
4065
4066 static bool
4067 get_computation_aff (class loop *loop, gimple *at, struct iv_use *use,
4068 struct iv_cand *cand, class aff_tree *aff)
4069 {
4070 aff_tree aff_var;
4071
4072 if (!get_computation_aff_1 (loop, at, use, cand, aff, &aff_var))
4073 return false;
4074
4075 aff_combination_add (aff, &aff_var);
4076 return true;
4077 }
4078
4079 /* Return the type of USE. */
4080
4081 static tree
4082 get_use_type (struct iv_use *use)
4083 {
4084 tree base_type = TREE_TYPE (use->iv->base);
4085 tree type;
4086
4087 if (use->type == USE_REF_ADDRESS)
4088 {
4089 /* The base_type may be a void pointer. Create a pointer type based on
4090 the mem_ref instead. */
4091 type = build_pointer_type (TREE_TYPE (*use->op_p));
4092 gcc_assert (TYPE_ADDR_SPACE (TREE_TYPE (type))
4093 == TYPE_ADDR_SPACE (TREE_TYPE (base_type)));
4094 }
4095 else
4096 type = base_type;
4097
4098 return type;
4099 }
4100
4101 /* Determines the expression by that USE is expressed from induction variable
4102 CAND at statement AT in LOOP. The computation is unshared. */
4103
4104 static tree
4105 get_computation_at (class loop *loop, gimple *at,
4106 struct iv_use *use, struct iv_cand *cand)
4107 {
4108 aff_tree aff;
4109 tree type = get_use_type (use);
4110
4111 if (!get_computation_aff (loop, at, use, cand, &aff))
4112 return NULL_TREE;
4113 unshare_aff_combination (&aff);
4114 return fold_convert (type, aff_combination_to_tree (&aff));
4115 }
4116
4117 /* Like get_computation_at, but try harder, even if the computation
4118 is more expensive. Intended for debug stmts. */
4119
4120 static tree
4121 get_debug_computation_at (class loop *loop, gimple *at,
4122 struct iv_use *use, struct iv_cand *cand)
4123 {
4124 if (tree ret = get_computation_at (loop, at, use, cand))
4125 return ret;
4126
4127 tree ubase = use->iv->base, ustep = use->iv->step;
4128 tree cbase = cand->iv->base, cstep = cand->iv->step;
4129 tree var;
4130 tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
4131 widest_int rat;
4132
4133 /* We must have a precision to express the values of use. */
4134 if (TYPE_PRECISION (utype) >= TYPE_PRECISION (ctype))
4135 return NULL_TREE;
4136
4137 /* Try to handle the case that get_computation_at doesn't,
4138 try to express
4139 use = ubase + (var - cbase) / ratio. */
4140 if (!constant_multiple_of (cstep, fold_convert (TREE_TYPE (cstep), ustep),
4141 &rat))
4142 return NULL_TREE;
4143
4144 bool neg_p = false;
4145 if (wi::neg_p (rat))
4146 {
4147 if (TYPE_UNSIGNED (ctype))
4148 return NULL_TREE;
4149 neg_p = true;
4150 rat = wi::neg (rat);
4151 }
4152
4153 /* If both IVs can wrap around and CAND doesn't have a power of two step,
4154 it is unsafe. Consider uint16_t CAND with step 9, when wrapping around,
4155 the values will be ... 0xfff0, 0xfff9, 2, 11 ... and when use is say
4156 uint8_t with step 3, those values divided by 3 cast to uint8_t will be
4157 ... 0x50, 0x53, 0, 3 ... rather than expected 0x50, 0x53, 0x56, 0x59. */
4158 if (!use->iv->no_overflow
4159 && !cand->iv->no_overflow
4160 && !integer_pow2p (cstep))
4161 return NULL_TREE;
4162
4163 int bits = wi::exact_log2 (rat);
4164 if (bits == -1)
4165 bits = wi::floor_log2 (rat) + 1;
4166 if (!cand->iv->no_overflow
4167 && TYPE_PRECISION (utype) + bits > TYPE_PRECISION (ctype))
4168 return NULL_TREE;
4169
4170 var = var_at_stmt (loop, cand, at);
4171
4172 if (POINTER_TYPE_P (ctype))
4173 {
4174 ctype = unsigned_type_for (ctype);
4175 cbase = fold_convert (ctype, cbase);
4176 cstep = fold_convert (ctype, cstep);
4177 var = fold_convert (ctype, var);
4178 }
4179
4180 if (stmt_after_increment (loop, cand, at))
4181 var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var,
4182 unshare_expr (cstep));
4183
4184 var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var, cbase);
4185 var = fold_build2 (EXACT_DIV_EXPR, TREE_TYPE (var), var,
4186 wide_int_to_tree (TREE_TYPE (var), rat));
4187 if (POINTER_TYPE_P (utype))
4188 {
4189 var = fold_convert (sizetype, var);
4190 if (neg_p)
4191 var = fold_build1 (NEGATE_EXPR, sizetype, var);
4192 var = fold_build2 (POINTER_PLUS_EXPR, utype, ubase, var);
4193 }
4194 else
4195 {
4196 var = fold_convert (utype, var);
4197 var = fold_build2 (neg_p ? MINUS_EXPR : PLUS_EXPR, utype,
4198 ubase, var);
4199 }
4200 return var;
4201 }
4202
4203 /* Adjust the cost COST for being in loop setup rather than loop body.
4204 If we're optimizing for space, the loop setup overhead is constant;
4205 if we're optimizing for speed, amortize it over the per-iteration cost.
4206 If ROUND_UP_P is true, the result is round up rather than to zero when
4207 optimizing for speed. */
4208 static int64_t
4209 adjust_setup_cost (struct ivopts_data *data, int64_t cost,
4210 bool round_up_p = false)
4211 {
4212 if (cost == INFTY)
4213 return cost;
4214 else if (optimize_loop_for_speed_p (data->current_loop))
4215 {
4216 int64_t niters = (int64_t) avg_loop_niter (data->current_loop);
4217 return (cost + (round_up_p ? niters - 1 : 0)) / niters;
4218 }
4219 else
4220 return cost;
4221 }
4222
4223 /* Calculate the SPEED or size cost of shiftadd EXPR in MODE. MULT is the
4224 EXPR operand holding the shift. COST0 and COST1 are the costs for
4225 calculating the operands of EXPR. Returns true if successful, and returns
4226 the cost in COST. */
4227
4228 static bool
4229 get_shiftadd_cost (tree expr, scalar_int_mode mode, comp_cost cost0,
4230 comp_cost cost1, tree mult, bool speed, comp_cost *cost)
4231 {
4232 comp_cost res;
4233 tree op1 = TREE_OPERAND (expr, 1);
4234 tree cst = TREE_OPERAND (mult, 1);
4235 tree multop = TREE_OPERAND (mult, 0);
4236 int m = exact_log2 (int_cst_value (cst));
4237 int maxm = MIN (BITS_PER_WORD, GET_MODE_BITSIZE (mode));
4238 int as_cost, sa_cost;
4239 bool mult_in_op1;
4240
4241 if (!(m >= 0 && m < maxm))
4242 return false;
4243
4244 STRIP_NOPS (op1);
4245 mult_in_op1 = operand_equal_p (op1, mult, 0);
4246
4247 as_cost = add_cost (speed, mode) + shift_cost (speed, mode, m);
4248
4249 /* If the target has a cheap shift-and-add or shift-and-sub instruction,
4250 use that in preference to a shift insn followed by an add insn. */
4251 sa_cost = (TREE_CODE (expr) != MINUS_EXPR
4252 ? shiftadd_cost (speed, mode, m)
4253 : (mult_in_op1
4254 ? shiftsub1_cost (speed, mode, m)
4255 : shiftsub0_cost (speed, mode, m)));
4256
4257 res = comp_cost (MIN (as_cost, sa_cost), 0);
4258 res += (mult_in_op1 ? cost0 : cost1);
4259
4260 STRIP_NOPS (multop);
4261 if (!is_gimple_val (multop))
4262 res += force_expr_to_var_cost (multop, speed);
4263
4264 *cost = res;
4265 return true;
4266 }
4267
4268 /* Estimates cost of forcing expression EXPR into a variable. */
4269
4270 static comp_cost
4271 force_expr_to_var_cost (tree expr, bool speed)
4272 {
4273 static bool costs_initialized = false;
4274 static unsigned integer_cost [2];
4275 static unsigned symbol_cost [2];
4276 static unsigned address_cost [2];
4277 tree op0, op1;
4278 comp_cost cost0, cost1, cost;
4279 machine_mode mode;
4280 scalar_int_mode int_mode;
4281
4282 if (!costs_initialized)
4283 {
4284 tree type = build_pointer_type (integer_type_node);
4285 tree var, addr;
4286 rtx x;
4287 int i;
4288
4289 var = create_tmp_var_raw (integer_type_node, "test_var");
4290 TREE_STATIC (var) = 1;
4291 x = produce_memory_decl_rtl (var, NULL);
4292 SET_DECL_RTL (var, x);
4293
4294 addr = build1 (ADDR_EXPR, type, var);
4295
4296
4297 for (i = 0; i < 2; i++)
4298 {
4299 integer_cost[i] = computation_cost (build_int_cst (integer_type_node,
4300 2000), i);
4301
4302 symbol_cost[i] = computation_cost (addr, i) + 1;
4303
4304 address_cost[i]
4305 = computation_cost (fold_build_pointer_plus_hwi (addr, 2000), i) + 1;
4306 if (dump_file && (dump_flags & TDF_DETAILS))
4307 {
4308 fprintf (dump_file, "force_expr_to_var_cost %s costs:\n", i ? "speed" : "size");
4309 fprintf (dump_file, " integer %d\n", (int) integer_cost[i]);
4310 fprintf (dump_file, " symbol %d\n", (int) symbol_cost[i]);
4311 fprintf (dump_file, " address %d\n", (int) address_cost[i]);
4312 fprintf (dump_file, " other %d\n", (int) target_spill_cost[i]);
4313 fprintf (dump_file, "\n");
4314 }
4315 }
4316
4317 costs_initialized = true;
4318 }
4319
4320 STRIP_NOPS (expr);
4321
4322 if (SSA_VAR_P (expr))
4323 return no_cost;
4324
4325 if (is_gimple_min_invariant (expr))
4326 {
4327 if (poly_int_tree_p (expr))
4328 return comp_cost (integer_cost [speed], 0);
4329
4330 if (TREE_CODE (expr) == ADDR_EXPR)
4331 {
4332 tree obj = TREE_OPERAND (expr, 0);
4333
4334 if (VAR_P (obj)
4335 || TREE_CODE (obj) == PARM_DECL
4336 || TREE_CODE (obj) == RESULT_DECL)
4337 return comp_cost (symbol_cost [speed], 0);
4338 }
4339
4340 return comp_cost (address_cost [speed], 0);
4341 }
4342
4343 switch (TREE_CODE (expr))
4344 {
4345 case POINTER_PLUS_EXPR:
4346 case PLUS_EXPR:
4347 case MINUS_EXPR:
4348 case MULT_EXPR:
4349 case EXACT_DIV_EXPR:
4350 case TRUNC_DIV_EXPR:
4351 case BIT_AND_EXPR:
4352 case BIT_IOR_EXPR:
4353 case LSHIFT_EXPR:
4354 case RSHIFT_EXPR:
4355 op0 = TREE_OPERAND (expr, 0);
4356 op1 = TREE_OPERAND (expr, 1);
4357 STRIP_NOPS (op0);
4358 STRIP_NOPS (op1);
4359 break;
4360
4361 CASE_CONVERT:
4362 case NEGATE_EXPR:
4363 case BIT_NOT_EXPR:
4364 op0 = TREE_OPERAND (expr, 0);
4365 STRIP_NOPS (op0);
4366 op1 = NULL_TREE;
4367 break;
4368 /* See add_iv_candidate_for_doloop, for doloop may_be_zero case, we
4369 introduce COND_EXPR for IV base, need to support better cost estimation
4370 for this COND_EXPR and tcc_comparison. */
4371 case COND_EXPR:
4372 op0 = TREE_OPERAND (expr, 1);
4373 STRIP_NOPS (op0);
4374 op1 = TREE_OPERAND (expr, 2);
4375 STRIP_NOPS (op1);
4376 break;
4377 case LT_EXPR:
4378 case LE_EXPR:
4379 case GT_EXPR:
4380 case GE_EXPR:
4381 case EQ_EXPR:
4382 case NE_EXPR:
4383 case UNORDERED_EXPR:
4384 case ORDERED_EXPR:
4385 case UNLT_EXPR:
4386 case UNLE_EXPR:
4387 case UNGT_EXPR:
4388 case UNGE_EXPR:
4389 case UNEQ_EXPR:
4390 case LTGT_EXPR:
4391 case MAX_EXPR:
4392 case MIN_EXPR:
4393 op0 = TREE_OPERAND (expr, 0);
4394 STRIP_NOPS (op0);
4395 op1 = TREE_OPERAND (expr, 1);
4396 STRIP_NOPS (op1);
4397 break;
4398
4399 default:
4400 /* Just an arbitrary value, FIXME. */
4401 return comp_cost (target_spill_cost[speed], 0);
4402 }
4403
4404 if (op0 == NULL_TREE
4405 || TREE_CODE (op0) == SSA_NAME || CONSTANT_CLASS_P (op0))
4406 cost0 = no_cost;
4407 else
4408 cost0 = force_expr_to_var_cost (op0, speed);
4409
4410 if (op1 == NULL_TREE
4411 || TREE_CODE (op1) == SSA_NAME || CONSTANT_CLASS_P (op1))
4412 cost1 = no_cost;
4413 else
4414 cost1 = force_expr_to_var_cost (op1, speed);
4415
4416 mode = TYPE_MODE (TREE_TYPE (expr));
4417 switch (TREE_CODE (expr))
4418 {
4419 case POINTER_PLUS_EXPR:
4420 case PLUS_EXPR:
4421 case MINUS_EXPR:
4422 case NEGATE_EXPR:
4423 cost = comp_cost (add_cost (speed, mode), 0);
4424 if (TREE_CODE (expr) != NEGATE_EXPR)
4425 {
4426 tree mult = NULL_TREE;
4427 comp_cost sa_cost;
4428 if (TREE_CODE (op1) == MULT_EXPR)
4429 mult = op1;
4430 else if (TREE_CODE (op0) == MULT_EXPR)
4431 mult = op0;
4432
4433 if (mult != NULL_TREE
4434 && is_a <scalar_int_mode> (mode, &int_mode)
4435 && cst_and_fits_in_hwi (TREE_OPERAND (mult, 1))
4436 && get_shiftadd_cost (expr, int_mode, cost0, cost1, mult,
4437 speed, &sa_cost))
4438 return sa_cost;
4439 }
4440 break;
4441
4442 CASE_CONVERT:
4443 {
4444 tree inner_mode, outer_mode;
4445 outer_mode = TREE_TYPE (expr);
4446 inner_mode = TREE_TYPE (op0);
4447 cost = comp_cost (convert_cost (TYPE_MODE (outer_mode),
4448 TYPE_MODE (inner_mode), speed), 0);
4449 }
4450 break;
4451
4452 case MULT_EXPR:
4453 if (cst_and_fits_in_hwi (op0))
4454 cost = comp_cost (mult_by_coeff_cost (int_cst_value (op0),
4455 mode, speed), 0);
4456 else if (cst_and_fits_in_hwi (op1))
4457 cost = comp_cost (mult_by_coeff_cost (int_cst_value (op1),
4458 mode, speed), 0);
4459 else
4460 return comp_cost (target_spill_cost [speed], 0);
4461 break;
4462
4463 case EXACT_DIV_EXPR:
4464 case TRUNC_DIV_EXPR:
4465 /* Division by power of two is usually cheap, so we allow it. Forbid
4466 anything else. */
4467 if (integer_pow2p (TREE_OPERAND (expr, 1)))
4468 cost = comp_cost (add_cost (speed, mode), 0);
4469 else
4470 cost = comp_cost (target_spill_cost[speed], 0);
4471 break;
4472
4473 case BIT_AND_EXPR:
4474 case BIT_IOR_EXPR:
4475 case BIT_NOT_EXPR:
4476 case LSHIFT_EXPR:
4477 case RSHIFT_EXPR:
4478 cost = comp_cost (add_cost (speed, mode), 0);
4479 break;
4480 case COND_EXPR:
4481 op0 = TREE_OPERAND (expr, 0);
4482 STRIP_NOPS (op0);
4483 if (op0 == NULL_TREE || TREE_CODE (op0) == SSA_NAME
4484 || CONSTANT_CLASS_P (op0))
4485 cost = no_cost;
4486 else
4487 cost = force_expr_to_var_cost (op0, speed);
4488 break;
4489 case LT_EXPR:
4490 case LE_EXPR:
4491 case GT_EXPR:
4492 case GE_EXPR:
4493 case EQ_EXPR:
4494 case NE_EXPR:
4495 case UNORDERED_EXPR:
4496 case ORDERED_EXPR:
4497 case UNLT_EXPR:
4498 case UNLE_EXPR:
4499 case UNGT_EXPR:
4500 case UNGE_EXPR:
4501 case UNEQ_EXPR:
4502 case LTGT_EXPR:
4503 case MAX_EXPR:
4504 case MIN_EXPR:
4505 /* Simply use add cost for now, FIXME if there is some more accurate cost
4506 evaluation way. */
4507 cost = comp_cost (add_cost (speed, mode), 0);
4508 break;
4509
4510 default:
4511 gcc_unreachable ();
4512 }
4513
4514 cost += cost0;
4515 cost += cost1;
4516 return cost;
4517 }
4518
4519 /* Estimates cost of forcing EXPR into a variable. INV_VARS is a set of the
4520 invariants the computation depends on. */
4521
4522 static comp_cost
4523 force_var_cost (struct ivopts_data *data, tree expr, bitmap *inv_vars)
4524 {
4525 if (!expr)
4526 return no_cost;
4527
4528 find_inv_vars (data, &expr, inv_vars);
4529 return force_expr_to_var_cost (expr, data->speed);
4530 }
4531
4532 /* Returns cost of auto-modifying address expression in shape base + offset.
4533 AINC_STEP is step size of the address IV. AINC_OFFSET is offset of the
4534 address expression. The address expression has ADDR_MODE in addr space
4535 AS. The memory access has MEM_MODE. SPEED means we are optimizing for
4536 speed or size. */
4537
4538 enum ainc_type
4539 {
4540 AINC_PRE_INC, /* Pre increment. */
4541 AINC_PRE_DEC, /* Pre decrement. */
4542 AINC_POST_INC, /* Post increment. */
4543 AINC_POST_DEC, /* Post decrement. */
4544 AINC_NONE /* Also the number of auto increment types. */
4545 };
4546
4547 struct ainc_cost_data
4548 {
4549 int64_t costs[AINC_NONE];
4550 };
4551
4552 static comp_cost
4553 get_address_cost_ainc (poly_int64 ainc_step, poly_int64 ainc_offset,
4554 machine_mode addr_mode, machine_mode mem_mode,
4555 addr_space_t as, bool speed)
4556 {
4557 if (!USE_LOAD_PRE_DECREMENT (mem_mode)
4558 && !USE_STORE_PRE_DECREMENT (mem_mode)
4559 && !USE_LOAD_POST_DECREMENT (mem_mode)
4560 && !USE_STORE_POST_DECREMENT (mem_mode)
4561 && !USE_LOAD_PRE_INCREMENT (mem_mode)
4562 && !USE_STORE_PRE_INCREMENT (mem_mode)
4563 && !USE_LOAD_POST_INCREMENT (mem_mode)
4564 && !USE_STORE_POST_INCREMENT (mem_mode))
4565 return infinite_cost;
4566
4567 static vec<ainc_cost_data *> ainc_cost_data_list;
4568 unsigned idx = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
4569 if (idx >= ainc_cost_data_list.length ())
4570 {
4571 unsigned nsize = ((unsigned) as + 1) *MAX_MACHINE_MODE;
4572
4573 gcc_assert (nsize > idx);
4574 ainc_cost_data_list.safe_grow_cleared (nsize, true);
4575 }
4576
4577 ainc_cost_data *data = ainc_cost_data_list[idx];
4578 if (data == NULL)
4579 {
4580 rtx reg = gen_raw_REG (addr_mode, LAST_VIRTUAL_REGISTER + 1);
4581
4582 data = (ainc_cost_data *) xcalloc (1, sizeof (*data));
4583 data->costs[AINC_PRE_DEC] = INFTY;
4584 data->costs[AINC_POST_DEC] = INFTY;
4585 data->costs[AINC_PRE_INC] = INFTY;
4586 data->costs[AINC_POST_INC] = INFTY;
4587 if (USE_LOAD_PRE_DECREMENT (mem_mode)
4588 || USE_STORE_PRE_DECREMENT (mem_mode))
4589 {
4590 rtx addr = gen_rtx_PRE_DEC (addr_mode, reg);
4591
4592 if (memory_address_addr_space_p (mem_mode, addr, as))
4593 data->costs[AINC_PRE_DEC]
4594 = address_cost (addr, mem_mode, as, speed);
4595 }
4596 if (USE_LOAD_POST_DECREMENT (mem_mode)
4597 || USE_STORE_POST_DECREMENT (mem_mode))
4598 {
4599 rtx addr = gen_rtx_POST_DEC (addr_mode, reg);
4600
4601 if (memory_address_addr_space_p (mem_mode, addr, as))
4602 data->costs[AINC_POST_DEC]
4603 = address_cost (addr, mem_mode, as, speed);
4604 }
4605 if (USE_LOAD_PRE_INCREMENT (mem_mode)
4606 || USE_STORE_PRE_INCREMENT (mem_mode))
4607 {
4608 rtx addr = gen_rtx_PRE_INC (addr_mode, reg);
4609
4610 if (memory_address_addr_space_p (mem_mode, addr, as))
4611 data->costs[AINC_PRE_INC]
4612 = address_cost (addr, mem_mode, as, speed);
4613 }
4614 if (USE_LOAD_POST_INCREMENT (mem_mode)
4615 || USE_STORE_POST_INCREMENT (mem_mode))
4616 {
4617 rtx addr = gen_rtx_POST_INC (addr_mode, reg);
4618
4619 if (memory_address_addr_space_p (mem_mode, addr, as))
4620 data->costs[AINC_POST_INC]
4621 = address_cost (addr, mem_mode, as, speed);
4622 }
4623 ainc_cost_data_list[idx] = data;
4624 }
4625
4626 poly_int64 msize = GET_MODE_SIZE (mem_mode);
4627 if (known_eq (ainc_offset, 0) && known_eq (msize, ainc_step))
4628 return comp_cost (data->costs[AINC_POST_INC], 0);
4629 if (known_eq (ainc_offset, 0) && known_eq (msize, -ainc_step))
4630 return comp_cost (data->costs[AINC_POST_DEC], 0);
4631 if (known_eq (ainc_offset, msize) && known_eq (msize, ainc_step))
4632 return comp_cost (data->costs[AINC_PRE_INC], 0);
4633 if (known_eq (ainc_offset, -msize) && known_eq (msize, -ainc_step))
4634 return comp_cost (data->costs[AINC_PRE_DEC], 0);
4635
4636 return infinite_cost;
4637 }
4638
4639 /* Return cost of computing USE's address expression by using CAND.
4640 AFF_INV and AFF_VAR represent invariant and variant parts of the
4641 address expression, respectively. If AFF_INV is simple, store
4642 the loop invariant variables which are depended by it in INV_VARS;
4643 if AFF_INV is complicated, handle it as a new invariant expression
4644 and record it in INV_EXPR. RATIO indicates multiple times between
4645 steps of USE and CAND. If CAN_AUTOINC is nonNULL, store boolean
4646 value to it indicating if this is an auto-increment address. */
4647
4648 static comp_cost
4649 get_address_cost (struct ivopts_data *data, struct iv_use *use,
4650 struct iv_cand *cand, aff_tree *aff_inv,
4651 aff_tree *aff_var, HOST_WIDE_INT ratio,
4652 bitmap *inv_vars, iv_inv_expr_ent **inv_expr,
4653 bool *can_autoinc, bool speed)
4654 {
4655 rtx addr;
4656 bool simple_inv = true;
4657 tree comp_inv = NULL_TREE, type = aff_var->type;
4658 comp_cost var_cost = no_cost, cost = no_cost;
4659 struct mem_address parts = {NULL_TREE, integer_one_node,
4660 NULL_TREE, NULL_TREE, NULL_TREE};
4661 machine_mode addr_mode = TYPE_MODE (type);
4662 machine_mode mem_mode = TYPE_MODE (use->mem_type);
4663 addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
4664 /* Only true if ratio != 1. */
4665 bool ok_with_ratio_p = false;
4666 bool ok_without_ratio_p = false;
4667 code_helper code = ERROR_MARK;
4668
4669 if (use->type == USE_PTR_ADDRESS)
4670 {
4671 gcall *call = as_a<gcall *> (use->stmt);
4672 gcc_assert (gimple_call_internal_p (call));
4673 code = gimple_call_internal_fn (call);
4674 }
4675
4676 if (!aff_combination_const_p (aff_inv))
4677 {
4678 parts.index = integer_one_node;
4679 /* Addressing mode "base + index". */
4680 ok_without_ratio_p = valid_mem_ref_p (mem_mode, as, &parts, code);
4681 if (ratio != 1)
4682 {
4683 parts.step = wide_int_to_tree (type, ratio);
4684 /* Addressing mode "base + index << scale". */
4685 ok_with_ratio_p = valid_mem_ref_p (mem_mode, as, &parts, code);
4686 if (!ok_with_ratio_p)
4687 parts.step = NULL_TREE;
4688 }
4689 if (ok_with_ratio_p || ok_without_ratio_p)
4690 {
4691 if (maybe_ne (aff_inv->offset, 0))
4692 {
4693 parts.offset = wide_int_to_tree (sizetype, aff_inv->offset);
4694 /* Addressing mode "base + index [<< scale] + offset". */
4695 if (!valid_mem_ref_p (mem_mode, as, &parts, code))
4696 parts.offset = NULL_TREE;
4697 else
4698 aff_inv->offset = 0;
4699 }
4700
4701 move_fixed_address_to_symbol (&parts, aff_inv);
4702 /* Base is fixed address and is moved to symbol part. */
4703 if (parts.symbol != NULL_TREE && aff_combination_zero_p (aff_inv))
4704 parts.base = NULL_TREE;
4705
4706 /* Addressing mode "symbol + base + index [<< scale] [+ offset]". */
4707 if (parts.symbol != NULL_TREE
4708 && !valid_mem_ref_p (mem_mode, as, &parts, code))
4709 {
4710 aff_combination_add_elt (aff_inv, parts.symbol, 1);
4711 parts.symbol = NULL_TREE;
4712 /* Reset SIMPLE_INV since symbol address needs to be computed
4713 outside of address expression in this case. */
4714 simple_inv = false;
4715 /* Symbol part is moved back to base part, it can't be NULL. */
4716 parts.base = integer_one_node;
4717 }
4718 }
4719 else
4720 parts.index = NULL_TREE;
4721 }
4722 else
4723 {
4724 poly_int64 ainc_step;
4725 if (can_autoinc
4726 && ratio == 1
4727 && ptrdiff_tree_p (cand->iv->step, &ainc_step))
4728 {
4729 poly_int64 ainc_offset = (aff_inv->offset).force_shwi ();
4730
4731 if (stmt_after_increment (data->current_loop, cand, use->stmt))
4732 ainc_offset += ainc_step;
4733 cost = get_address_cost_ainc (ainc_step, ainc_offset,
4734 addr_mode, mem_mode, as, speed);
4735 if (!cost.infinite_cost_p ())
4736 {
4737 *can_autoinc = true;
4738 return cost;
4739 }
4740 cost = no_cost;
4741 }
4742 if (!aff_combination_zero_p (aff_inv))
4743 {
4744 parts.offset = wide_int_to_tree (sizetype, aff_inv->offset);
4745 /* Addressing mode "base + offset". */
4746 if (!valid_mem_ref_p (mem_mode, as, &parts, code))
4747 parts.offset = NULL_TREE;
4748 else
4749 aff_inv->offset = 0;
4750 }
4751 }
4752
4753 if (simple_inv)
4754 simple_inv = (aff_inv == NULL
4755 || aff_combination_const_p (aff_inv)
4756 || aff_combination_singleton_var_p (aff_inv));
4757 if (!aff_combination_zero_p (aff_inv))
4758 comp_inv = aff_combination_to_tree (aff_inv);
4759 if (comp_inv != NULL_TREE)
4760 cost = force_var_cost (data, comp_inv, inv_vars);
4761 if (ratio != 1 && parts.step == NULL_TREE)
4762 var_cost += mult_by_coeff_cost (ratio, addr_mode, speed);
4763 if (comp_inv != NULL_TREE && parts.index == NULL_TREE)
4764 var_cost += add_cost (speed, addr_mode);
4765
4766 if (comp_inv && inv_expr && !simple_inv)
4767 {
4768 *inv_expr = get_loop_invariant_expr (data, comp_inv);
4769 /* Clear depends on. */
4770 if (*inv_expr != NULL && inv_vars && *inv_vars)
4771 bitmap_clear (*inv_vars);
4772
4773 /* Cost of small invariant expression adjusted against loop niters
4774 is usually zero, which makes it difficult to be differentiated
4775 from candidate based on loop invariant variables. Secondly, the
4776 generated invariant expression may not be hoisted out of loop by
4777 following pass. We penalize the cost by rounding up in order to
4778 neutralize such effects. */
4779 cost.cost = adjust_setup_cost (data, cost.cost, true);
4780 cost.scratch = cost.cost;
4781 }
4782
4783 cost += var_cost;
4784 addr = addr_for_mem_ref (&parts, as, false);
4785 gcc_assert (memory_address_addr_space_p (mem_mode, addr, as));
4786 cost += address_cost (addr, mem_mode, as, speed);
4787
4788 if (parts.symbol != NULL_TREE)
4789 cost.complexity += 1;
4790 /* Don't increase the complexity of adding a scaled index if it's
4791 the only kind of index that the target allows. */
4792 if (parts.step != NULL_TREE && ok_without_ratio_p)
4793 cost.complexity += 1;
4794 if (parts.base != NULL_TREE && parts.index != NULL_TREE)
4795 cost.complexity += 1;
4796 if (parts.offset != NULL_TREE && !integer_zerop (parts.offset))
4797 cost.complexity += 1;
4798
4799 return cost;
4800 }
4801
4802 /* Scale (multiply) the computed COST (except scratch part that should be
4803 hoisted out a loop) by header->frequency / AT->frequency, which makes
4804 expected cost more accurate. */
4805
4806 static comp_cost
4807 get_scaled_computation_cost_at (ivopts_data *data, gimple *at, comp_cost cost)
4808 {
4809 if (data->speed
4810 && data->current_loop->header->count.to_frequency (cfun) > 0)
4811 {
4812 basic_block bb = gimple_bb (at);
4813 gcc_assert (cost.scratch <= cost.cost);
4814 int scale_factor = (int)(intptr_t) bb->aux;
4815 if (scale_factor == 1)
4816 return cost;
4817
4818 int64_t scaled_cost
4819 = cost.scratch + (cost.cost - cost.scratch) * scale_factor;
4820
4821 if (dump_file && (dump_flags & TDF_DETAILS))
4822 fprintf (dump_file, "Scaling cost based on bb prob by %2.2f: "
4823 "%" PRId64 " (scratch: %" PRId64 ") -> %" PRId64 "\n",
4824 1.0f * scale_factor, cost.cost, cost.scratch, scaled_cost);
4825
4826 cost.cost = scaled_cost;
4827 }
4828
4829 return cost;
4830 }
4831
4832 /* Determines the cost of the computation by that USE is expressed
4833 from induction variable CAND. If ADDRESS_P is true, we just need
4834 to create an address from it, otherwise we want to get it into
4835 register. A set of invariants we depend on is stored in INV_VARS.
4836 If CAN_AUTOINC is nonnull, use it to record whether autoinc
4837 addressing is likely. If INV_EXPR is nonnull, record invariant
4838 expr entry in it. */
4839
4840 static comp_cost
4841 get_computation_cost (struct ivopts_data *data, struct iv_use *use,
4842 struct iv_cand *cand, bool address_p, bitmap *inv_vars,
4843 bool *can_autoinc, iv_inv_expr_ent **inv_expr)
4844 {
4845 gimple *at = use->stmt;
4846 tree ubase = use->iv->base, cbase = cand->iv->base;
4847 tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
4848 tree comp_inv = NULL_TREE;
4849 HOST_WIDE_INT ratio, aratio;
4850 comp_cost cost;
4851 widest_int rat;
4852 aff_tree aff_inv, aff_var;
4853 bool speed = optimize_bb_for_speed_p (gimple_bb (at));
4854
4855 if (inv_vars)
4856 *inv_vars = NULL;
4857 if (can_autoinc)
4858 *can_autoinc = false;
4859 if (inv_expr)
4860 *inv_expr = NULL;
4861
4862 /* Check if we have enough precision to express the values of use. */
4863 if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
4864 return infinite_cost;
4865
4866 if (address_p
4867 || (use->iv->base_object
4868 && cand->iv->base_object
4869 && POINTER_TYPE_P (TREE_TYPE (use->iv->base_object))
4870 && POINTER_TYPE_P (TREE_TYPE (cand->iv->base_object))))
4871 {
4872 /* Do not try to express address of an object with computation based
4873 on address of a different object. This may cause problems in rtl
4874 level alias analysis (that does not expect this to be happening,
4875 as this is illegal in C), and would be unlikely to be useful
4876 anyway. */
4877 if (use->iv->base_object
4878 && cand->iv->base_object
4879 && !operand_equal_p (use->iv->base_object, cand->iv->base_object, 0))
4880 return infinite_cost;
4881 }
4882
4883 if (!get_computation_aff_1 (data->current_loop, at, use,
4884 cand, &aff_inv, &aff_var, &rat)
4885 || !wi::fits_shwi_p (rat))
4886 return infinite_cost;
4887
4888 ratio = rat.to_shwi ();
4889 if (address_p)
4890 {
4891 cost = get_address_cost (data, use, cand, &aff_inv, &aff_var, ratio,
4892 inv_vars, inv_expr, can_autoinc, speed);
4893 cost = get_scaled_computation_cost_at (data, at, cost);
4894 /* For doloop IV cand, add on the extra cost. */
4895 cost += cand->doloop_p ? targetm.doloop_cost_for_address : 0;
4896 return cost;
4897 }
4898
4899 bool simple_inv = (aff_combination_const_p (&aff_inv)
4900 || aff_combination_singleton_var_p (&aff_inv));
4901 tree signed_type = signed_type_for (aff_combination_type (&aff_inv));
4902 aff_combination_convert (&aff_inv, signed_type);
4903 if (!aff_combination_zero_p (&aff_inv))
4904 comp_inv = aff_combination_to_tree (&aff_inv);
4905
4906 cost = force_var_cost (data, comp_inv, inv_vars);
4907 if (comp_inv && inv_expr && !simple_inv)
4908 {
4909 *inv_expr = get_loop_invariant_expr (data, comp_inv);
4910 /* Clear depends on. */
4911 if (*inv_expr != NULL && inv_vars && *inv_vars)
4912 bitmap_clear (*inv_vars);
4913
4914 cost.cost = adjust_setup_cost (data, cost.cost);
4915 /* Record setup cost in scratch field. */
4916 cost.scratch = cost.cost;
4917 }
4918 /* Cost of constant integer can be covered when adding invariant part to
4919 variant part. */
4920 else if (comp_inv && CONSTANT_CLASS_P (comp_inv))
4921 cost = no_cost;
4922
4923 /* Need type narrowing to represent use with cand. */
4924 if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
4925 {
4926 machine_mode outer_mode = TYPE_MODE (utype);
4927 machine_mode inner_mode = TYPE_MODE (ctype);
4928 cost += comp_cost (convert_cost (outer_mode, inner_mode, speed), 0);
4929 }
4930
4931 /* Turn a + i * (-c) into a - i * c. */
4932 if (ratio < 0 && comp_inv && !integer_zerop (comp_inv))
4933 aratio = -ratio;
4934 else
4935 aratio = ratio;
4936
4937 if (ratio != 1)
4938 cost += mult_by_coeff_cost (aratio, TYPE_MODE (utype), speed);
4939
4940 /* TODO: We may also need to check if we can compute a + i * 4 in one
4941 instruction. */
4942 /* Need to add up the invariant and variant parts. */
4943 if (comp_inv && !integer_zerop (comp_inv))
4944 cost += add_cost (speed, TYPE_MODE (utype));
4945
4946 cost = get_scaled_computation_cost_at (data, at, cost);
4947
4948 /* For doloop IV cand, add on the extra cost. */
4949 if (cand->doloop_p && use->type == USE_NONLINEAR_EXPR)
4950 cost += targetm.doloop_cost_for_generic;
4951
4952 return cost;
4953 }
4954
4955 /* Determines cost of computing the use in GROUP with CAND in a generic
4956 expression. */
4957
4958 static bool
4959 determine_group_iv_cost_generic (struct ivopts_data *data,
4960 struct iv_group *group, struct iv_cand *cand)
4961 {
4962 comp_cost cost;
4963 iv_inv_expr_ent *inv_expr = NULL;
4964 bitmap inv_vars = NULL, inv_exprs = NULL;
4965 struct iv_use *use = group->vuses[0];
4966
4967 /* The simple case first -- if we need to express value of the preserved
4968 original biv, the cost is 0. This also prevents us from counting the
4969 cost of increment twice -- once at this use and once in the cost of
4970 the candidate. */
4971 if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
4972 cost = no_cost;
4973 /* If the IV candidate involves undefined SSA values and is not the
4974 same IV as on the USE avoid using that candidate here. */
4975 else if (cand->involves_undefs
4976 && (!use->iv || !operand_equal_p (cand->iv->base, use->iv->base, 0)))
4977 return false;
4978 else
4979 cost = get_computation_cost (data, use, cand, false,
4980 &inv_vars, NULL, &inv_expr);
4981
4982 if (inv_expr)
4983 {
4984 inv_exprs = BITMAP_ALLOC (NULL);
4985 bitmap_set_bit (inv_exprs, inv_expr->id);
4986 }
4987 set_group_iv_cost (data, group, cand, cost, inv_vars,
4988 NULL_TREE, ERROR_MARK, inv_exprs);
4989 return !cost.infinite_cost_p ();
4990 }
4991
4992 /* Determines cost of computing uses in GROUP with CAND in addresses. */
4993
4994 static bool
4995 determine_group_iv_cost_address (struct ivopts_data *data,
4996 struct iv_group *group, struct iv_cand *cand)
4997 {
4998 unsigned i;
4999 bitmap inv_vars = NULL, inv_exprs = NULL;
5000 bool can_autoinc;
5001 iv_inv_expr_ent *inv_expr = NULL;
5002 struct iv_use *use = group->vuses[0];
5003 comp_cost sum_cost = no_cost, cost;
5004
5005 cost = get_computation_cost (data, use, cand, true,
5006 &inv_vars, &can_autoinc, &inv_expr);
5007
5008 if (inv_expr)
5009 {
5010 inv_exprs = BITMAP_ALLOC (NULL);
5011 bitmap_set_bit (inv_exprs, inv_expr->id);
5012 }
5013 sum_cost = cost;
5014 if (!sum_cost.infinite_cost_p () && cand->ainc_use == use)
5015 {
5016 if (can_autoinc)
5017 sum_cost -= cand->cost_step;
5018 /* If we generated the candidate solely for exploiting autoincrement
5019 opportunities, and it turns out it can't be used, set the cost to
5020 infinity to make sure we ignore it. */
5021 else if (cand->pos == IP_AFTER_USE || cand->pos == IP_BEFORE_USE)
5022 sum_cost = infinite_cost;
5023 }
5024
5025 /* Uses in a group can share setup code, so only add setup cost once. */
5026 cost -= cost.scratch;
5027 /* Compute and add costs for rest uses of this group. */
5028 for (i = 1; i < group->vuses.length () && !sum_cost.infinite_cost_p (); i++)
5029 {
5030 struct iv_use *next = group->vuses[i];
5031
5032 /* TODO: We could skip computing cost for sub iv_use when it has the
5033 same cost as the first iv_use, but the cost really depends on the
5034 offset and where the iv_use is. */
5035 cost = get_computation_cost (data, next, cand, true,
5036 NULL, &can_autoinc, &inv_expr);
5037 if (inv_expr)
5038 {
5039 if (!inv_exprs)
5040 inv_exprs = BITMAP_ALLOC (NULL);
5041
5042 bitmap_set_bit (inv_exprs, inv_expr->id);
5043 }
5044 sum_cost += cost;
5045 }
5046 set_group_iv_cost (data, group, cand, sum_cost, inv_vars,
5047 NULL_TREE, ERROR_MARK, inv_exprs);
5048
5049 return !sum_cost.infinite_cost_p ();
5050 }
5051
5052 /* Computes value of candidate CAND at position AT in iteration DESC->NITER,
5053 and stores it to VAL. */
5054
5055 static void
5056 cand_value_at (class loop *loop, struct iv_cand *cand, gimple *at,
5057 class tree_niter_desc *desc, aff_tree *val)
5058 {
5059 aff_tree step, delta, nit;
5060 struct iv *iv = cand->iv;
5061 tree type = TREE_TYPE (iv->base);
5062 tree niter = desc->niter;
5063 bool after_adjust = stmt_after_increment (loop, cand, at);
5064 tree steptype;
5065
5066 if (POINTER_TYPE_P (type))
5067 steptype = sizetype;
5068 else
5069 steptype = unsigned_type_for (type);
5070
5071 /* If AFTER_ADJUST is required, the code below generates the equivalent
5072 of BASE + NITER * STEP + STEP, when ideally we'd prefer the expression
5073 BASE + (NITER + 1) * STEP, especially when NITER is often of the form
5074 SSA_NAME - 1. Unfortunately, guaranteeing that adding 1 to NITER
5075 doesn't overflow is tricky, so we peek inside the TREE_NITER_DESC
5076 class for common idioms that we know are safe. */
5077 if (after_adjust
5078 && desc->control.no_overflow
5079 && integer_onep (desc->control.step)
5080 && (desc->cmp == LT_EXPR
5081 || desc->cmp == NE_EXPR)
5082 && TREE_CODE (desc->bound) == SSA_NAME)
5083 {
5084 if (integer_onep (desc->control.base))
5085 {
5086 niter = desc->bound;
5087 after_adjust = false;
5088 }
5089 else if (TREE_CODE (niter) == MINUS_EXPR
5090 && integer_onep (TREE_OPERAND (niter, 1)))
5091 {
5092 niter = TREE_OPERAND (niter, 0);
5093 after_adjust = false;
5094 }
5095 }
5096
5097 tree_to_aff_combination (iv->step, TREE_TYPE (iv->step), &step);
5098 aff_combination_convert (&step, steptype);
5099 tree_to_aff_combination (niter, TREE_TYPE (niter), &nit);
5100 aff_combination_convert (&nit, steptype);
5101 aff_combination_mult (&nit, &step, &delta);
5102 if (after_adjust)
5103 aff_combination_add (&delta, &step);
5104
5105 tree_to_aff_combination (iv->base, type, val);
5106 if (!POINTER_TYPE_P (type))
5107 aff_combination_convert (val, steptype);
5108 aff_combination_add (val, &delta);
5109 }
5110
5111 /* Returns period of induction variable iv. */
5112
5113 static tree
5114 iv_period (struct iv *iv)
5115 {
5116 tree step = iv->step, period, type;
5117 tree pow2div;
5118
5119 gcc_assert (step && TREE_CODE (step) == INTEGER_CST);
5120
5121 type = unsigned_type_for (TREE_TYPE (step));
5122 /* Period of the iv is lcm (step, type_range)/step -1,
5123 i.e., N*type_range/step - 1. Since type range is power
5124 of two, N == (step >> num_of_ending_zeros_binary (step),
5125 so the final result is
5126
5127 (type_range >> num_of_ending_zeros_binary (step)) - 1
5128
5129 */
5130 pow2div = num_ending_zeros (step);
5131
5132 period = build_low_bits_mask (type,
5133 (TYPE_PRECISION (type)
5134 - tree_to_uhwi (pow2div)));
5135
5136 return period;
5137 }
5138
5139 /* Returns the comparison operator used when eliminating the iv USE. */
5140
5141 static enum tree_code
5142 iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
5143 {
5144 class loop *loop = data->current_loop;
5145 basic_block ex_bb;
5146 edge exit;
5147
5148 ex_bb = gimple_bb (use->stmt);
5149 exit = EDGE_SUCC (ex_bb, 0);
5150 if (flow_bb_inside_loop_p (loop, exit->dest))
5151 exit = EDGE_SUCC (ex_bb, 1);
5152
5153 return (exit->flags & EDGE_TRUE_VALUE ? EQ_EXPR : NE_EXPR);
5154 }
5155
5156 /* Returns true if we can prove that BASE - OFFSET does not overflow. For now,
5157 we only detect the situation that BASE = SOMETHING + OFFSET, where the
5158 calculation is performed in non-wrapping type.
5159
5160 TODO: More generally, we could test for the situation that
5161 BASE = SOMETHING + OFFSET' and OFFSET is between OFFSET' and zero.
5162 This would require knowing the sign of OFFSET. */
5163
5164 static bool
5165 difference_cannot_overflow_p (struct ivopts_data *data, tree base, tree offset)
5166 {
5167 enum tree_code code;
5168 tree e1, e2;
5169 aff_tree aff_e1, aff_e2, aff_offset;
5170
5171 if (!nowrap_type_p (TREE_TYPE (base)))
5172 return false;
5173
5174 base = expand_simple_operations (base);
5175
5176 if (TREE_CODE (base) == SSA_NAME)
5177 {
5178 gimple *stmt = SSA_NAME_DEF_STMT (base);
5179
5180 if (gimple_code (stmt) != GIMPLE_ASSIGN)
5181 return false;
5182
5183 code = gimple_assign_rhs_code (stmt);
5184 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
5185 return false;
5186
5187 e1 = gimple_assign_rhs1 (stmt);
5188 e2 = gimple_assign_rhs2 (stmt);
5189 }
5190 else
5191 {
5192 code = TREE_CODE (base);
5193 if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
5194 return false;
5195 e1 = TREE_OPERAND (base, 0);
5196 e2 = TREE_OPERAND (base, 1);
5197 }
5198
5199 /* Use affine expansion as deeper inspection to prove the equality. */
5200 tree_to_aff_combination_expand (e2, TREE_TYPE (e2),
5201 &aff_e2, &data->name_expansion_cache);
5202 tree_to_aff_combination_expand (offset, TREE_TYPE (offset),
5203 &aff_offset, &data->name_expansion_cache);
5204 aff_combination_scale (&aff_offset, -1);
5205 switch (code)
5206 {
5207 case PLUS_EXPR:
5208 aff_combination_add (&aff_e2, &aff_offset);
5209 if (aff_combination_zero_p (&aff_e2))
5210 return true;
5211
5212 tree_to_aff_combination_expand (e1, TREE_TYPE (e1),
5213 &aff_e1, &data->name_expansion_cache);
5214 aff_combination_add (&aff_e1, &aff_offset);
5215 return aff_combination_zero_p (&aff_e1);
5216
5217 case POINTER_PLUS_EXPR:
5218 aff_combination_add (&aff_e2, &aff_offset);
5219 return aff_combination_zero_p (&aff_e2);
5220
5221 default:
5222 return false;
5223 }
5224 }
5225
5226 /* Tries to replace loop exit by one formulated in terms of a LT_EXPR
5227 comparison with CAND. NITER describes the number of iterations of
5228 the loops. If successful, the comparison in COMP_P is altered accordingly.
5229
5230 We aim to handle the following situation:
5231
5232 sometype *base, *p;
5233 int a, b, i;
5234
5235 i = a;
5236 p = p_0 = base + a;
5237
5238 do
5239 {
5240 bla (*p);
5241 p++;
5242 i++;
5243 }
5244 while (i < b);
5245
5246 Here, the number of iterations of the loop is (a + 1 > b) ? 0 : b - a - 1.
5247 We aim to optimize this to
5248
5249 p = p_0 = base + a;
5250 do
5251 {
5252 bla (*p);
5253 p++;
5254 }
5255 while (p < p_0 - a + b);
5256
5257 This preserves the correctness, since the pointer arithmetics does not
5258 overflow. More precisely:
5259
5260 1) if a + 1 <= b, then p_0 - a + b is the final value of p, hence there is no
5261 overflow in computing it or the values of p.
5262 2) if a + 1 > b, then we need to verify that the expression p_0 - a does not
5263 overflow. To prove this, we use the fact that p_0 = base + a. */
5264
5265 static bool
5266 iv_elimination_compare_lt (struct ivopts_data *data,
5267 struct iv_cand *cand, enum tree_code *comp_p,
5268 class tree_niter_desc *niter)
5269 {
5270 tree cand_type, a, b, mbz, nit_type = TREE_TYPE (niter->niter), offset;
5271 class aff_tree nit, tmpa, tmpb;
5272 enum tree_code comp;
5273 HOST_WIDE_INT step;
5274
5275 /* We need to know that the candidate induction variable does not overflow.
5276 While more complex analysis may be used to prove this, for now just
5277 check that the variable appears in the original program and that it
5278 is computed in a type that guarantees no overflows. */
5279 cand_type = TREE_TYPE (cand->iv->base);
5280 if (cand->pos != IP_ORIGINAL || !nowrap_type_p (cand_type))
5281 return false;
5282
5283 /* Make sure that the loop iterates till the loop bound is hit, as otherwise
5284 the calculation of the BOUND could overflow, making the comparison
5285 invalid. */
5286 if (!data->loop_single_exit_p)
5287 return false;
5288
5289 /* We need to be able to decide whether candidate is increasing or decreasing
5290 in order to choose the right comparison operator. */
5291 if (!cst_and_fits_in_hwi (cand->iv->step))
5292 return false;
5293 step = int_cst_value (cand->iv->step);
5294
5295 /* Check that the number of iterations matches the expected pattern:
5296 a + 1 > b ? 0 : b - a - 1. */
5297 mbz = niter->may_be_zero;
5298 if (TREE_CODE (mbz) == GT_EXPR)
5299 {
5300 /* Handle a + 1 > b. */
5301 tree op0 = TREE_OPERAND (mbz, 0);
5302 if (TREE_CODE (op0) == PLUS_EXPR && integer_onep (TREE_OPERAND (op0, 1)))
5303 {
5304 a = TREE_OPERAND (op0, 0);
5305 b = TREE_OPERAND (mbz, 1);
5306 }
5307 else
5308 return false;
5309 }
5310 else if (TREE_CODE (mbz) == LT_EXPR)
5311 {
5312 tree op1 = TREE_OPERAND (mbz, 1);
5313
5314 /* Handle b < a + 1. */
5315 if (TREE_CODE (op1) == PLUS_EXPR && integer_onep (TREE_OPERAND (op1, 1)))
5316 {
5317 a = TREE_OPERAND (op1, 0);
5318 b = TREE_OPERAND (mbz, 0);
5319 }
5320 else
5321 return false;
5322 }
5323 else
5324 return false;
5325
5326 /* Expected number of iterations is B - A - 1. Check that it matches
5327 the actual number, i.e., that B - A - NITER = 1. */
5328 tree_to_aff_combination (niter->niter, nit_type, &nit);
5329 tree_to_aff_combination (fold_convert (nit_type, a), nit_type, &tmpa);
5330 tree_to_aff_combination (fold_convert (nit_type, b), nit_type, &tmpb);
5331 aff_combination_scale (&nit, -1);
5332 aff_combination_scale (&tmpa, -1);
5333 aff_combination_add (&tmpb, &tmpa);
5334 aff_combination_add (&tmpb, &nit);
5335 if (tmpb.n != 0 || maybe_ne (tmpb.offset, 1))
5336 return false;
5337
5338 /* Finally, check that CAND->IV->BASE - CAND->IV->STEP * A does not
5339 overflow. */
5340 offset = fold_build2 (MULT_EXPR, TREE_TYPE (cand->iv->step),
5341 cand->iv->step,
5342 fold_convert (TREE_TYPE (cand->iv->step), a));
5343 if (!difference_cannot_overflow_p (data, cand->iv->base, offset))
5344 return false;
5345
5346 /* Determine the new comparison operator. */
5347 comp = step < 0 ? GT_EXPR : LT_EXPR;
5348 if (*comp_p == NE_EXPR)
5349 *comp_p = comp;
5350 else if (*comp_p == EQ_EXPR)
5351 *comp_p = invert_tree_comparison (comp, false);
5352 else
5353 gcc_unreachable ();
5354
5355 return true;
5356 }
5357
5358 /* Check whether it is possible to express the condition in USE by comparison
5359 of candidate CAND. If so, store the value compared with to BOUND, and the
5360 comparison operator to COMP. */
5361
5362 static bool
5363 may_eliminate_iv (struct ivopts_data *data,
5364 struct iv_use *use, struct iv_cand *cand, tree *bound,
5365 enum tree_code *comp)
5366 {
5367 basic_block ex_bb;
5368 edge exit;
5369 tree period;
5370 class loop *loop = data->current_loop;
5371 aff_tree bnd;
5372 class tree_niter_desc *desc = NULL;
5373
5374 if (TREE_CODE (cand->iv->step) != INTEGER_CST)
5375 return false;
5376
5377 /* For now works only for exits that dominate the loop latch.
5378 TODO: extend to other conditions inside loop body. */
5379 ex_bb = gimple_bb (use->stmt);
5380 if (use->stmt != last_nondebug_stmt (ex_bb)
5381 || gimple_code (use->stmt) != GIMPLE_COND
5382 || !dominated_by_p (CDI_DOMINATORS, loop->latch, ex_bb))
5383 return false;
5384
5385 exit = EDGE_SUCC (ex_bb, 0);
5386 if (flow_bb_inside_loop_p (loop, exit->dest))
5387 exit = EDGE_SUCC (ex_bb, 1);
5388 if (flow_bb_inside_loop_p (loop, exit->dest))
5389 return false;
5390
5391 desc = niter_for_exit (data, exit);
5392 if (!desc)
5393 return false;
5394
5395 /* Determine whether we can use the variable to test the exit condition.
5396 This is the case iff the period of the induction variable is greater
5397 than the number of iterations for which the exit condition is true. */
5398 period = iv_period (cand->iv);
5399
5400 /* If the number of iterations is constant, compare against it directly. */
5401 if (TREE_CODE (desc->niter) == INTEGER_CST)
5402 {
5403 /* See cand_value_at. */
5404 if (stmt_after_increment (loop, cand, use->stmt))
5405 {
5406 if (!tree_int_cst_lt (desc->niter, period))
5407 return false;
5408 }
5409 else
5410 {
5411 if (tree_int_cst_lt (period, desc->niter))
5412 return false;
5413 }
5414 }
5415
5416 /* If not, and if this is the only possible exit of the loop, see whether
5417 we can get a conservative estimate on the number of iterations of the
5418 entire loop and compare against that instead. */
5419 else
5420 {
5421 widest_int period_value, max_niter;
5422
5423 max_niter = desc->max;
5424 if (stmt_after_increment (loop, cand, use->stmt))
5425 max_niter += 1;
5426 period_value = wi::to_widest (period);
5427 if (wi::gtu_p (max_niter, period_value))
5428 {
5429 /* See if we can take advantage of inferred loop bound
5430 information. */
5431 if (data->loop_single_exit_p)
5432 {
5433 if (!max_loop_iterations (loop, &max_niter))
5434 return false;
5435 /* The loop bound is already adjusted by adding 1. */
5436 if (wi::gtu_p (max_niter, period_value))
5437 return false;
5438 }
5439 else
5440 return false;
5441 }
5442 }
5443
5444 /* For doloop IV cand, the bound would be zero. It's safe whether
5445 may_be_zero set or not. */
5446 if (cand->doloop_p)
5447 {
5448 *bound = build_int_cst (TREE_TYPE (cand->iv->base), 0);
5449 *comp = iv_elimination_compare (data, use);
5450 return true;
5451 }
5452
5453 cand_value_at (loop, cand, use->stmt, desc, &bnd);
5454
5455 *bound = fold_convert (TREE_TYPE (cand->iv->base),
5456 aff_combination_to_tree (&bnd));
5457 *comp = iv_elimination_compare (data, use);
5458
5459 /* It is unlikely that computing the number of iterations using division
5460 would be more profitable than keeping the original induction variable. */
5461 bool cond_overflow_p;
5462 if (expression_expensive_p (*bound, &cond_overflow_p))
5463 return false;
5464
5465 /* Sometimes, it is possible to handle the situation that the number of
5466 iterations may be zero unless additional assumptions by using <
5467 instead of != in the exit condition.
5468
5469 TODO: we could also calculate the value MAY_BE_ZERO ? 0 : NITER and
5470 base the exit condition on it. However, that is often too
5471 expensive. */
5472 if (!integer_zerop (desc->may_be_zero))
5473 return iv_elimination_compare_lt (data, cand, comp, desc);
5474
5475 return true;
5476 }
5477
5478 /* Calculates the cost of BOUND, if it is a PARM_DECL. A PARM_DECL must
5479 be copied, if it is used in the loop body and DATA->body_includes_call. */
5480
5481 static int
5482 parm_decl_cost (struct ivopts_data *data, tree bound)
5483 {
5484 tree sbound = bound;
5485 STRIP_NOPS (sbound);
5486
5487 if (TREE_CODE (sbound) == SSA_NAME
5488 && SSA_NAME_IS_DEFAULT_DEF (sbound)
5489 && TREE_CODE (SSA_NAME_VAR (sbound)) == PARM_DECL
5490 && data->body_includes_call)
5491 return COSTS_N_INSNS (1);
5492
5493 return 0;
5494 }
5495
5496 /* Determines cost of computing the use in GROUP with CAND in a condition. */
5497
5498 static bool
5499 determine_group_iv_cost_cond (struct ivopts_data *data,
5500 struct iv_group *group, struct iv_cand *cand)
5501 {
5502 tree bound = NULL_TREE;
5503 struct iv *cmp_iv;
5504 bitmap inv_exprs = NULL;
5505 bitmap inv_vars_elim = NULL, inv_vars_express = NULL, inv_vars;
5506 comp_cost elim_cost = infinite_cost, express_cost, cost, bound_cost;
5507 enum comp_iv_rewrite rewrite_type;
5508 iv_inv_expr_ent *inv_expr_elim = NULL, *inv_expr_express = NULL, *inv_expr;
5509 tree *control_var, *bound_cst;
5510 enum tree_code comp = ERROR_MARK;
5511 struct iv_use *use = group->vuses[0];
5512
5513 /* Extract condition operands. */
5514 rewrite_type = extract_cond_operands (data, use->stmt, &control_var,
5515 &bound_cst, NULL, &cmp_iv);
5516 gcc_assert (rewrite_type != COMP_IV_NA);
5517
5518 /* Try iv elimination. */
5519 if (rewrite_type == COMP_IV_ELIM
5520 && may_eliminate_iv (data, use, cand, &bound, &comp))
5521 {
5522 elim_cost = force_var_cost (data, bound, &inv_vars_elim);
5523 if (elim_cost.cost == 0)
5524 elim_cost.cost = parm_decl_cost (data, bound);
5525 else if (TREE_CODE (bound) == INTEGER_CST)
5526 elim_cost.cost = 0;
5527 /* If we replace a loop condition 'i < n' with 'p < base + n',
5528 inv_vars_elim will have 'base' and 'n' set, which implies that both
5529 'base' and 'n' will be live during the loop. More likely,
5530 'base + n' will be loop invariant, resulting in only one live value
5531 during the loop. So in that case we clear inv_vars_elim and set
5532 inv_expr_elim instead. */
5533 if (inv_vars_elim && bitmap_count_bits (inv_vars_elim) > 1)
5534 {
5535 inv_expr_elim = get_loop_invariant_expr (data, bound);
5536 bitmap_clear (inv_vars_elim);
5537 }
5538 /* The bound is a loop invariant, so it will be only computed
5539 once. */
5540 elim_cost.cost = adjust_setup_cost (data, elim_cost.cost);
5541 }
5542
5543 /* When the condition is a comparison of the candidate IV against
5544 zero, prefer this IV.
5545
5546 TODO: The constant that we're subtracting from the cost should
5547 be target-dependent. This information should be added to the
5548 target costs for each backend. */
5549 if (!elim_cost.infinite_cost_p () /* Do not try to decrease infinite! */
5550 && integer_zerop (*bound_cst)
5551 && (operand_equal_p (*control_var, cand->var_after, 0)
5552 || operand_equal_p (*control_var, cand->var_before, 0)))
5553 elim_cost -= 1;
5554
5555 express_cost = get_computation_cost (data, use, cand, false,
5556 &inv_vars_express, NULL,
5557 &inv_expr_express);
5558 if (cmp_iv != NULL)
5559 find_inv_vars (data, &cmp_iv->base, &inv_vars_express);
5560
5561 /* Count the cost of the original bound as well. */
5562 bound_cost = force_var_cost (data, *bound_cst, NULL);
5563 if (bound_cost.cost == 0)
5564 bound_cost.cost = parm_decl_cost (data, *bound_cst);
5565 else if (TREE_CODE (*bound_cst) == INTEGER_CST)
5566 bound_cost.cost = 0;
5567 express_cost += bound_cost;
5568
5569 /* Choose the better approach, preferring the eliminated IV. */
5570 if (elim_cost <= express_cost)
5571 {
5572 cost = elim_cost;
5573 inv_vars = inv_vars_elim;
5574 inv_vars_elim = NULL;
5575 inv_expr = inv_expr_elim;
5576 /* For doloop candidate/use pair, adjust to zero cost. */
5577 if (group->doloop_p && cand->doloop_p && elim_cost.cost > no_cost.cost)
5578 cost = no_cost;
5579 }
5580 else
5581 {
5582 cost = express_cost;
5583 inv_vars = inv_vars_express;
5584 inv_vars_express = NULL;
5585 bound = NULL_TREE;
5586 comp = ERROR_MARK;
5587 inv_expr = inv_expr_express;
5588 }
5589
5590 if (inv_expr)
5591 {
5592 inv_exprs = BITMAP_ALLOC (NULL);
5593 bitmap_set_bit (inv_exprs, inv_expr->id);
5594 }
5595 set_group_iv_cost (data, group, cand, cost,
5596 inv_vars, bound, comp, inv_exprs);
5597
5598 if (inv_vars_elim)
5599 BITMAP_FREE (inv_vars_elim);
5600 if (inv_vars_express)
5601 BITMAP_FREE (inv_vars_express);
5602
5603 return !cost.infinite_cost_p ();
5604 }
5605
5606 /* Determines cost of computing uses in GROUP with CAND. Returns false
5607 if USE cannot be represented with CAND. */
5608
5609 static bool
5610 determine_group_iv_cost (struct ivopts_data *data,
5611 struct iv_group *group, struct iv_cand *cand)
5612 {
5613 switch (group->type)
5614 {
5615 case USE_NONLINEAR_EXPR:
5616 return determine_group_iv_cost_generic (data, group, cand);
5617
5618 case USE_REF_ADDRESS:
5619 case USE_PTR_ADDRESS:
5620 return determine_group_iv_cost_address (data, group, cand);
5621
5622 case USE_COMPARE:
5623 return determine_group_iv_cost_cond (data, group, cand);
5624
5625 default:
5626 gcc_unreachable ();
5627 }
5628 }
5629
5630 /* Return true if get_computation_cost indicates that autoincrement is
5631 a possibility for the pair of USE and CAND, false otherwise. */
5632
5633 static bool
5634 autoinc_possible_for_pair (struct ivopts_data *data, struct iv_use *use,
5635 struct iv_cand *cand)
5636 {
5637 if (!address_p (use->type))
5638 return false;
5639
5640 bool can_autoinc = false;
5641 get_computation_cost (data, use, cand, true, NULL, &can_autoinc, NULL);
5642 return can_autoinc;
5643 }
5644
5645 /* Examine IP_ORIGINAL candidates to see if they are incremented next to a
5646 use that allows autoincrement, and set their AINC_USE if possible. */
5647
5648 static void
5649 set_autoinc_for_original_candidates (struct ivopts_data *data)
5650 {
5651 unsigned i, j;
5652
5653 for (i = 0; i < data->vcands.length (); i++)
5654 {
5655 struct iv_cand *cand = data->vcands[i];
5656 struct iv_use *closest_before = NULL;
5657 struct iv_use *closest_after = NULL;
5658 if (cand->pos != IP_ORIGINAL)
5659 continue;
5660
5661 for (j = 0; j < data->vgroups.length (); j++)
5662 {
5663 struct iv_group *group = data->vgroups[j];
5664 struct iv_use *use = group->vuses[0];
5665 unsigned uid = gimple_uid (use->stmt);
5666
5667 if (gimple_bb (use->stmt) != gimple_bb (cand->incremented_at))
5668 continue;
5669
5670 if (uid < gimple_uid (cand->incremented_at)
5671 && (closest_before == NULL
5672 || uid > gimple_uid (closest_before->stmt)))
5673 closest_before = use;
5674
5675 if (uid > gimple_uid (cand->incremented_at)
5676 && (closest_after == NULL
5677 || uid < gimple_uid (closest_after->stmt)))
5678 closest_after = use;
5679 }
5680
5681 if (closest_before != NULL
5682 && autoinc_possible_for_pair (data, closest_before, cand))
5683 cand->ainc_use = closest_before;
5684 else if (closest_after != NULL
5685 && autoinc_possible_for_pair (data, closest_after, cand))
5686 cand->ainc_use = closest_after;
5687 }
5688 }
5689
5690 /* Relate compare use with all candidates. */
5691
5692 static void
5693 relate_compare_use_with_all_cands (struct ivopts_data *data)
5694 {
5695 unsigned i, count = data->vcands.length ();
5696 for (i = 0; i < data->vgroups.length (); i++)
5697 {
5698 struct iv_group *group = data->vgroups[i];
5699
5700 if (group->type == USE_COMPARE)
5701 bitmap_set_range (group->related_cands, 0, count);
5702 }
5703 }
5704
5705 /* If PREFERRED_MODE is suitable and profitable, use the preferred
5706 PREFERRED_MODE to compute doloop iv base from niter: base = niter + 1. */
5707
5708 static tree
5709 compute_doloop_base_on_mode (machine_mode preferred_mode, tree niter,
5710 const widest_int &iterations_max)
5711 {
5712 tree ntype = TREE_TYPE (niter);
5713 tree pref_type = lang_hooks.types.type_for_mode (preferred_mode, 1);
5714 if (!pref_type)
5715 return fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
5716 build_int_cst (ntype, 1));
5717
5718 gcc_assert (TREE_CODE (pref_type) == INTEGER_TYPE);
5719
5720 int prec = TYPE_PRECISION (ntype);
5721 int pref_prec = TYPE_PRECISION (pref_type);
5722
5723 tree base;
5724
5725 /* Check if the PREFERRED_MODED is able to present niter. */
5726 if (pref_prec > prec
5727 || wi::ltu_p (iterations_max,
5728 widest_int::from (wi::max_value (pref_prec, UNSIGNED),
5729 UNSIGNED)))
5730 {
5731 /* No wrap, it is safe to use preferred type after niter + 1. */
5732 if (wi::ltu_p (iterations_max,
5733 widest_int::from (wi::max_value (prec, UNSIGNED),
5734 UNSIGNED)))
5735 {
5736 /* This could help to optimize "-1 +1" pair when niter looks
5737 like "n-1": n is in original mode. "base = (n - 1) + 1"
5738 in PREFERRED_MODED: it could be base = (PREFERRED_TYPE)n. */
5739 base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
5740 build_int_cst (ntype, 1));
5741 base = fold_convert (pref_type, base);
5742 }
5743
5744 /* To avoid wrap, convert niter to preferred type before plus 1. */
5745 else
5746 {
5747 niter = fold_convert (pref_type, niter);
5748 base = fold_build2 (PLUS_EXPR, pref_type, unshare_expr (niter),
5749 build_int_cst (pref_type, 1));
5750 }
5751 }
5752 else
5753 base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
5754 build_int_cst (ntype, 1));
5755 return base;
5756 }
5757
5758 /* Add one doloop dedicated IV candidate:
5759 - Base is (may_be_zero ? 1 : (niter + 1)).
5760 - Step is -1. */
5761
5762 static void
5763 add_iv_candidate_for_doloop (struct ivopts_data *data)
5764 {
5765 tree_niter_desc *niter_desc = niter_for_single_dom_exit (data);
5766 gcc_assert (niter_desc && niter_desc->assumptions);
5767
5768 tree niter = niter_desc->niter;
5769 tree ntype = TREE_TYPE (niter);
5770 gcc_assert (TREE_CODE (ntype) == INTEGER_TYPE);
5771
5772 tree may_be_zero = niter_desc->may_be_zero;
5773 if (may_be_zero && integer_zerop (may_be_zero))
5774 may_be_zero = NULL_TREE;
5775 if (may_be_zero)
5776 {
5777 if (COMPARISON_CLASS_P (may_be_zero))
5778 {
5779 niter = fold_build3 (COND_EXPR, ntype, may_be_zero,
5780 build_int_cst (ntype, 0),
5781 rewrite_to_non_trapping_overflow (niter));
5782 }
5783 /* Don't try to obtain the iteration count expression when may_be_zero is
5784 integer_nonzerop (actually iteration count is one) or else. */
5785 else
5786 return;
5787 }
5788
5789 machine_mode mode = TYPE_MODE (ntype);
5790 machine_mode pref_mode = targetm.preferred_doloop_mode (mode);
5791
5792 tree base;
5793 if (mode != pref_mode)
5794 {
5795 base = compute_doloop_base_on_mode (pref_mode, niter, niter_desc->max);
5796 ntype = TREE_TYPE (base);
5797 }
5798 else
5799 base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
5800 build_int_cst (ntype, 1));
5801
5802
5803 add_candidate (data, base, build_int_cst (ntype, -1), true, NULL, NULL, true);
5804 }
5805
5806 /* Finds the candidates for the induction variables. */
5807
5808 static void
5809 find_iv_candidates (struct ivopts_data *data)
5810 {
5811 /* Add commonly used ivs. */
5812 add_standard_iv_candidates (data);
5813
5814 /* Add doloop dedicated ivs. */
5815 if (data->doloop_use_p)
5816 add_iv_candidate_for_doloop (data);
5817
5818 /* Add old induction variables. */
5819 add_iv_candidate_for_bivs (data);
5820
5821 /* Add induction variables derived from uses. */
5822 add_iv_candidate_for_groups (data);
5823
5824 set_autoinc_for_original_candidates (data);
5825
5826 /* Record the important candidates. */
5827 record_important_candidates (data);
5828
5829 /* Relate compare iv_use with all candidates. */
5830 if (!data->consider_all_candidates)
5831 relate_compare_use_with_all_cands (data);
5832
5833 if (dump_file && (dump_flags & TDF_DETAILS))
5834 {
5835 unsigned i;
5836
5837 fprintf (dump_file, "\n<Important Candidates>:\t");
5838 for (i = 0; i < data->vcands.length (); i++)
5839 if (data->vcands[i]->important)
5840 fprintf (dump_file, " %d,", data->vcands[i]->id);
5841 fprintf (dump_file, "\n");
5842
5843 fprintf (dump_file, "\n<Group, Cand> Related:\n");
5844 for (i = 0; i < data->vgroups.length (); i++)
5845 {
5846 struct iv_group *group = data->vgroups[i];
5847
5848 if (group->related_cands)
5849 {
5850 fprintf (dump_file, " Group %d:\t", group->id);
5851 dump_bitmap (dump_file, group->related_cands);
5852 }
5853 }
5854 fprintf (dump_file, "\n");
5855 }
5856 }
5857
5858 /* Determines costs of computing use of iv with an iv candidate. */
5859
5860 static void
5861 determine_group_iv_costs (struct ivopts_data *data)
5862 {
5863 unsigned i, j;
5864 struct iv_cand *cand;
5865 struct iv_group *group;
5866 bitmap to_clear = BITMAP_ALLOC (NULL);
5867
5868 alloc_use_cost_map (data);
5869
5870 for (i = 0; i < data->vgroups.length (); i++)
5871 {
5872 group = data->vgroups[i];
5873
5874 if (data->consider_all_candidates)
5875 {
5876 for (j = 0; j < data->vcands.length (); j++)
5877 {
5878 cand = data->vcands[j];
5879 determine_group_iv_cost (data, group, cand);
5880 }
5881 }
5882 else
5883 {
5884 bitmap_iterator bi;
5885
5886 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, j, bi)
5887 {
5888 cand = data->vcands[j];
5889 if (!determine_group_iv_cost (data, group, cand))
5890 bitmap_set_bit (to_clear, j);
5891 }
5892
5893 /* Remove the candidates for that the cost is infinite from
5894 the list of related candidates. */
5895 bitmap_and_compl_into (group->related_cands, to_clear);
5896 bitmap_clear (to_clear);
5897 }
5898 }
5899
5900 BITMAP_FREE (to_clear);
5901
5902 if (dump_file && (dump_flags & TDF_DETAILS))
5903 {
5904 bitmap_iterator bi;
5905
5906 /* Dump invariant variables. */
5907 fprintf (dump_file, "\n<Invariant Vars>:\n");
5908 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
5909 {
5910 struct version_info *info = ver_info (data, i);
5911 if (info->inv_id)
5912 {
5913 fprintf (dump_file, "Inv %d:\t", info->inv_id);
5914 print_generic_expr (dump_file, info->name, TDF_SLIM);
5915 fprintf (dump_file, "%s\n",
5916 info->has_nonlin_use ? "" : "\t(eliminable)");
5917 }
5918 }
5919
5920 /* Dump invariant expressions. */
5921 fprintf (dump_file, "\n<Invariant Expressions>:\n");
5922 auto_vec <iv_inv_expr_ent *> list (data->inv_expr_tab->elements ());
5923
5924 for (hash_table<iv_inv_expr_hasher>::iterator it
5925 = data->inv_expr_tab->begin (); it != data->inv_expr_tab->end ();
5926 ++it)
5927 list.safe_push (*it);
5928
5929 list.qsort (sort_iv_inv_expr_ent);
5930
5931 for (i = 0; i < list.length (); ++i)
5932 {
5933 fprintf (dump_file, "inv_expr %d: \t", list[i]->id);
5934 print_generic_expr (dump_file, list[i]->expr, TDF_SLIM);
5935 fprintf (dump_file, "\n");
5936 }
5937
5938 fprintf (dump_file, "\n<Group-candidate Costs>:\n");
5939
5940 for (i = 0; i < data->vgroups.length (); i++)
5941 {
5942 group = data->vgroups[i];
5943
5944 fprintf (dump_file, "Group %d:\n", i);
5945 fprintf (dump_file, " cand\tcost\tcompl.\tinv.expr.\tinv.vars\n");
5946 for (j = 0; j < group->n_map_members; j++)
5947 {
5948 if (!group->cost_map[j].cand
5949 || group->cost_map[j].cost.infinite_cost_p ())
5950 continue;
5951
5952 fprintf (dump_file, " %d\t%" PRId64 "\t%d\t",
5953 group->cost_map[j].cand->id,
5954 group->cost_map[j].cost.cost,
5955 group->cost_map[j].cost.complexity);
5956 if (!group->cost_map[j].inv_exprs
5957 || bitmap_empty_p (group->cost_map[j].inv_exprs))
5958 fprintf (dump_file, "NIL;\t");
5959 else
5960 bitmap_print (dump_file,
5961 group->cost_map[j].inv_exprs, "", ";\t");
5962 if (!group->cost_map[j].inv_vars
5963 || bitmap_empty_p (group->cost_map[j].inv_vars))
5964 fprintf (dump_file, "NIL;\n");
5965 else
5966 bitmap_print (dump_file,
5967 group->cost_map[j].inv_vars, "", "\n");
5968 }
5969
5970 fprintf (dump_file, "\n");
5971 }
5972 fprintf (dump_file, "\n");
5973 }
5974 }
5975
5976 /* Determines cost of the candidate CAND. */
5977
5978 static void
5979 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
5980 {
5981 comp_cost cost_base;
5982 int64_t cost, cost_step;
5983 tree base;
5984
5985 gcc_assert (cand->iv != NULL);
5986
5987 /* There are two costs associated with the candidate -- its increment
5988 and its initialization. The second is almost negligible for any loop
5989 that rolls enough, so we take it just very little into account. */
5990
5991 base = cand->iv->base;
5992 cost_base = force_var_cost (data, base, NULL);
5993 /* It will be exceptional that the iv register happens to be initialized with
5994 the proper value at no cost. In general, there will at least be a regcopy
5995 or a const set. */
5996 if (cost_base.cost == 0)
5997 cost_base.cost = COSTS_N_INSNS (1);
5998 /* Doloop decrement should be considered as zero cost. */
5999 if (cand->doloop_p)
6000 cost_step = 0;
6001 else
6002 cost_step = add_cost (data->speed, TYPE_MODE (TREE_TYPE (base)));
6003 cost = cost_step + adjust_setup_cost (data, cost_base.cost);
6004
6005 /* Prefer the original ivs unless we may gain something by replacing it.
6006 The reason is to make debugging simpler; so this is not relevant for
6007 artificial ivs created by other optimization passes. */
6008 if ((cand->pos != IP_ORIGINAL
6009 || !SSA_NAME_VAR (cand->var_before)
6010 || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
6011 /* Prefer doloop as well. */
6012 && !cand->doloop_p)
6013 cost++;
6014
6015 /* Prefer not to insert statements into latch unless there are some
6016 already (so that we do not create unnecessary jumps). */
6017 if (cand->pos == IP_END
6018 && empty_block_p (ip_end_pos (data->current_loop)))
6019 cost++;
6020
6021 cand->cost = cost;
6022 cand->cost_step = cost_step;
6023 }
6024
6025 /* Determines costs of computation of the candidates. */
6026
6027 static void
6028 determine_iv_costs (struct ivopts_data *data)
6029 {
6030 unsigned i;
6031
6032 if (dump_file && (dump_flags & TDF_DETAILS))
6033 {
6034 fprintf (dump_file, "<Candidate Costs>:\n");
6035 fprintf (dump_file, " cand\tcost\n");
6036 }
6037
6038 for (i = 0; i < data->vcands.length (); i++)
6039 {
6040 struct iv_cand *cand = data->vcands[i];
6041
6042 determine_iv_cost (data, cand);
6043
6044 if (dump_file && (dump_flags & TDF_DETAILS))
6045 fprintf (dump_file, " %d\t%d\n", i, cand->cost);
6046 }
6047
6048 if (dump_file && (dump_flags & TDF_DETAILS))
6049 fprintf (dump_file, "\n");
6050 }
6051
6052 /* Estimate register pressure for loop having N_INVS invariants and N_CANDS
6053 induction variables. Note N_INVS includes both invariant variables and
6054 invariant expressions. */
6055
6056 static unsigned
6057 ivopts_estimate_reg_pressure (struct ivopts_data *data, unsigned n_invs,
6058 unsigned n_cands)
6059 {
6060 unsigned cost;
6061 unsigned n_old = data->regs_used, n_new = n_invs + n_cands;
6062 unsigned regs_needed = n_new + n_old, available_regs = target_avail_regs;
6063 bool speed = data->speed;
6064
6065 /* If there is a call in the loop body, the call-clobbered registers
6066 are not available for loop invariants. */
6067 if (data->body_includes_call)
6068 available_regs = available_regs - target_clobbered_regs;
6069
6070 /* If we have enough registers. */
6071 if (regs_needed + target_res_regs < available_regs)
6072 cost = n_new;
6073 /* If close to running out of registers, try to preserve them. */
6074 else if (regs_needed <= available_regs)
6075 cost = target_reg_cost [speed] * regs_needed;
6076 /* If we run out of available registers but the number of candidates
6077 does not, we penalize extra registers using target_spill_cost. */
6078 else if (n_cands <= available_regs)
6079 cost = target_reg_cost [speed] * available_regs
6080 + target_spill_cost [speed] * (regs_needed - available_regs);
6081 /* If the number of candidates runs out available registers, we penalize
6082 extra candidate registers using target_spill_cost * 2. Because it is
6083 more expensive to spill induction variable than invariant. */
6084 else
6085 cost = target_reg_cost [speed] * available_regs
6086 + target_spill_cost [speed] * (n_cands - available_regs) * 2
6087 + target_spill_cost [speed] * (regs_needed - n_cands);
6088
6089 /* Finally, add the number of candidates, so that we prefer eliminating
6090 induction variables if possible. */
6091 return cost + n_cands;
6092 }
6093
6094 /* For each size of the induction variable set determine the penalty. */
6095
6096 static void
6097 determine_set_costs (struct ivopts_data *data)
6098 {
6099 unsigned j, n;
6100 gphi *phi;
6101 gphi_iterator psi;
6102 tree op;
6103 class loop *loop = data->current_loop;
6104 bitmap_iterator bi;
6105
6106 if (dump_file && (dump_flags & TDF_DETAILS))
6107 {
6108 fprintf (dump_file, "<Global Costs>:\n");
6109 fprintf (dump_file, " target_avail_regs %d\n", target_avail_regs);
6110 fprintf (dump_file, " target_clobbered_regs %d\n", target_clobbered_regs);
6111 fprintf (dump_file, " target_reg_cost %d\n", target_reg_cost[data->speed]);
6112 fprintf (dump_file, " target_spill_cost %d\n", target_spill_cost[data->speed]);
6113 }
6114
6115 n = 0;
6116 for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
6117 {
6118 phi = psi.phi ();
6119 op = PHI_RESULT (phi);
6120
6121 if (virtual_operand_p (op))
6122 continue;
6123
6124 if (get_iv (data, op))
6125 continue;
6126
6127 if (!POINTER_TYPE_P (TREE_TYPE (op))
6128 && !INTEGRAL_TYPE_P (TREE_TYPE (op)))
6129 continue;
6130
6131 n++;
6132 }
6133
6134 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
6135 {
6136 struct version_info *info = ver_info (data, j);
6137
6138 if (info->inv_id && info->has_nonlin_use)
6139 n++;
6140 }
6141
6142 data->regs_used = n;
6143 if (dump_file && (dump_flags & TDF_DETAILS))
6144 fprintf (dump_file, " regs_used %d\n", n);
6145
6146 if (dump_file && (dump_flags & TDF_DETAILS))
6147 {
6148 fprintf (dump_file, " cost for size:\n");
6149 fprintf (dump_file, " ivs\tcost\n");
6150 for (j = 0; j <= 2 * target_avail_regs; j++)
6151 fprintf (dump_file, " %d\t%d\n", j,
6152 ivopts_estimate_reg_pressure (data, 0, j));
6153 fprintf (dump_file, "\n");
6154 }
6155 }
6156
6157 /* Returns true if A is a cheaper cost pair than B. */
6158
6159 static bool
6160 cheaper_cost_pair (class cost_pair *a, class cost_pair *b)
6161 {
6162 if (!a)
6163 return false;
6164
6165 if (!b)
6166 return true;
6167
6168 if (a->cost < b->cost)
6169 return true;
6170
6171 if (b->cost < a->cost)
6172 return false;
6173
6174 /* In case the costs are the same, prefer the cheaper candidate. */
6175 if (a->cand->cost < b->cand->cost)
6176 return true;
6177
6178 return false;
6179 }
6180
6181 /* Compare if A is a more expensive cost pair than B. Return 1, 0 and -1
6182 for more expensive, equal and cheaper respectively. */
6183
6184 static int
6185 compare_cost_pair (class cost_pair *a, class cost_pair *b)
6186 {
6187 if (cheaper_cost_pair (a, b))
6188 return -1;
6189 if (cheaper_cost_pair (b, a))
6190 return 1;
6191
6192 return 0;
6193 }
6194
6195 /* Returns candidate by that USE is expressed in IVS. */
6196
6197 static class cost_pair *
6198 iv_ca_cand_for_group (class iv_ca *ivs, struct iv_group *group)
6199 {
6200 return ivs->cand_for_group[group->id];
6201 }
6202
6203 /* Computes the cost field of IVS structure. */
6204
6205 static void
6206 iv_ca_recount_cost (struct ivopts_data *data, class iv_ca *ivs)
6207 {
6208 comp_cost cost = ivs->cand_use_cost;
6209
6210 cost += ivs->cand_cost;
6211 cost += ivopts_estimate_reg_pressure (data, ivs->n_invs, ivs->n_cands);
6212 ivs->cost = cost;
6213 }
6214
6215 /* Remove use of invariants in set INVS by decreasing counter in N_INV_USES
6216 and IVS. */
6217
6218 static void
6219 iv_ca_set_remove_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
6220 {
6221 bitmap_iterator bi;
6222 unsigned iid;
6223
6224 if (!invs)
6225 return;
6226
6227 gcc_assert (n_inv_uses != NULL);
6228 EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
6229 {
6230 n_inv_uses[iid]--;
6231 if (n_inv_uses[iid] == 0)
6232 ivs->n_invs--;
6233 }
6234 }
6235
6236 /* Set USE not to be expressed by any candidate in IVS. */
6237
6238 static void
6239 iv_ca_set_no_cp (struct ivopts_data *data, class iv_ca *ivs,
6240 struct iv_group *group)
6241 {
6242 unsigned gid = group->id, cid;
6243 class cost_pair *cp;
6244
6245 cp = ivs->cand_for_group[gid];
6246 if (!cp)
6247 return;
6248 cid = cp->cand->id;
6249
6250 ivs->bad_groups++;
6251 ivs->cand_for_group[gid] = NULL;
6252 ivs->n_cand_uses[cid]--;
6253
6254 if (ivs->n_cand_uses[cid] == 0)
6255 {
6256 bitmap_clear_bit (ivs->cands, cid);
6257 if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
6258 ivs->n_cands--;
6259 ivs->cand_cost -= cp->cand->cost;
6260 iv_ca_set_remove_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
6261 iv_ca_set_remove_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses);
6262 }
6263
6264 ivs->cand_use_cost -= cp->cost;
6265 iv_ca_set_remove_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses);
6266 iv_ca_set_remove_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses);
6267 iv_ca_recount_cost (data, ivs);
6268 }
6269
6270 /* Add use of invariants in set INVS by increasing counter in N_INV_USES and
6271 IVS. */
6272
6273 static void
6274 iv_ca_set_add_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
6275 {
6276 bitmap_iterator bi;
6277 unsigned iid;
6278
6279 if (!invs)
6280 return;
6281
6282 gcc_assert (n_inv_uses != NULL);
6283 EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
6284 {
6285 n_inv_uses[iid]++;
6286 if (n_inv_uses[iid] == 1)
6287 ivs->n_invs++;
6288 }
6289 }
6290
6291 /* Set cost pair for GROUP in set IVS to CP. */
6292
6293 static void
6294 iv_ca_set_cp (struct ivopts_data *data, class iv_ca *ivs,
6295 struct iv_group *group, class cost_pair *cp)
6296 {
6297 unsigned gid = group->id, cid;
6298
6299 if (ivs->cand_for_group[gid] == cp)
6300 return;
6301
6302 if (ivs->cand_for_group[gid])
6303 iv_ca_set_no_cp (data, ivs, group);
6304
6305 if (cp)
6306 {
6307 cid = cp->cand->id;
6308
6309 ivs->bad_groups--;
6310 ivs->cand_for_group[gid] = cp;
6311 ivs->n_cand_uses[cid]++;
6312 if (ivs->n_cand_uses[cid] == 1)
6313 {
6314 bitmap_set_bit (ivs->cands, cid);
6315 if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
6316 ivs->n_cands++;
6317 ivs->cand_cost += cp->cand->cost;
6318 iv_ca_set_add_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
6319 iv_ca_set_add_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses);
6320 }
6321
6322 ivs->cand_use_cost += cp->cost;
6323 iv_ca_set_add_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses);
6324 iv_ca_set_add_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses);
6325 iv_ca_recount_cost (data, ivs);
6326 }
6327 }
6328
6329 /* Extend set IVS by expressing USE by some of the candidates in it
6330 if possible. Consider all important candidates if candidates in
6331 set IVS don't give any result. */
6332
6333 static void
6334 iv_ca_add_group (struct ivopts_data *data, class iv_ca *ivs,
6335 struct iv_group *group)
6336 {
6337 class cost_pair *best_cp = NULL, *cp;
6338 bitmap_iterator bi;
6339 unsigned i;
6340 struct iv_cand *cand;
6341
6342 gcc_assert (ivs->upto >= group->id);
6343 ivs->upto++;
6344 ivs->bad_groups++;
6345
6346 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6347 {
6348 cand = data->vcands[i];
6349 cp = get_group_iv_cost (data, group, cand);
6350 if (cheaper_cost_pair (cp, best_cp))
6351 best_cp = cp;
6352 }
6353
6354 if (best_cp == NULL)
6355 {
6356 EXECUTE_IF_SET_IN_BITMAP (data->important_candidates, 0, i, bi)
6357 {
6358 cand = data->vcands[i];
6359 cp = get_group_iv_cost (data, group, cand);
6360 if (cheaper_cost_pair (cp, best_cp))
6361 best_cp = cp;
6362 }
6363 }
6364
6365 iv_ca_set_cp (data, ivs, group, best_cp);
6366 }
6367
6368 /* Get cost for assignment IVS. */
6369
6370 static comp_cost
6371 iv_ca_cost (class iv_ca *ivs)
6372 {
6373 /* This was a conditional expression but it triggered a bug in
6374 Sun C 5.5. */
6375 if (ivs->bad_groups)
6376 return infinite_cost;
6377 else
6378 return ivs->cost;
6379 }
6380
6381 /* Compare if applying NEW_CP to GROUP for IVS introduces more invariants
6382 than OLD_CP. Return 1, 0 and -1 for more, equal and fewer invariants
6383 respectively. */
6384
6385 static int
6386 iv_ca_compare_deps (struct ivopts_data *data, class iv_ca *ivs,
6387 struct iv_group *group, class cost_pair *old_cp,
6388 class cost_pair *new_cp)
6389 {
6390 gcc_assert (old_cp && new_cp && old_cp != new_cp);
6391 unsigned old_n_invs = ivs->n_invs;
6392 iv_ca_set_cp (data, ivs, group, new_cp);
6393 unsigned new_n_invs = ivs->n_invs;
6394 iv_ca_set_cp (data, ivs, group, old_cp);
6395
6396 return new_n_invs > old_n_invs ? 1 : (new_n_invs < old_n_invs ? -1 : 0);
6397 }
6398
6399 /* Creates change of expressing GROUP by NEW_CP instead of OLD_CP and chains
6400 it before NEXT. */
6401
6402 static struct iv_ca_delta *
6403 iv_ca_delta_add (struct iv_group *group, class cost_pair *old_cp,
6404 class cost_pair *new_cp, struct iv_ca_delta *next)
6405 {
6406 struct iv_ca_delta *change = XNEW (struct iv_ca_delta);
6407
6408 change->group = group;
6409 change->old_cp = old_cp;
6410 change->new_cp = new_cp;
6411 change->next = next;
6412
6413 return change;
6414 }
6415
6416 /* Joins two lists of changes L1 and L2. Destructive -- old lists
6417 are rewritten. */
6418
6419 static struct iv_ca_delta *
6420 iv_ca_delta_join (struct iv_ca_delta *l1, struct iv_ca_delta *l2)
6421 {
6422 struct iv_ca_delta *last;
6423
6424 if (!l2)
6425 return l1;
6426
6427 if (!l1)
6428 return l2;
6429
6430 for (last = l1; last->next; last = last->next)
6431 continue;
6432 last->next = l2;
6433
6434 return l1;
6435 }
6436
6437 /* Reverse the list of changes DELTA, forming the inverse to it. */
6438
6439 static struct iv_ca_delta *
6440 iv_ca_delta_reverse (struct iv_ca_delta *delta)
6441 {
6442 struct iv_ca_delta *act, *next, *prev = NULL;
6443
6444 for (act = delta; act; act = next)
6445 {
6446 next = act->next;
6447 act->next = prev;
6448 prev = act;
6449
6450 std::swap (act->old_cp, act->new_cp);
6451 }
6452
6453 return prev;
6454 }
6455
6456 /* Commit changes in DELTA to IVS. If FORWARD is false, the changes are
6457 reverted instead. */
6458
6459 static void
6460 iv_ca_delta_commit (struct ivopts_data *data, class iv_ca *ivs,
6461 struct iv_ca_delta *delta, bool forward)
6462 {
6463 class cost_pair *from, *to;
6464 struct iv_ca_delta *act;
6465
6466 if (!forward)
6467 delta = iv_ca_delta_reverse (delta);
6468
6469 for (act = delta; act; act = act->next)
6470 {
6471 from = act->old_cp;
6472 to = act->new_cp;
6473 gcc_assert (iv_ca_cand_for_group (ivs, act->group) == from);
6474 iv_ca_set_cp (data, ivs, act->group, to);
6475 }
6476
6477 if (!forward)
6478 iv_ca_delta_reverse (delta);
6479 }
6480
6481 /* Returns true if CAND is used in IVS. */
6482
6483 static bool
6484 iv_ca_cand_used_p (class iv_ca *ivs, struct iv_cand *cand)
6485 {
6486 return ivs->n_cand_uses[cand->id] > 0;
6487 }
6488
6489 /* Returns number of induction variable candidates in the set IVS. */
6490
6491 static unsigned
6492 iv_ca_n_cands (class iv_ca *ivs)
6493 {
6494 return ivs->n_cands;
6495 }
6496
6497 /* Free the list of changes DELTA. */
6498
6499 static void
6500 iv_ca_delta_free (struct iv_ca_delta **delta)
6501 {
6502 struct iv_ca_delta *act, *next;
6503
6504 for (act = *delta; act; act = next)
6505 {
6506 next = act->next;
6507 free (act);
6508 }
6509
6510 *delta = NULL;
6511 }
6512
6513 /* Allocates new iv candidates assignment. */
6514
6515 static class iv_ca *
6516 iv_ca_new (struct ivopts_data *data)
6517 {
6518 class iv_ca *nw = XNEW (class iv_ca);
6519
6520 nw->upto = 0;
6521 nw->bad_groups = 0;
6522 nw->cand_for_group = XCNEWVEC (class cost_pair *,
6523 data->vgroups.length ());
6524 nw->n_cand_uses = XCNEWVEC (unsigned, data->vcands.length ());
6525 nw->cands = BITMAP_ALLOC (NULL);
6526 nw->n_cands = 0;
6527 nw->n_invs = 0;
6528 nw->cand_use_cost = no_cost;
6529 nw->cand_cost = 0;
6530 nw->n_inv_var_uses = XCNEWVEC (unsigned, data->max_inv_var_id + 1);
6531 nw->n_inv_expr_uses = XCNEWVEC (unsigned, data->max_inv_expr_id + 1);
6532 nw->cost = no_cost;
6533
6534 return nw;
6535 }
6536
6537 /* Free memory occupied by the set IVS. */
6538
6539 static void
6540 iv_ca_free (class iv_ca **ivs)
6541 {
6542 free ((*ivs)->cand_for_group);
6543 free ((*ivs)->n_cand_uses);
6544 BITMAP_FREE ((*ivs)->cands);
6545 free ((*ivs)->n_inv_var_uses);
6546 free ((*ivs)->n_inv_expr_uses);
6547 free (*ivs);
6548 *ivs = NULL;
6549 }
6550
6551 /* Dumps IVS to FILE. */
6552
6553 static void
6554 iv_ca_dump (struct ivopts_data *data, FILE *file, class iv_ca *ivs)
6555 {
6556 unsigned i;
6557 comp_cost cost = iv_ca_cost (ivs);
6558
6559 fprintf (file, " cost: %" PRId64 " (complexity %d)\n", cost.cost,
6560 cost.complexity);
6561 fprintf (file, " reg_cost: %d\n",
6562 ivopts_estimate_reg_pressure (data, ivs->n_invs, ivs->n_cands));
6563 fprintf (file, " cand_cost: %" PRId64 "\n cand_group_cost: "
6564 "%" PRId64 " (complexity %d)\n", ivs->cand_cost,
6565 ivs->cand_use_cost.cost, ivs->cand_use_cost.complexity);
6566 bitmap_print (file, ivs->cands, " candidates: ","\n");
6567
6568 for (i = 0; i < ivs->upto; i++)
6569 {
6570 struct iv_group *group = data->vgroups[i];
6571 class cost_pair *cp = iv_ca_cand_for_group (ivs, group);
6572 if (cp)
6573 fprintf (file, " group:%d --> iv_cand:%d, cost=("
6574 "%" PRId64 ",%d)\n", group->id, cp->cand->id,
6575 cp->cost.cost, cp->cost.complexity);
6576 else
6577 fprintf (file, " group:%d --> ??\n", group->id);
6578 }
6579
6580 const char *pref = "";
6581 fprintf (file, " invariant variables: ");
6582 for (i = 1; i <= data->max_inv_var_id; i++)
6583 if (ivs->n_inv_var_uses[i])
6584 {
6585 fprintf (file, "%s%d", pref, i);
6586 pref = ", ";
6587 }
6588
6589 pref = "";
6590 fprintf (file, "\n invariant expressions: ");
6591 for (i = 1; i <= data->max_inv_expr_id; i++)
6592 if (ivs->n_inv_expr_uses[i])
6593 {
6594 fprintf (file, "%s%d", pref, i);
6595 pref = ", ";
6596 }
6597
6598 fprintf (file, "\n\n");
6599 }
6600
6601 /* Try changing candidate in IVS to CAND for each use. Return cost of the
6602 new set, and store differences in DELTA. Number of induction variables
6603 in the new set is stored to N_IVS. MIN_NCAND is a flag. When it is true
6604 the function will try to find a solution with mimimal iv candidates. */
6605
6606 static comp_cost
6607 iv_ca_extend (struct ivopts_data *data, class iv_ca *ivs,
6608 struct iv_cand *cand, struct iv_ca_delta **delta,
6609 unsigned *n_ivs, bool min_ncand)
6610 {
6611 unsigned i;
6612 comp_cost cost;
6613 struct iv_group *group;
6614 class cost_pair *old_cp, *new_cp;
6615
6616 *delta = NULL;
6617 for (i = 0; i < ivs->upto; i++)
6618 {
6619 group = data->vgroups[i];
6620 old_cp = iv_ca_cand_for_group (ivs, group);
6621
6622 if (old_cp
6623 && old_cp->cand == cand)
6624 continue;
6625
6626 new_cp = get_group_iv_cost (data, group, cand);
6627 if (!new_cp)
6628 continue;
6629
6630 if (!min_ncand)
6631 {
6632 int cmp_invs = iv_ca_compare_deps (data, ivs, group, old_cp, new_cp);
6633 /* Skip if new_cp depends on more invariants. */
6634 if (cmp_invs > 0)
6635 continue;
6636
6637 int cmp_cost = compare_cost_pair (new_cp, old_cp);
6638 /* Skip if new_cp is not cheaper. */
6639 if (cmp_cost > 0 || (cmp_cost == 0 && cmp_invs == 0))
6640 continue;
6641 }
6642
6643 *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
6644 }
6645
6646 iv_ca_delta_commit (data, ivs, *delta, true);
6647 cost = iv_ca_cost (ivs);
6648 if (n_ivs)
6649 *n_ivs = iv_ca_n_cands (ivs);
6650 iv_ca_delta_commit (data, ivs, *delta, false);
6651
6652 return cost;
6653 }
6654
6655 /* Try narrowing set IVS by removing CAND. Return the cost of
6656 the new set and store the differences in DELTA. START is
6657 the candidate with which we start narrowing. */
6658
6659 static comp_cost
6660 iv_ca_narrow (struct ivopts_data *data, class iv_ca *ivs,
6661 struct iv_cand *cand, struct iv_cand *start,
6662 struct iv_ca_delta **delta)
6663 {
6664 unsigned i, ci;
6665 struct iv_group *group;
6666 class cost_pair *old_cp, *new_cp, *cp;
6667 bitmap_iterator bi;
6668 struct iv_cand *cnd;
6669 comp_cost cost, best_cost, acost;
6670
6671 *delta = NULL;
6672 for (i = 0; i < data->vgroups.length (); i++)
6673 {
6674 group = data->vgroups[i];
6675
6676 old_cp = iv_ca_cand_for_group (ivs, group);
6677 if (old_cp->cand != cand)
6678 continue;
6679
6680 best_cost = iv_ca_cost (ivs);
6681 /* Start narrowing with START. */
6682 new_cp = get_group_iv_cost (data, group, start);
6683
6684 if (data->consider_all_candidates)
6685 {
6686 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, ci, bi)
6687 {
6688 if (ci == cand->id || (start && ci == start->id))
6689 continue;
6690
6691 cnd = data->vcands[ci];
6692
6693 cp = get_group_iv_cost (data, group, cnd);
6694 if (!cp)
6695 continue;
6696
6697 iv_ca_set_cp (data, ivs, group, cp);
6698 acost = iv_ca_cost (ivs);
6699
6700 if (acost < best_cost)
6701 {
6702 best_cost = acost;
6703 new_cp = cp;
6704 }
6705 }
6706 }
6707 else
6708 {
6709 EXECUTE_IF_AND_IN_BITMAP (group->related_cands, ivs->cands, 0, ci, bi)
6710 {
6711 if (ci == cand->id || (start && ci == start->id))
6712 continue;
6713
6714 cnd = data->vcands[ci];
6715
6716 cp = get_group_iv_cost (data, group, cnd);
6717 if (!cp)
6718 continue;
6719
6720 iv_ca_set_cp (data, ivs, group, cp);
6721 acost = iv_ca_cost (ivs);
6722
6723 if (acost < best_cost)
6724 {
6725 best_cost = acost;
6726 new_cp = cp;
6727 }
6728 }
6729 }
6730 /* Restore to old cp for use. */
6731 iv_ca_set_cp (data, ivs, group, old_cp);
6732
6733 if (!new_cp)
6734 {
6735 iv_ca_delta_free (delta);
6736 return infinite_cost;
6737 }
6738
6739 *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
6740 }
6741
6742 iv_ca_delta_commit (data, ivs, *delta, true);
6743 cost = iv_ca_cost (ivs);
6744 iv_ca_delta_commit (data, ivs, *delta, false);
6745
6746 return cost;
6747 }
6748
6749 /* Try optimizing the set of candidates IVS by removing candidates different
6750 from to EXCEPT_CAND from it. Return cost of the new set, and store
6751 differences in DELTA. */
6752
6753 static comp_cost
6754 iv_ca_prune (struct ivopts_data *data, class iv_ca *ivs,
6755 struct iv_cand *except_cand, struct iv_ca_delta **delta)
6756 {
6757 bitmap_iterator bi;
6758 struct iv_ca_delta *act_delta, *best_delta;
6759 unsigned i;
6760 comp_cost best_cost, acost;
6761 struct iv_cand *cand;
6762
6763 best_delta = NULL;
6764 best_cost = iv_ca_cost (ivs);
6765
6766 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6767 {
6768 cand = data->vcands[i];
6769
6770 if (cand == except_cand)
6771 continue;
6772
6773 acost = iv_ca_narrow (data, ivs, cand, except_cand, &act_delta);
6774
6775 if (acost < best_cost)
6776 {
6777 best_cost = acost;
6778 iv_ca_delta_free (&best_delta);
6779 best_delta = act_delta;
6780 }
6781 else
6782 iv_ca_delta_free (&act_delta);
6783 }
6784
6785 if (!best_delta)
6786 {
6787 *delta = NULL;
6788 return best_cost;
6789 }
6790
6791 /* Recurse to possibly remove other unnecessary ivs. */
6792 iv_ca_delta_commit (data, ivs, best_delta, true);
6793 best_cost = iv_ca_prune (data, ivs, except_cand, delta);
6794 iv_ca_delta_commit (data, ivs, best_delta, false);
6795 *delta = iv_ca_delta_join (best_delta, *delta);
6796 return best_cost;
6797 }
6798
6799 /* Check if CAND_IDX is a candidate other than OLD_CAND and has
6800 cheaper local cost for GROUP than BEST_CP. Return pointer to
6801 the corresponding cost_pair, otherwise just return BEST_CP. */
6802
6803 static class cost_pair*
6804 cheaper_cost_with_cand (struct ivopts_data *data, struct iv_group *group,
6805 unsigned int cand_idx, struct iv_cand *old_cand,
6806 class cost_pair *best_cp)
6807 {
6808 struct iv_cand *cand;
6809 class cost_pair *cp;
6810
6811 gcc_assert (old_cand != NULL && best_cp != NULL);
6812 if (cand_idx == old_cand->id)
6813 return best_cp;
6814
6815 cand = data->vcands[cand_idx];
6816 cp = get_group_iv_cost (data, group, cand);
6817 if (cp != NULL && cheaper_cost_pair (cp, best_cp))
6818 return cp;
6819
6820 return best_cp;
6821 }
6822
6823 /* Try breaking local optimal fixed-point for IVS by replacing candidates
6824 which are used by more than one iv uses. For each of those candidates,
6825 this function tries to represent iv uses under that candidate using
6826 other ones with lower local cost, then tries to prune the new set.
6827 If the new set has lower cost, It returns the new cost after recording
6828 candidate replacement in list DELTA. */
6829
6830 static comp_cost
6831 iv_ca_replace (struct ivopts_data *data, class iv_ca *ivs,
6832 struct iv_ca_delta **delta)
6833 {
6834 bitmap_iterator bi, bj;
6835 unsigned int i, j, k;
6836 struct iv_cand *cand;
6837 comp_cost orig_cost, acost;
6838 struct iv_ca_delta *act_delta, *tmp_delta;
6839 class cost_pair *old_cp, *best_cp = NULL;
6840
6841 *delta = NULL;
6842 orig_cost = iv_ca_cost (ivs);
6843
6844 EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
6845 {
6846 if (ivs->n_cand_uses[i] == 1
6847 || ivs->n_cand_uses[i] > ALWAYS_PRUNE_CAND_SET_BOUND)
6848 continue;
6849
6850 cand = data->vcands[i];
6851
6852 act_delta = NULL;
6853 /* Represent uses under current candidate using other ones with
6854 lower local cost. */
6855 for (j = 0; j < ivs->upto; j++)
6856 {
6857 struct iv_group *group = data->vgroups[j];
6858 old_cp = iv_ca_cand_for_group (ivs, group);
6859
6860 if (old_cp->cand != cand)
6861 continue;
6862
6863 best_cp = old_cp;
6864 if (data->consider_all_candidates)
6865 for (k = 0; k < data->vcands.length (); k++)
6866 best_cp = cheaper_cost_with_cand (data, group, k,
6867 old_cp->cand, best_cp);
6868 else
6869 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, k, bj)
6870 best_cp = cheaper_cost_with_cand (data, group, k,
6871 old_cp->cand, best_cp);
6872
6873 if (best_cp == old_cp)
6874 continue;
6875
6876 act_delta = iv_ca_delta_add (group, old_cp, best_cp, act_delta);
6877 }
6878 /* No need for further prune. */
6879 if (!act_delta)
6880 continue;
6881
6882 /* Prune the new candidate set. */
6883 iv_ca_delta_commit (data, ivs, act_delta, true);
6884 acost = iv_ca_prune (data, ivs, NULL, &tmp_delta);
6885 iv_ca_delta_commit (data, ivs, act_delta, false);
6886 act_delta = iv_ca_delta_join (act_delta, tmp_delta);
6887
6888 if (acost < orig_cost)
6889 {
6890 *delta = act_delta;
6891 return acost;
6892 }
6893 else
6894 iv_ca_delta_free (&act_delta);
6895 }
6896
6897 return orig_cost;
6898 }
6899
6900 /* Tries to extend the sets IVS in the best possible way in order to
6901 express the GROUP. If ORIGINALP is true, prefer candidates from
6902 the original set of IVs, otherwise favor important candidates not
6903 based on any memory object. */
6904
6905 static bool
6906 try_add_cand_for (struct ivopts_data *data, class iv_ca *ivs,
6907 struct iv_group *group, bool originalp)
6908 {
6909 comp_cost best_cost, act_cost;
6910 unsigned i;
6911 bitmap_iterator bi;
6912 struct iv_cand *cand;
6913 struct iv_ca_delta *best_delta = NULL, *act_delta;
6914 class cost_pair *cp;
6915
6916 iv_ca_add_group (data, ivs, group);
6917 best_cost = iv_ca_cost (ivs);
6918 cp = iv_ca_cand_for_group (ivs, group);
6919 if (cp)
6920 {
6921 best_delta = iv_ca_delta_add (group, NULL, cp, NULL);
6922 iv_ca_set_no_cp (data, ivs, group);
6923 }
6924
6925 /* If ORIGINALP is true, try to find the original IV for the use. Otherwise
6926 first try important candidates not based on any memory object. Only if
6927 this fails, try the specific ones. Rationale -- in loops with many
6928 variables the best choice often is to use just one generic biv. If we
6929 added here many ivs specific to the uses, the optimization algorithm later
6930 would be likely to get stuck in a local minimum, thus causing us to create
6931 too many ivs. The approach from few ivs to more seems more likely to be
6932 successful -- starting from few ivs, replacing an expensive use by a
6933 specific iv should always be a win. */
6934 EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, i, bi)
6935 {
6936 cand = data->vcands[i];
6937
6938 if (originalp && cand->pos !=IP_ORIGINAL)
6939 continue;
6940
6941 if (!originalp && cand->iv->base_object != NULL_TREE)
6942 continue;
6943
6944 if (iv_ca_cand_used_p (ivs, cand))
6945 continue;
6946
6947 cp = get_group_iv_cost (data, group, cand);
6948 if (!cp)
6949 continue;
6950
6951 iv_ca_set_cp (data, ivs, group, cp);
6952 act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL,
6953 true);
6954 iv_ca_set_no_cp (data, ivs, group);
6955 act_delta = iv_ca_delta_add (group, NULL, cp, act_delta);
6956
6957 if (act_cost < best_cost)
6958 {
6959 best_cost = act_cost;
6960
6961 iv_ca_delta_free (&best_delta);
6962 best_delta = act_delta;
6963 }
6964 else
6965 iv_ca_delta_free (&act_delta);
6966 }
6967
6968 if (best_cost.infinite_cost_p ())
6969 {
6970 for (i = 0; i < group->n_map_members; i++)
6971 {
6972 cp = group->cost_map + i;
6973 cand = cp->cand;
6974 if (!cand)
6975 continue;
6976
6977 /* Already tried this. */
6978 if (cand->important)
6979 {
6980 if (originalp && cand->pos == IP_ORIGINAL)
6981 continue;
6982 if (!originalp && cand->iv->base_object == NULL_TREE)
6983 continue;
6984 }
6985
6986 if (iv_ca_cand_used_p (ivs, cand))
6987 continue;
6988
6989 act_delta = NULL;
6990 iv_ca_set_cp (data, ivs, group, cp);
6991 act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL, true);
6992 iv_ca_set_no_cp (data, ivs, group);
6993 act_delta = iv_ca_delta_add (group,
6994 iv_ca_cand_for_group (ivs, group),
6995 cp, act_delta);
6996
6997 if (act_cost < best_cost)
6998 {
6999 best_cost = act_cost;
7000
7001 if (best_delta)
7002 iv_ca_delta_free (&best_delta);
7003 best_delta = act_delta;
7004 }
7005 else
7006 iv_ca_delta_free (&act_delta);
7007 }
7008 }
7009
7010 iv_ca_delta_commit (data, ivs, best_delta, true);
7011 iv_ca_delta_free (&best_delta);
7012
7013 return !best_cost.infinite_cost_p ();
7014 }
7015
7016 /* Finds an initial assignment of candidates to uses. */
7017
7018 static class iv_ca *
7019 get_initial_solution (struct ivopts_data *data, bool originalp)
7020 {
7021 unsigned i;
7022 class iv_ca *ivs = iv_ca_new (data);
7023
7024 for (i = 0; i < data->vgroups.length (); i++)
7025 if (!try_add_cand_for (data, ivs, data->vgroups[i], originalp))
7026 {
7027 iv_ca_free (&ivs);
7028 return NULL;
7029 }
7030
7031 return ivs;
7032 }
7033
7034 /* Tries to improve set of induction variables IVS. TRY_REPLACE_P
7035 points to a bool variable, this function tries to break local
7036 optimal fixed-point by replacing candidates in IVS if it's true. */
7037
7038 static bool
7039 try_improve_iv_set (struct ivopts_data *data,
7040 class iv_ca *ivs, bool *try_replace_p)
7041 {
7042 unsigned i, n_ivs;
7043 comp_cost acost, best_cost = iv_ca_cost (ivs);
7044 struct iv_ca_delta *best_delta = NULL, *act_delta, *tmp_delta;
7045 struct iv_cand *cand;
7046
7047 /* Try extending the set of induction variables by one. */
7048 for (i = 0; i < data->vcands.length (); i++)
7049 {
7050 cand = data->vcands[i];
7051
7052 if (iv_ca_cand_used_p (ivs, cand))
7053 continue;
7054
7055 acost = iv_ca_extend (data, ivs, cand, &act_delta, &n_ivs, false);
7056 if (!act_delta)
7057 continue;
7058
7059 /* If we successfully added the candidate and the set is small enough,
7060 try optimizing it by removing other candidates. */
7061 if (n_ivs <= ALWAYS_PRUNE_CAND_SET_BOUND)
7062 {
7063 iv_ca_delta_commit (data, ivs, act_delta, true);
7064 acost = iv_ca_prune (data, ivs, cand, &tmp_delta);
7065 iv_ca_delta_commit (data, ivs, act_delta, false);
7066 act_delta = iv_ca_delta_join (act_delta, tmp_delta);
7067 }
7068
7069 if (acost < best_cost)
7070 {
7071 best_cost = acost;
7072 iv_ca_delta_free (&best_delta);
7073 best_delta = act_delta;
7074 }
7075 else
7076 iv_ca_delta_free (&act_delta);
7077 }
7078
7079 if (!best_delta)
7080 {
7081 /* Try removing the candidates from the set instead. */
7082 best_cost = iv_ca_prune (data, ivs, NULL, &best_delta);
7083
7084 if (!best_delta && *try_replace_p)
7085 {
7086 *try_replace_p = false;
7087 /* So far candidate selecting algorithm tends to choose fewer IVs
7088 so that it can handle cases in which loops have many variables
7089 but the best choice is often to use only one general biv. One
7090 weakness is it can't handle opposite cases, in which different
7091 candidates should be chosen with respect to each use. To solve
7092 the problem, we replace candidates in a manner described by the
7093 comments of iv_ca_replace, thus give general algorithm a chance
7094 to break local optimal fixed-point in these cases. */
7095 best_cost = iv_ca_replace (data, ivs, &best_delta);
7096 }
7097
7098 if (!best_delta)
7099 return false;
7100 }
7101
7102 iv_ca_delta_commit (data, ivs, best_delta, true);
7103 iv_ca_delta_free (&best_delta);
7104 return best_cost == iv_ca_cost (ivs);
7105 }
7106
7107 /* Attempts to find the optimal set of induction variables. We do simple
7108 greedy heuristic -- we try to replace at most one candidate in the selected
7109 solution and remove the unused ivs while this improves the cost. */
7110
7111 static class iv_ca *
7112 find_optimal_iv_set_1 (struct ivopts_data *data, bool originalp)
7113 {
7114 class iv_ca *set;
7115 bool try_replace_p = true;
7116
7117 /* Get the initial solution. */
7118 set = get_initial_solution (data, originalp);
7119 if (!set)
7120 {
7121 if (dump_file && (dump_flags & TDF_DETAILS))
7122 fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
7123 return NULL;
7124 }
7125
7126 if (dump_file && (dump_flags & TDF_DETAILS))
7127 {
7128 fprintf (dump_file, "Initial set of candidates:\n");
7129 iv_ca_dump (data, dump_file, set);
7130 }
7131
7132 while (try_improve_iv_set (data, set, &try_replace_p))
7133 {
7134 if (dump_file && (dump_flags & TDF_DETAILS))
7135 {
7136 fprintf (dump_file, "Improved to:\n");
7137 iv_ca_dump (data, dump_file, set);
7138 }
7139 }
7140
7141 /* If the set has infinite_cost, it can't be optimal. */
7142 if (iv_ca_cost (set).infinite_cost_p ())
7143 {
7144 if (dump_file && (dump_flags & TDF_DETAILS))
7145 fprintf (dump_file,
7146 "Overflow to infinite cost in try_improve_iv_set.\n");
7147 iv_ca_free (&set);
7148 }
7149 return set;
7150 }
7151
7152 static class iv_ca *
7153 find_optimal_iv_set (struct ivopts_data *data)
7154 {
7155 unsigned i;
7156 comp_cost cost, origcost;
7157 class iv_ca *set, *origset;
7158
7159 /* Determine the cost based on a strategy that starts with original IVs,
7160 and try again using a strategy that prefers candidates not based
7161 on any IVs. */
7162 origset = find_optimal_iv_set_1 (data, true);
7163 set = find_optimal_iv_set_1 (data, false);
7164
7165 if (!origset && !set)
7166 return NULL;
7167
7168 origcost = origset ? iv_ca_cost (origset) : infinite_cost;
7169 cost = set ? iv_ca_cost (set) : infinite_cost;
7170
7171 if (dump_file && (dump_flags & TDF_DETAILS))
7172 {
7173 fprintf (dump_file, "Original cost %" PRId64 " (complexity %d)\n\n",
7174 origcost.cost, origcost.complexity);
7175 fprintf (dump_file, "Final cost %" PRId64 " (complexity %d)\n\n",
7176 cost.cost, cost.complexity);
7177 }
7178
7179 /* Choose the one with the best cost. */
7180 if (origcost <= cost)
7181 {
7182 if (set)
7183 iv_ca_free (&set);
7184 set = origset;
7185 }
7186 else if (origset)
7187 iv_ca_free (&origset);
7188
7189 for (i = 0; i < data->vgroups.length (); i++)
7190 {
7191 struct iv_group *group = data->vgroups[i];
7192 group->selected = iv_ca_cand_for_group (set, group)->cand;
7193 }
7194
7195 return set;
7196 }
7197
7198 /* Creates a new induction variable corresponding to CAND. */
7199
7200 static void
7201 create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
7202 {
7203 gimple_stmt_iterator incr_pos;
7204 tree base;
7205 struct iv_use *use;
7206 struct iv_group *group;
7207 bool after = false;
7208
7209 gcc_assert (cand->iv != NULL);
7210
7211 switch (cand->pos)
7212 {
7213 case IP_NORMAL:
7214 incr_pos = gsi_last_bb (ip_normal_pos (data->current_loop));
7215 break;
7216
7217 case IP_END:
7218 incr_pos = gsi_last_bb (ip_end_pos (data->current_loop));
7219 after = true;
7220 gcc_assert (gsi_end_p (incr_pos) || !stmt_ends_bb_p (*incr_pos));
7221 break;
7222
7223 case IP_AFTER_USE:
7224 after = true;
7225 /* fall through */
7226 case IP_BEFORE_USE:
7227 incr_pos = gsi_for_stmt (cand->incremented_at);
7228 break;
7229
7230 case IP_ORIGINAL:
7231 /* Mark that the iv is preserved. */
7232 name_info (data, cand->var_before)->preserve_biv = true;
7233 name_info (data, cand->var_after)->preserve_biv = true;
7234
7235 /* Rewrite the increment so that it uses var_before directly. */
7236 use = find_interesting_uses_op (data, cand->var_after);
7237 group = data->vgroups[use->group_id];
7238 group->selected = cand;
7239 return;
7240 }
7241
7242 gimple_add_tmp_var (cand->var_before);
7243
7244 base = unshare_expr (cand->iv->base);
7245
7246 create_iv (base, PLUS_EXPR, unshare_expr (cand->iv->step),
7247 cand->var_before, data->current_loop,
7248 &incr_pos, after, &cand->var_before, &cand->var_after);
7249 }
7250
7251 /* Creates new induction variables described in SET. */
7252
7253 static void
7254 create_new_ivs (struct ivopts_data *data, class iv_ca *set)
7255 {
7256 unsigned i;
7257 struct iv_cand *cand;
7258 bitmap_iterator bi;
7259
7260 EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
7261 {
7262 cand = data->vcands[i];
7263 create_new_iv (data, cand);
7264 }
7265
7266 if (dump_file && (dump_flags & TDF_DETAILS))
7267 {
7268 fprintf (dump_file, "Selected IV set for loop %d",
7269 data->current_loop->num);
7270 if (data->loop_loc != UNKNOWN_LOCATION)
7271 fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
7272 LOCATION_LINE (data->loop_loc));
7273 fprintf (dump_file, ", " HOST_WIDE_INT_PRINT_DEC " avg niters",
7274 avg_loop_niter (data->current_loop));
7275 fprintf (dump_file, ", %lu IVs:\n", bitmap_count_bits (set->cands));
7276 EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
7277 {
7278 cand = data->vcands[i];
7279 dump_cand (dump_file, cand);
7280 }
7281 fprintf (dump_file, "\n");
7282 }
7283 }
7284
7285 /* Rewrites USE (definition of iv used in a nonlinear expression)
7286 using candidate CAND. */
7287
7288 static void
7289 rewrite_use_nonlinear_expr (struct ivopts_data *data,
7290 struct iv_use *use, struct iv_cand *cand)
7291 {
7292 gassign *ass;
7293 gimple_stmt_iterator bsi;
7294 tree comp, type = get_use_type (use), tgt;
7295
7296 /* An important special case -- if we are asked to express value of
7297 the original iv by itself, just exit; there is no need to
7298 introduce a new computation (that might also need casting the
7299 variable to unsigned and back). */
7300 if (cand->pos == IP_ORIGINAL
7301 && cand->incremented_at == use->stmt)
7302 {
7303 tree op = NULL_TREE;
7304 enum tree_code stmt_code;
7305
7306 gcc_assert (is_gimple_assign (use->stmt));
7307 gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
7308
7309 /* Check whether we may leave the computation unchanged.
7310 This is the case only if it does not rely on other
7311 computations in the loop -- otherwise, the computation
7312 we rely upon may be removed in remove_unused_ivs,
7313 thus leading to ICE. */
7314 stmt_code = gimple_assign_rhs_code (use->stmt);
7315 if (stmt_code == PLUS_EXPR
7316 || stmt_code == MINUS_EXPR
7317 || stmt_code == POINTER_PLUS_EXPR)
7318 {
7319 if (gimple_assign_rhs1 (use->stmt) == cand->var_before)
7320 op = gimple_assign_rhs2 (use->stmt);
7321 else if (gimple_assign_rhs2 (use->stmt) == cand->var_before)
7322 op = gimple_assign_rhs1 (use->stmt);
7323 }
7324
7325 if (op != NULL_TREE)
7326 {
7327 if (expr_invariant_in_loop_p (data->current_loop, op))
7328 return;
7329 if (TREE_CODE (op) == SSA_NAME)
7330 {
7331 struct iv *iv = get_iv (data, op);
7332 if (iv != NULL && integer_zerop (iv->step))
7333 return;
7334 }
7335 }
7336 }
7337
7338 switch (gimple_code (use->stmt))
7339 {
7340 case GIMPLE_PHI:
7341 tgt = PHI_RESULT (use->stmt);
7342
7343 /* If we should keep the biv, do not replace it. */
7344 if (name_info (data, tgt)->preserve_biv)
7345 return;
7346
7347 bsi = gsi_after_labels (gimple_bb (use->stmt));
7348 break;
7349
7350 case GIMPLE_ASSIGN:
7351 tgt = gimple_assign_lhs (use->stmt);
7352 bsi = gsi_for_stmt (use->stmt);
7353 break;
7354
7355 default:
7356 gcc_unreachable ();
7357 }
7358
7359 aff_tree aff_inv, aff_var;
7360 if (!get_computation_aff_1 (data->current_loop, use->stmt,
7361 use, cand, &aff_inv, &aff_var))
7362 gcc_unreachable ();
7363
7364 unshare_aff_combination (&aff_inv);
7365 unshare_aff_combination (&aff_var);
7366 /* Prefer CSE opportunity than loop invariant by adding offset at last
7367 so that iv_uses have different offsets can be CSEed. */
7368 poly_widest_int offset = aff_inv.offset;
7369 aff_inv.offset = 0;
7370
7371 gimple_seq stmt_list = NULL, seq = NULL;
7372 tree comp_op1 = aff_combination_to_tree (&aff_inv);
7373 tree comp_op2 = aff_combination_to_tree (&aff_var);
7374 gcc_assert (comp_op1 && comp_op2);
7375
7376 comp_op1 = force_gimple_operand (comp_op1, &seq, true, NULL);
7377 gimple_seq_add_seq (&stmt_list, seq);
7378 comp_op2 = force_gimple_operand (comp_op2, &seq, true, NULL);
7379 gimple_seq_add_seq (&stmt_list, seq);
7380
7381 if (POINTER_TYPE_P (TREE_TYPE (comp_op2)))
7382 std::swap (comp_op1, comp_op2);
7383
7384 if (POINTER_TYPE_P (TREE_TYPE (comp_op1)))
7385 {
7386 comp = fold_build_pointer_plus (comp_op1,
7387 fold_convert (sizetype, comp_op2));
7388 comp = fold_build_pointer_plus (comp,
7389 wide_int_to_tree (sizetype, offset));
7390 }
7391 else
7392 {
7393 comp = fold_build2 (PLUS_EXPR, TREE_TYPE (comp_op1), comp_op1,
7394 fold_convert (TREE_TYPE (comp_op1), comp_op2));
7395 comp = fold_build2 (PLUS_EXPR, TREE_TYPE (comp_op1), comp,
7396 wide_int_to_tree (TREE_TYPE (comp_op1), offset));
7397 }
7398
7399 comp = fold_convert (type, comp);
7400 comp = force_gimple_operand (comp, &seq, false, NULL);
7401 gimple_seq_add_seq (&stmt_list, seq);
7402 if (gimple_code (use->stmt) != GIMPLE_PHI
7403 /* We can't allow re-allocating the stmt as it might be pointed
7404 to still. */
7405 && (get_gimple_rhs_num_ops (TREE_CODE (comp))
7406 >= gimple_num_ops (gsi_stmt (bsi))))
7407 {
7408 comp = force_gimple_operand (comp, &seq, true, NULL);
7409 gimple_seq_add_seq (&stmt_list, seq);
7410 if (POINTER_TYPE_P (TREE_TYPE (tgt)))
7411 {
7412 duplicate_ssa_name_ptr_info (comp, SSA_NAME_PTR_INFO (tgt));
7413 /* As this isn't a plain copy we have to reset alignment
7414 information. */
7415 if (SSA_NAME_PTR_INFO (comp))
7416 mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (comp));
7417 }
7418 }
7419
7420 gsi_insert_seq_before (&bsi, stmt_list, GSI_SAME_STMT);
7421 if (gimple_code (use->stmt) == GIMPLE_PHI)
7422 {
7423 ass = gimple_build_assign (tgt, comp);
7424 gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
7425
7426 bsi = gsi_for_stmt (use->stmt);
7427 remove_phi_node (&bsi, false);
7428 }
7429 else
7430 {
7431 gimple_assign_set_rhs_from_tree (&bsi, comp);
7432 use->stmt = gsi_stmt (bsi);
7433 }
7434 }
7435
7436 /* Performs a peephole optimization to reorder the iv update statement with
7437 a mem ref to enable instruction combining in later phases. The mem ref uses
7438 the iv value before the update, so the reordering transformation requires
7439 adjustment of the offset. CAND is the selected IV_CAND.
7440
7441 Example:
7442
7443 t = MEM_REF (base, iv1, 8, 16); // base, index, stride, offset
7444 iv2 = iv1 + 1;
7445
7446 if (t < val) (1)
7447 goto L;
7448 goto Head;
7449
7450
7451 directly propagating t over to (1) will introduce overlapping live range
7452 thus increase register pressure. This peephole transform it into:
7453
7454
7455 iv2 = iv1 + 1;
7456 t = MEM_REF (base, iv2, 8, 8);
7457 if (t < val)
7458 goto L;
7459 goto Head;
7460 */
7461
7462 static void
7463 adjust_iv_update_pos (struct iv_cand *cand, struct iv_use *use)
7464 {
7465 tree var_after;
7466 gimple *iv_update, *stmt;
7467 basic_block bb;
7468 gimple_stmt_iterator gsi, gsi_iv;
7469
7470 if (cand->pos != IP_NORMAL)
7471 return;
7472
7473 var_after = cand->var_after;
7474 iv_update = SSA_NAME_DEF_STMT (var_after);
7475
7476 bb = gimple_bb (iv_update);
7477 gsi = gsi_last_nondebug_bb (bb);
7478 stmt = gsi_stmt (gsi);
7479
7480 /* Only handle conditional statement for now. */
7481 if (gimple_code (stmt) != GIMPLE_COND)
7482 return;
7483
7484 gsi_prev_nondebug (&gsi);
7485 stmt = gsi_stmt (gsi);
7486 if (stmt != iv_update)
7487 return;
7488
7489 gsi_prev_nondebug (&gsi);
7490 if (gsi_end_p (gsi))
7491 return;
7492
7493 stmt = gsi_stmt (gsi);
7494 if (gimple_code (stmt) != GIMPLE_ASSIGN)
7495 return;
7496
7497 if (stmt != use->stmt)
7498 return;
7499
7500 if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
7501 return;
7502
7503 if (dump_file && (dump_flags & TDF_DETAILS))
7504 {
7505 fprintf (dump_file, "Reordering \n");
7506 print_gimple_stmt (dump_file, iv_update, 0);
7507 print_gimple_stmt (dump_file, use->stmt, 0);
7508 fprintf (dump_file, "\n");
7509 }
7510
7511 gsi = gsi_for_stmt (use->stmt);
7512 gsi_iv = gsi_for_stmt (iv_update);
7513 gsi_move_before (&gsi_iv, &gsi);
7514
7515 cand->pos = IP_BEFORE_USE;
7516 cand->incremented_at = use->stmt;
7517 }
7518
7519 /* Return the alias pointer type that should be used for a MEM_REF
7520 associated with USE, which has type USE_PTR_ADDRESS. */
7521
7522 static tree
7523 get_alias_ptr_type_for_ptr_address (iv_use *use)
7524 {
7525 gcall *call = as_a <gcall *> (use->stmt);
7526 switch (gimple_call_internal_fn (call))
7527 {
7528 case IFN_MASK_LOAD:
7529 case IFN_MASK_STORE:
7530 case IFN_MASK_LOAD_LANES:
7531 case IFN_MASK_STORE_LANES:
7532 case IFN_MASK_LEN_LOAD_LANES:
7533 case IFN_MASK_LEN_STORE_LANES:
7534 case IFN_LEN_LOAD:
7535 case IFN_LEN_STORE:
7536 case IFN_MASK_LEN_LOAD:
7537 case IFN_MASK_LEN_STORE:
7538 /* The second argument contains the correct alias type. */
7539 gcc_assert (use->op_p == gimple_call_arg_ptr (call, 0));
7540 return TREE_TYPE (gimple_call_arg (call, 1));
7541
7542 default:
7543 gcc_unreachable ();
7544 }
7545 }
7546
7547
7548 /* Rewrites USE (address that is an iv) using candidate CAND. */
7549
7550 static void
7551 rewrite_use_address (struct ivopts_data *data,
7552 struct iv_use *use, struct iv_cand *cand)
7553 {
7554 aff_tree aff;
7555 bool ok;
7556
7557 adjust_iv_update_pos (cand, use);
7558 ok = get_computation_aff (data->current_loop, use->stmt, use, cand, &aff);
7559 gcc_assert (ok);
7560 unshare_aff_combination (&aff);
7561
7562 /* To avoid undefined overflow problems, all IV candidates use unsigned
7563 integer types. The drawback is that this makes it impossible for
7564 create_mem_ref to distinguish an IV that is based on a memory object
7565 from one that represents simply an offset.
7566
7567 To work around this problem, we pass a hint to create_mem_ref that
7568 indicates which variable (if any) in aff is an IV based on a memory
7569 object. Note that we only consider the candidate. If this is not
7570 based on an object, the base of the reference is in some subexpression
7571 of the use -- but these will use pointer types, so they are recognized
7572 by the create_mem_ref heuristics anyway. */
7573 tree iv = var_at_stmt (data->current_loop, cand, use->stmt);
7574 tree base_hint = (cand->iv->base_object) ? iv : NULL_TREE;
7575 gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
7576 tree type = use->mem_type;
7577 tree alias_ptr_type;
7578 if (use->type == USE_PTR_ADDRESS)
7579 alias_ptr_type = get_alias_ptr_type_for_ptr_address (use);
7580 else
7581 {
7582 gcc_assert (type == TREE_TYPE (*use->op_p));
7583 unsigned int align = get_object_alignment (*use->op_p);
7584 if (align != TYPE_ALIGN (type))
7585 type = build_aligned_type (type, align);
7586 alias_ptr_type = reference_alias_ptr_type (*use->op_p);
7587 }
7588 tree ref = create_mem_ref (&bsi, type, &aff, alias_ptr_type,
7589 iv, base_hint, data->speed);
7590
7591 if (use->type == USE_PTR_ADDRESS)
7592 {
7593 ref = fold_build1 (ADDR_EXPR, build_pointer_type (use->mem_type), ref);
7594 ref = fold_convert (get_use_type (use), ref);
7595 ref = force_gimple_operand_gsi (&bsi, ref, true, NULL_TREE,
7596 true, GSI_SAME_STMT);
7597 }
7598 else
7599 {
7600 /* When we end up confused enough and have no suitable base but
7601 stuffed everything to index2 use a LEA for the address and
7602 create a plain MEM_REF to avoid basing a memory reference
7603 on address zero which create_mem_ref_raw does as fallback. */
7604 if (TREE_CODE (ref) == TARGET_MEM_REF
7605 && TMR_INDEX2 (ref) != NULL_TREE
7606 && integer_zerop (TREE_OPERAND (ref, 0)))
7607 {
7608 ref = fold_build1 (ADDR_EXPR, TREE_TYPE (TREE_OPERAND (ref, 0)), ref);
7609 ref = force_gimple_operand_gsi (&bsi, ref, true, NULL_TREE,
7610 true, GSI_SAME_STMT);
7611 ref = build2 (MEM_REF, type, ref, build_zero_cst (alias_ptr_type));
7612 }
7613 copy_ref_info (ref, *use->op_p);
7614 }
7615
7616 *use->op_p = ref;
7617 }
7618
7619 /* Rewrites USE (the condition such that one of the arguments is an iv) using
7620 candidate CAND. */
7621
7622 static void
7623 rewrite_use_compare (struct ivopts_data *data,
7624 struct iv_use *use, struct iv_cand *cand)
7625 {
7626 tree comp, op, bound;
7627 gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
7628 enum tree_code compare;
7629 struct iv_group *group = data->vgroups[use->group_id];
7630 class cost_pair *cp = get_group_iv_cost (data, group, cand);
7631
7632 bound = cp->value;
7633 if (bound)
7634 {
7635 tree var = var_at_stmt (data->current_loop, cand, use->stmt);
7636 tree var_type = TREE_TYPE (var);
7637 gimple_seq stmts;
7638
7639 if (dump_file && (dump_flags & TDF_DETAILS))
7640 {
7641 fprintf (dump_file, "Replacing exit test: ");
7642 print_gimple_stmt (dump_file, use->stmt, 0, TDF_SLIM);
7643 }
7644 compare = cp->comp;
7645 bound = unshare_expr (fold_convert (var_type, bound));
7646 op = force_gimple_operand (bound, &stmts, true, NULL_TREE);
7647 if (stmts)
7648 gsi_insert_seq_on_edge_immediate (
7649 loop_preheader_edge (data->current_loop),
7650 stmts);
7651
7652 gcond *cond_stmt = as_a <gcond *> (use->stmt);
7653 gimple_cond_set_lhs (cond_stmt, var);
7654 gimple_cond_set_code (cond_stmt, compare);
7655 gimple_cond_set_rhs (cond_stmt, op);
7656 return;
7657 }
7658
7659 /* The induction variable elimination failed; just express the original
7660 giv. */
7661 comp = get_computation_at (data->current_loop, use->stmt, use, cand);
7662 gcc_assert (comp != NULL_TREE);
7663 gcc_assert (use->op_p != NULL);
7664 *use->op_p = force_gimple_operand_gsi (&bsi, comp, true,
7665 SSA_NAME_VAR (*use->op_p),
7666 true, GSI_SAME_STMT);
7667 }
7668
7669 /* Rewrite the groups using the selected induction variables. */
7670
7671 static void
7672 rewrite_groups (struct ivopts_data *data)
7673 {
7674 unsigned i, j;
7675
7676 for (i = 0; i < data->vgroups.length (); i++)
7677 {
7678 struct iv_group *group = data->vgroups[i];
7679 struct iv_cand *cand = group->selected;
7680
7681 gcc_assert (cand);
7682
7683 if (group->type == USE_NONLINEAR_EXPR)
7684 {
7685 for (j = 0; j < group->vuses.length (); j++)
7686 {
7687 rewrite_use_nonlinear_expr (data, group->vuses[j], cand);
7688 update_stmt (group->vuses[j]->stmt);
7689 }
7690 }
7691 else if (address_p (group->type))
7692 {
7693 for (j = 0; j < group->vuses.length (); j++)
7694 {
7695 rewrite_use_address (data, group->vuses[j], cand);
7696 update_stmt (group->vuses[j]->stmt);
7697 }
7698 }
7699 else
7700 {
7701 gcc_assert (group->type == USE_COMPARE);
7702
7703 for (j = 0; j < group->vuses.length (); j++)
7704 {
7705 rewrite_use_compare (data, group->vuses[j], cand);
7706 update_stmt (group->vuses[j]->stmt);
7707 }
7708 }
7709 }
7710 }
7711
7712 /* Removes the ivs that are not used after rewriting. */
7713
7714 static void
7715 remove_unused_ivs (struct ivopts_data *data, bitmap toremove)
7716 {
7717 unsigned j;
7718 bitmap_iterator bi;
7719
7720 /* Figure out an order in which to release SSA DEFs so that we don't
7721 release something that we'd have to propagate into a debug stmt
7722 afterwards. */
7723 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
7724 {
7725 struct version_info *info;
7726
7727 info = ver_info (data, j);
7728 if (info->iv
7729 && !integer_zerop (info->iv->step)
7730 && !info->inv_id
7731 && !info->iv->nonlin_use
7732 && !info->preserve_biv)
7733 {
7734 bitmap_set_bit (toremove, SSA_NAME_VERSION (info->iv->ssa_name));
7735
7736 tree def = info->iv->ssa_name;
7737
7738 if (MAY_HAVE_DEBUG_BIND_STMTS && SSA_NAME_DEF_STMT (def))
7739 {
7740 imm_use_iterator imm_iter;
7741 use_operand_p use_p;
7742 gimple *stmt;
7743 int count = 0;
7744
7745 FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
7746 {
7747 if (!gimple_debug_bind_p (stmt))
7748 continue;
7749
7750 /* We just want to determine whether to do nothing
7751 (count == 0), to substitute the computed
7752 expression into a single use of the SSA DEF by
7753 itself (count == 1), or to use a debug temp
7754 because the SSA DEF is used multiple times or as
7755 part of a larger expression (count > 1). */
7756 count++;
7757 if (gimple_debug_bind_get_value (stmt) != def)
7758 count++;
7759
7760 if (count > 1)
7761 break;
7762 }
7763
7764 if (!count)
7765 continue;
7766
7767 struct iv_use dummy_use;
7768 struct iv_cand *best_cand = NULL, *cand;
7769 unsigned i, best_pref = 0, cand_pref;
7770 tree comp = NULL_TREE;
7771
7772 memset (&dummy_use, 0, sizeof (dummy_use));
7773 dummy_use.iv = info->iv;
7774 for (i = 0; i < data->vgroups.length () && i < 64; i++)
7775 {
7776 cand = data->vgroups[i]->selected;
7777 if (cand == best_cand)
7778 continue;
7779 cand_pref = operand_equal_p (cand->iv->step,
7780 info->iv->step, 0)
7781 ? 4 : 0;
7782 cand_pref
7783 += TYPE_MODE (TREE_TYPE (cand->iv->base))
7784 == TYPE_MODE (TREE_TYPE (info->iv->base))
7785 ? 2 : 0;
7786 cand_pref
7787 += TREE_CODE (cand->iv->base) == INTEGER_CST
7788 ? 1 : 0;
7789 if (best_cand == NULL || best_pref < cand_pref)
7790 {
7791 tree this_comp
7792 = get_debug_computation_at (data->current_loop,
7793 SSA_NAME_DEF_STMT (def),
7794 &dummy_use, cand);
7795 if (this_comp)
7796 {
7797 best_cand = cand;
7798 best_pref = cand_pref;
7799 comp = this_comp;
7800 }
7801 }
7802 }
7803
7804 if (!best_cand)
7805 continue;
7806
7807 comp = unshare_expr (comp);
7808 if (count > 1)
7809 {
7810 tree vexpr = build_debug_expr_decl (TREE_TYPE (comp));
7811 /* FIXME: Is setting the mode really necessary? */
7812 if (SSA_NAME_VAR (def))
7813 SET_DECL_MODE (vexpr, DECL_MODE (SSA_NAME_VAR (def)));
7814 else
7815 SET_DECL_MODE (vexpr, TYPE_MODE (TREE_TYPE (vexpr)));
7816 gdebug *def_temp
7817 = gimple_build_debug_bind (vexpr, comp, NULL);
7818 gimple_stmt_iterator gsi;
7819
7820 if (gimple_code (SSA_NAME_DEF_STMT (def)) == GIMPLE_PHI)
7821 gsi = gsi_after_labels (gimple_bb
7822 (SSA_NAME_DEF_STMT (def)));
7823 else
7824 gsi = gsi_for_stmt (SSA_NAME_DEF_STMT (def));
7825
7826 gsi_insert_before (&gsi, def_temp, GSI_SAME_STMT);
7827 comp = vexpr;
7828 }
7829
7830 FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
7831 {
7832 if (!gimple_debug_bind_p (stmt))
7833 continue;
7834
7835 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
7836 SET_USE (use_p, comp);
7837
7838 update_stmt (stmt);
7839 }
7840 }
7841 }
7842 }
7843 }
7844
7845 /* Frees memory occupied by class tree_niter_desc in *VALUE. Callback
7846 for hash_map::traverse. */
7847
7848 bool
7849 free_tree_niter_desc (edge const &, tree_niter_desc *const &value, void *)
7850 {
7851 if (value)
7852 {
7853 value->~tree_niter_desc ();
7854 free (value);
7855 }
7856 return true;
7857 }
7858
7859 /* Frees data allocated by the optimization of a single loop. */
7860
7861 static void
7862 free_loop_data (struct ivopts_data *data)
7863 {
7864 unsigned i, j;
7865 bitmap_iterator bi;
7866 tree obj;
7867
7868 if (data->niters)
7869 {
7870 data->niters->traverse<void *, free_tree_niter_desc> (NULL);
7871 delete data->niters;
7872 data->niters = NULL;
7873 }
7874
7875 EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
7876 {
7877 struct version_info *info;
7878
7879 info = ver_info (data, i);
7880 info->iv = NULL;
7881 info->has_nonlin_use = false;
7882 info->preserve_biv = false;
7883 info->inv_id = 0;
7884 }
7885 bitmap_clear (data->relevant);
7886 bitmap_clear (data->important_candidates);
7887
7888 for (i = 0; i < data->vgroups.length (); i++)
7889 {
7890 struct iv_group *group = data->vgroups[i];
7891
7892 for (j = 0; j < group->vuses.length (); j++)
7893 free (group->vuses[j]);
7894 group->vuses.release ();
7895
7896 BITMAP_FREE (group->related_cands);
7897 for (j = 0; j < group->n_map_members; j++)
7898 {
7899 if (group->cost_map[j].inv_vars)
7900 BITMAP_FREE (group->cost_map[j].inv_vars);
7901 if (group->cost_map[j].inv_exprs)
7902 BITMAP_FREE (group->cost_map[j].inv_exprs);
7903 }
7904
7905 free (group->cost_map);
7906 free (group);
7907 }
7908 data->vgroups.truncate (0);
7909
7910 for (i = 0; i < data->vcands.length (); i++)
7911 {
7912 struct iv_cand *cand = data->vcands[i];
7913
7914 if (cand->inv_vars)
7915 BITMAP_FREE (cand->inv_vars);
7916 if (cand->inv_exprs)
7917 BITMAP_FREE (cand->inv_exprs);
7918 free (cand);
7919 }
7920 data->vcands.truncate (0);
7921
7922 if (data->version_info_size < num_ssa_names)
7923 {
7924 data->version_info_size = 2 * num_ssa_names;
7925 free (data->version_info);
7926 data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
7927 }
7928
7929 data->max_inv_var_id = 0;
7930 data->max_inv_expr_id = 0;
7931
7932 FOR_EACH_VEC_ELT (decl_rtl_to_reset, i, obj)
7933 SET_DECL_RTL (obj, NULL_RTX);
7934
7935 decl_rtl_to_reset.truncate (0);
7936
7937 data->inv_expr_tab->empty ();
7938
7939 data->iv_common_cand_tab->empty ();
7940 data->iv_common_cands.truncate (0);
7941 }
7942
7943 /* Finalizes data structures used by the iv optimization pass. LOOPS is the
7944 loop tree. */
7945
7946 static void
7947 tree_ssa_iv_optimize_finalize (struct ivopts_data *data)
7948 {
7949 free_loop_data (data);
7950 free (data->version_info);
7951 BITMAP_FREE (data->relevant);
7952 BITMAP_FREE (data->important_candidates);
7953
7954 decl_rtl_to_reset.release ();
7955 data->vgroups.release ();
7956 data->vcands.release ();
7957 delete data->inv_expr_tab;
7958 data->inv_expr_tab = NULL;
7959 free_affine_expand_cache (&data->name_expansion_cache);
7960 if (data->base_object_map)
7961 delete data->base_object_map;
7962 delete data->iv_common_cand_tab;
7963 data->iv_common_cand_tab = NULL;
7964 data->iv_common_cands.release ();
7965 obstack_free (&data->iv_obstack, NULL);
7966 }
7967
7968 /* Returns true if the loop body BODY includes any function calls. */
7969
7970 static bool
7971 loop_body_includes_call (basic_block *body, unsigned num_nodes)
7972 {
7973 gimple_stmt_iterator gsi;
7974 unsigned i;
7975
7976 for (i = 0; i < num_nodes; i++)
7977 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
7978 {
7979 gimple *stmt = gsi_stmt (gsi);
7980 if (is_gimple_call (stmt)
7981 && !gimple_call_internal_p (stmt)
7982 && !is_inexpensive_builtin (gimple_call_fndecl (stmt)))
7983 return true;
7984 }
7985 return false;
7986 }
7987
7988 /* Determine cost scaling factor for basic blocks in loop. */
7989 #define COST_SCALING_FACTOR_BOUND (20)
7990
7991 static void
7992 determine_scaling_factor (struct ivopts_data *data, basic_block *body)
7993 {
7994 int lfreq = data->current_loop->header->count.to_frequency (cfun);
7995 if (!data->speed || lfreq <= 0)
7996 return;
7997
7998 int max_freq = lfreq;
7999 for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
8000 {
8001 body[i]->aux = (void *)(intptr_t) 1;
8002 if (max_freq < body[i]->count.to_frequency (cfun))
8003 max_freq = body[i]->count.to_frequency (cfun);
8004 }
8005 if (max_freq > lfreq)
8006 {
8007 int divisor, factor;
8008 /* Check if scaling factor itself needs to be scaled by the bound. This
8009 is to avoid overflow when scaling cost according to profile info. */
8010 if (max_freq / lfreq > COST_SCALING_FACTOR_BOUND)
8011 {
8012 divisor = max_freq;
8013 factor = COST_SCALING_FACTOR_BOUND;
8014 }
8015 else
8016 {
8017 divisor = lfreq;
8018 factor = 1;
8019 }
8020 for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
8021 {
8022 int bfreq = body[i]->count.to_frequency (cfun);
8023 if (bfreq <= lfreq)
8024 continue;
8025
8026 body[i]->aux = (void*)(intptr_t) (factor * bfreq / divisor);
8027 }
8028 }
8029 }
8030
8031 /* Find doloop comparison use and set its doloop_p on if found. */
8032
8033 static bool
8034 find_doloop_use (struct ivopts_data *data)
8035 {
8036 struct loop *loop = data->current_loop;
8037
8038 for (unsigned i = 0; i < data->vgroups.length (); i++)
8039 {
8040 struct iv_group *group = data->vgroups[i];
8041 if (group->type == USE_COMPARE)
8042 {
8043 gcc_assert (group->vuses.length () == 1);
8044 struct iv_use *use = group->vuses[0];
8045 gimple *stmt = use->stmt;
8046 if (gimple_code (stmt) == GIMPLE_COND)
8047 {
8048 basic_block bb = gimple_bb (stmt);
8049 edge true_edge, false_edge;
8050 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
8051 /* This comparison is used for loop latch. Require latch is empty
8052 for now. */
8053 if ((loop->latch == true_edge->dest
8054 || loop->latch == false_edge->dest)
8055 && empty_block_p (loop->latch))
8056 {
8057 group->doloop_p = true;
8058 if (dump_file && (dump_flags & TDF_DETAILS))
8059 {
8060 fprintf (dump_file, "Doloop cmp iv use: ");
8061 print_gimple_stmt (dump_file, stmt, TDF_DETAILS);
8062 }
8063 return true;
8064 }
8065 }
8066 }
8067 }
8068
8069 return false;
8070 }
8071
8072 /* For the targets which support doloop, to predict whether later RTL doloop
8073 transformation will perform on this loop, further detect the doloop use and
8074 mark the flag doloop_use_p if predicted. */
8075
8076 void
8077 analyze_and_mark_doloop_use (struct ivopts_data *data)
8078 {
8079 data->doloop_use_p = false;
8080
8081 if (!flag_branch_on_count_reg)
8082 return;
8083
8084 if (data->current_loop->unroll == USHRT_MAX)
8085 return;
8086
8087 if (!generic_predict_doloop_p (data))
8088 return;
8089
8090 if (find_doloop_use (data))
8091 {
8092 data->doloop_use_p = true;
8093 if (dump_file && (dump_flags & TDF_DETAILS))
8094 {
8095 struct loop *loop = data->current_loop;
8096 fprintf (dump_file,
8097 "Predict loop %d can perform"
8098 " doloop optimization later.\n",
8099 loop->num);
8100 flow_loop_dump (loop, dump_file, NULL, 1);
8101 }
8102 }
8103 }
8104
8105 /* Optimizes the LOOP. Returns true if anything changed. */
8106
8107 static bool
8108 tree_ssa_iv_optimize_loop (struct ivopts_data *data, class loop *loop,
8109 bitmap toremove)
8110 {
8111 bool changed = false;
8112 class iv_ca *iv_ca;
8113 edge exit = single_dom_exit (loop);
8114 basic_block *body;
8115
8116 gcc_assert (!data->niters);
8117 data->current_loop = loop;
8118 data->loop_loc = find_loop_location (loop).get_location_t ();
8119 data->speed = optimize_loop_for_speed_p (loop);
8120
8121 if (dump_file && (dump_flags & TDF_DETAILS))
8122 {
8123 fprintf (dump_file, "Processing loop %d", loop->num);
8124 if (data->loop_loc != UNKNOWN_LOCATION)
8125 fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
8126 LOCATION_LINE (data->loop_loc));
8127 fprintf (dump_file, "\n");
8128
8129 if (exit)
8130 {
8131 fprintf (dump_file, " single exit %d -> %d, exit condition ",
8132 exit->src->index, exit->dest->index);
8133 print_gimple_stmt (dump_file, *gsi_last_bb (exit->src),
8134 0, TDF_SLIM);
8135 fprintf (dump_file, "\n");
8136 }
8137
8138 fprintf (dump_file, "\n");
8139 }
8140
8141 body = get_loop_body (loop);
8142 data->body_includes_call = loop_body_includes_call (body, loop->num_nodes);
8143 renumber_gimple_stmt_uids_in_blocks (body, loop->num_nodes);
8144
8145 data->loop_single_exit_p
8146 = exit != NULL && loop_only_exit_p (loop, body, exit);
8147
8148 /* For each ssa name determines whether it behaves as an induction variable
8149 in some loop. */
8150 if (!find_induction_variables (data, body))
8151 goto finish;
8152
8153 /* Finds interesting uses (item 1). */
8154 find_interesting_uses (data, body);
8155 if (data->vgroups.length () > MAX_CONSIDERED_GROUPS)
8156 goto finish;
8157
8158 /* Determine cost scaling factor for basic blocks in loop. */
8159 determine_scaling_factor (data, body);
8160
8161 /* Analyze doloop possibility and mark the doloop use if predicted. */
8162 analyze_and_mark_doloop_use (data);
8163
8164 /* Finds candidates for the induction variables (item 2). */
8165 find_iv_candidates (data);
8166
8167 /* Calculates the costs (item 3, part 1). */
8168 determine_iv_costs (data);
8169 determine_group_iv_costs (data);
8170 determine_set_costs (data);
8171
8172 /* Find the optimal set of induction variables (item 3, part 2). */
8173 iv_ca = find_optimal_iv_set (data);
8174 /* Cleanup basic block aux field. */
8175 for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
8176 body[i]->aux = NULL;
8177 if (!iv_ca)
8178 goto finish;
8179 changed = true;
8180
8181 /* Create the new induction variables (item 4, part 1). */
8182 create_new_ivs (data, iv_ca);
8183 iv_ca_free (&iv_ca);
8184
8185 /* Rewrite the uses (item 4, part 2). */
8186 rewrite_groups (data);
8187
8188 /* Remove the ivs that are unused after rewriting. */
8189 remove_unused_ivs (data, toremove);
8190
8191 finish:
8192 free (body);
8193 free_loop_data (data);
8194
8195 return changed;
8196 }
8197
8198 /* Main entry point. Optimizes induction variables in loops. */
8199
8200 void
8201 tree_ssa_iv_optimize (void)
8202 {
8203 struct ivopts_data data;
8204 auto_bitmap toremove;
8205
8206 tree_ssa_iv_optimize_init (&data);
8207 mark_ssa_maybe_undefs ();
8208
8209 /* Optimize the loops starting with the innermost ones. */
8210 for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
8211 {
8212 if (!dbg_cnt (ivopts_loop))
8213 continue;
8214
8215 if (dump_file && (dump_flags & TDF_DETAILS))
8216 flow_loop_dump (loop, dump_file, NULL, 1);
8217
8218 tree_ssa_iv_optimize_loop (&data, loop, toremove);
8219 }
8220
8221 /* Remove eliminated IV defs. */
8222 release_defs_bitset (toremove);
8223
8224 /* We have changed the structure of induction variables; it might happen
8225 that definitions in the scev database refer to some of them that were
8226 eliminated. */
8227 scev_reset_htab ();
8228 /* Likewise niter and control-IV information. */
8229 free_numbers_of_iterations_estimates (cfun);
8230
8231 tree_ssa_iv_optimize_finalize (&data);
8232 }
8233
8234 #include "gt-tree-ssa-loop-ivopts.h"