OSDN Git Service

a1fdfa46254c0806da7eb505271c22064341bd9c
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-ivopts.c
1 /* Induction variable optimizations.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 /* This pass tries to find the optimal set of induction variables for the loop.
22    It optimizes just the basic linear induction variables (although adding
23    support for other types should not be too hard).  It includes the
24    optimizations commonly known as strength reduction, induction variable
25    coalescing and induction variable elimination.  It does it in the
26    following steps:
27
28    1) The interesting uses of induction variables are found.  This includes
29
30       -- uses of induction variables in non-linear expressions
31       -- addresses of arrays
32       -- comparisons of induction variables
33
34    2) Candidates for the induction variables are found.  This includes
35
36       -- old induction variables
37       -- the variables defined by expressions derived from the "interesting
38          uses" above
39
40    3) The optimal (w.r. to a cost function) set of variables is chosen.  The
41       cost function assigns a cost to sets of induction variables and consists
42       of three parts:
43
44       -- The use costs.  Each of the interesting uses chooses the best induction
45          variable in the set and adds its cost to the sum.  The cost reflects
46          the time spent on modifying the induction variables value to be usable
47          for the given purpose (adding base and offset for arrays, etc.).
48       -- The variable costs.  Each of the variables has a cost assigned that
49          reflects the costs associated with incrementing the value of the
50          variable.  The original variables are somewhat preferred.
51       -- The set cost.  Depending on the size of the set, extra cost may be
52          added to reflect register pressure.
53
54       All the costs are defined in a machine-specific way, using the target
55       hooks and machine descriptions to determine them.
56
57    4) The trees are transformed to use the new variables, the dead code is
58       removed.
59
60    All of this is done loop by loop.  Doing it globally is theoretically
61    possible, it might give a better performance and it might enable us
62    to decide costs more precisely, but getting all the interactions right
63    would be complicated.  */
64
65 #include "config.h"
66 #include "system.h"
67 #include "coretypes.h"
68 #include "tm.h"
69 #include "tree.h"
70 #include "rtl.h"
71 #include "tm_p.h"
72 #include "hard-reg-set.h"
73 #include "basic-block.h"
74 #include "output.h"
75 #include "diagnostic.h"
76 #include "tree-flow.h"
77 #include "tree-dump.h"
78 #include "timevar.h"
79 #include "cfgloop.h"
80 #include "expr.h"
81 #include "tree-pass.h"
82 #include "ggc.h"
83 #include "insn-config.h"
84 #include "recog.h"
85 #include "pointer-set.h"
86 #include "hashtab.h"
87 #include "tree-chrec.h"
88 #include "tree-scalar-evolution.h"
89 #include "cfgloop.h"
90 #include "params.h"
91 #include "langhooks.h"
92 #include "tree-affine.h"
93 #include "target.h"
94
95 /* The infinite cost.  */
96 #define INFTY 10000000
97
98 /* The expected number of loop iterations.  TODO -- use profiling instead of
99    this.  */
100 #define AVG_LOOP_NITER(LOOP) 5
101
102
103 /* Representation of the induction variable.  */
104 struct iv
105 {
106   tree base;            /* Initial value of the iv.  */
107   tree base_object;     /* A memory object to that the induction variable points.  */
108   tree step;            /* Step of the iv (constant only).  */
109   tree ssa_name;        /* The ssa name with the value.  */
110   bool biv_p;           /* Is it a biv?  */
111   bool have_use_for;    /* Do we already have a use for it?  */
112   unsigned use_id;      /* The identifier in the use if it is the case.  */
113 };
114
115 /* Per-ssa version information (induction variable descriptions, etc.).  */
116 struct version_info
117 {
118   tree name;            /* The ssa name.  */
119   struct iv *iv;        /* Induction variable description.  */
120   bool has_nonlin_use;  /* For a loop-level invariant, whether it is used in
121                            an expression that is not an induction variable.  */
122   bool preserve_biv;    /* For the original biv, whether to preserve it.  */
123   unsigned inv_id;      /* Id of an invariant.  */
124 };
125
126 /* Types of uses.  */
127 enum use_type
128 {
129   USE_NONLINEAR_EXPR,   /* Use in a nonlinear expression.  */
130   USE_ADDRESS,          /* Use in an address.  */
131   USE_COMPARE           /* Use is a compare.  */
132 };
133
134 /* Cost of a computation.  */
135 typedef struct
136 {
137   int cost;             /* The runtime cost.  */
138   unsigned complexity;  /* The estimate of the complexity of the code for
139                            the computation (in no concrete units --
140                            complexity field should be larger for more
141                            complex expressions and addressing modes).  */
142 } comp_cost;
143
144 static const comp_cost zero_cost = {0, 0};
145 static const comp_cost infinite_cost = {INFTY, INFTY};
146
147 /* The candidate - cost pair.  */
148 struct cost_pair
149 {
150   struct iv_cand *cand; /* The candidate.  */
151   comp_cost cost;       /* The cost.  */
152   bitmap depends_on;    /* The list of invariants that have to be
153                            preserved.  */
154   tree value;           /* For final value elimination, the expression for
155                            the final value of the iv.  For iv elimination,
156                            the new bound to compare with.  */
157 };
158
159 /* Use.  */
160 struct iv_use
161 {
162   unsigned id;          /* The id of the use.  */
163   enum use_type type;   /* Type of the use.  */
164   struct iv *iv;        /* The induction variable it is based on.  */
165   gimple stmt;          /* Statement in that it occurs.  */
166   tree *op_p;           /* The place where it occurs.  */
167   bitmap related_cands; /* The set of "related" iv candidates, plus the common
168                            important ones.  */
169
170   unsigned n_map_members; /* Number of candidates in the cost_map list.  */
171   struct cost_pair *cost_map;
172                         /* The costs wrto the iv candidates.  */
173
174   struct iv_cand *selected;
175                         /* The selected candidate.  */
176 };
177
178 /* The position where the iv is computed.  */
179 enum iv_position
180 {
181   IP_NORMAL,            /* At the end, just before the exit condition.  */
182   IP_END,               /* At the end of the latch block.  */
183   IP_BEFORE_USE,        /* Immediately before a specific use.  */
184   IP_AFTER_USE,         /* Immediately after a specific use.  */
185   IP_ORIGINAL           /* The original biv.  */
186 };
187
188 /* The induction variable candidate.  */
189 struct iv_cand
190 {
191   unsigned id;          /* The number of the candidate.  */
192   bool important;       /* Whether this is an "important" candidate, i.e. such
193                            that it should be considered by all uses.  */
194   ENUM_BITFIELD(iv_position) pos : 8;   /* Where it is computed.  */
195   gimple incremented_at;/* For original biv, the statement where it is
196                            incremented.  */
197   tree var_before;      /* The variable used for it before increment.  */
198   tree var_after;       /* The variable used for it after increment.  */
199   struct iv *iv;        /* The value of the candidate.  NULL for
200                            "pseudocandidate" used to indicate the possibility
201                            to replace the final value of an iv by direct
202                            computation of the value.  */
203   unsigned cost;        /* Cost of the candidate.  */
204   unsigned cost_step;   /* Cost of the candidate's increment operation.  */
205   struct iv_use *ainc_use; /* For IP_{BEFORE,AFTER}_USE candidates, the place
206                               where it is incremented.  */
207   bitmap depends_on;    /* The list of invariants that are used in step of the
208                            biv.  */
209 };
210
211 /* The data used by the induction variable optimizations.  */
212
213 typedef struct iv_use *iv_use_p;
214 DEF_VEC_P(iv_use_p);
215 DEF_VEC_ALLOC_P(iv_use_p,heap);
216
217 typedef struct iv_cand *iv_cand_p;
218 DEF_VEC_P(iv_cand_p);
219 DEF_VEC_ALLOC_P(iv_cand_p,heap);
220
221 struct ivopts_data
222 {
223   /* The currently optimized loop.  */
224   struct loop *current_loop;
225
226   /* Numbers of iterations for all exits of the current loop.  */
227   struct pointer_map_t *niters;
228
229   /* Number of registers used in it.  */
230   unsigned regs_used;
231
232   /* The size of version_info array allocated.  */
233   unsigned version_info_size;
234
235   /* The array of information for the ssa names.  */
236   struct version_info *version_info;
237
238   /* The bitmap of indices in version_info whose value was changed.  */
239   bitmap relevant;
240
241   /* The uses of induction variables.  */
242   VEC(iv_use_p,heap) *iv_uses;
243
244   /* The candidates.  */
245   VEC(iv_cand_p,heap) *iv_candidates;
246
247   /* A bitmap of important candidates.  */
248   bitmap important_candidates;
249
250   /* The maximum invariant id.  */
251   unsigned max_inv_id;
252
253   /* Whether to consider just related and important candidates when replacing a
254      use.  */
255   bool consider_all_candidates;
256
257   /* Are we optimizing for speed?  */
258   bool speed;
259 };
260
261 /* An assignment of iv candidates to uses.  */
262
263 struct iv_ca
264 {
265   /* The number of uses covered by the assignment.  */
266   unsigned upto;
267
268   /* Number of uses that cannot be expressed by the candidates in the set.  */
269   unsigned bad_uses;
270
271   /* Candidate assigned to a use, together with the related costs.  */
272   struct cost_pair **cand_for_use;
273
274   /* Number of times each candidate is used.  */
275   unsigned *n_cand_uses;
276
277   /* The candidates used.  */
278   bitmap cands;
279
280   /* The number of candidates in the set.  */
281   unsigned n_cands;
282
283   /* Total number of registers needed.  */
284   unsigned n_regs;
285
286   /* Total cost of expressing uses.  */
287   comp_cost cand_use_cost;
288
289   /* Total cost of candidates.  */
290   unsigned cand_cost;
291
292   /* Number of times each invariant is used.  */
293   unsigned *n_invariant_uses;
294
295   /* Total cost of the assignment.  */
296   comp_cost cost;
297 };
298
299 /* Difference of two iv candidate assignments.  */
300
301 struct iv_ca_delta
302 {
303   /* Changed use.  */
304   struct iv_use *use;
305
306   /* An old assignment (for rollback purposes).  */
307   struct cost_pair *old_cp;
308
309   /* A new assignment.  */
310   struct cost_pair *new_cp;
311
312   /* Next change in the list.  */
313   struct iv_ca_delta *next_change;
314 };
315
316 /* Bound on number of candidates below that all candidates are considered.  */
317
318 #define CONSIDER_ALL_CANDIDATES_BOUND \
319   ((unsigned) PARAM_VALUE (PARAM_IV_CONSIDER_ALL_CANDIDATES_BOUND))
320
321 /* If there are more iv occurrences, we just give up (it is quite unlikely that
322    optimizing such a loop would help, and it would take ages).  */
323
324 #define MAX_CONSIDERED_USES \
325   ((unsigned) PARAM_VALUE (PARAM_IV_MAX_CONSIDERED_USES))
326
327 /* If there are at most this number of ivs in the set, try removing unnecessary
328    ivs from the set always.  */
329
330 #define ALWAYS_PRUNE_CAND_SET_BOUND \
331   ((unsigned) PARAM_VALUE (PARAM_IV_ALWAYS_PRUNE_CAND_SET_BOUND))
332
333 /* The list of trees for that the decl_rtl field must be reset is stored
334    here.  */
335
336 static VEC(tree,heap) *decl_rtl_to_reset;
337
338 /* Number of uses recorded in DATA.  */
339
340 static inline unsigned
341 n_iv_uses (struct ivopts_data *data)
342 {
343   return VEC_length (iv_use_p, data->iv_uses);
344 }
345
346 /* Ith use recorded in DATA.  */
347
348 static inline struct iv_use *
349 iv_use (struct ivopts_data *data, unsigned i)
350 {
351   return VEC_index (iv_use_p, data->iv_uses, i);
352 }
353
354 /* Number of candidates recorded in DATA.  */
355
356 static inline unsigned
357 n_iv_cands (struct ivopts_data *data)
358 {
359   return VEC_length (iv_cand_p, data->iv_candidates);
360 }
361
362 /* Ith candidate recorded in DATA.  */
363
364 static inline struct iv_cand *
365 iv_cand (struct ivopts_data *data, unsigned i)
366 {
367   return VEC_index (iv_cand_p, data->iv_candidates, i);
368 }
369
370 /* The single loop exit if it dominates the latch, NULL otherwise.  */
371
372 edge
373 single_dom_exit (struct loop *loop)
374 {
375   edge exit = single_exit (loop);
376
377   if (!exit)
378     return NULL;
379
380   if (!just_once_each_iteration_p (loop, exit->src))
381     return NULL;
382
383   return exit;
384 }
385
386 /* Dumps information about the induction variable IV to FILE.  */
387
388 extern void dump_iv (FILE *, struct iv *);
389 void
390 dump_iv (FILE *file, struct iv *iv)
391 {
392   if (iv->ssa_name)
393     {
394       fprintf (file, "ssa name ");
395       print_generic_expr (file, iv->ssa_name, TDF_SLIM);
396       fprintf (file, "\n");
397     }
398
399   fprintf (file, "  type ");
400   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
401   fprintf (file, "\n");
402
403   if (iv->step)
404     {
405       fprintf (file, "  base ");
406       print_generic_expr (file, iv->base, TDF_SLIM);
407       fprintf (file, "\n");
408
409       fprintf (file, "  step ");
410       print_generic_expr (file, iv->step, TDF_SLIM);
411       fprintf (file, "\n");
412     }
413   else
414     {
415       fprintf (file, "  invariant ");
416       print_generic_expr (file, iv->base, TDF_SLIM);
417       fprintf (file, "\n");
418     }
419
420   if (iv->base_object)
421     {
422       fprintf (file, "  base object ");
423       print_generic_expr (file, iv->base_object, TDF_SLIM);
424       fprintf (file, "\n");
425     }
426
427   if (iv->biv_p)
428     fprintf (file, "  is a biv\n");
429 }
430
431 /* Dumps information about the USE to FILE.  */
432
433 extern void dump_use (FILE *, struct iv_use *);
434 void
435 dump_use (FILE *file, struct iv_use *use)
436 {
437   fprintf (file, "use %d\n", use->id);
438
439   switch (use->type)
440     {
441     case USE_NONLINEAR_EXPR:
442       fprintf (file, "  generic\n");
443       break;
444
445     case USE_ADDRESS:
446       fprintf (file, "  address\n");
447       break;
448
449     case USE_COMPARE:
450       fprintf (file, "  compare\n");
451       break;
452
453     default:
454       gcc_unreachable ();
455     }
456
457   fprintf (file, "  in statement ");
458   print_gimple_stmt (file, use->stmt, 0, 0);
459   fprintf (file, "\n");
460
461   fprintf (file, "  at position ");
462   if (use->op_p)
463     print_generic_expr (file, *use->op_p, TDF_SLIM);
464   fprintf (file, "\n");
465
466   dump_iv (file, use->iv);
467
468   if (use->related_cands)
469     {
470       fprintf (file, "  related candidates ");
471       dump_bitmap (file, use->related_cands);
472     }
473 }
474
475 /* Dumps information about the uses to FILE.  */
476
477 extern void dump_uses (FILE *, struct ivopts_data *);
478 void
479 dump_uses (FILE *file, struct ivopts_data *data)
480 {
481   unsigned i;
482   struct iv_use *use;
483
484   for (i = 0; i < n_iv_uses (data); i++)
485     {
486       use = iv_use (data, i);
487
488       dump_use (file, use);
489       fprintf (file, "\n");
490     }
491 }
492
493 /* Dumps information about induction variable candidate CAND to FILE.  */
494
495 extern void dump_cand (FILE *, struct iv_cand *);
496 void
497 dump_cand (FILE *file, struct iv_cand *cand)
498 {
499   struct iv *iv = cand->iv;
500
501   fprintf (file, "candidate %d%s\n",
502            cand->id, cand->important ? " (important)" : "");
503
504   if (cand->depends_on)
505     {
506       fprintf (file, "  depends on ");
507       dump_bitmap (file, cand->depends_on);
508     }
509
510   if (!iv)
511     {
512       fprintf (file, "  final value replacement\n");
513       return;
514     }
515
516   switch (cand->pos)
517     {
518     case IP_NORMAL:
519       fprintf (file, "  incremented before exit test\n");
520       break;
521
522     case IP_BEFORE_USE:
523       fprintf (file, "  incremented before use %d\n", cand->ainc_use->id);
524       break;
525
526     case IP_AFTER_USE:
527       fprintf (file, "  incremented after use %d\n", cand->ainc_use->id);
528       break;
529
530     case IP_END:
531       fprintf (file, "  incremented at end\n");
532       break;
533
534     case IP_ORIGINAL:
535       fprintf (file, "  original biv\n");
536       break;
537     }
538
539   dump_iv (file, iv);
540 }
541
542 /* Returns the info for ssa version VER.  */
543
544 static inline struct version_info *
545 ver_info (struct ivopts_data *data, unsigned ver)
546 {
547   return data->version_info + ver;
548 }
549
550 /* Returns the info for ssa name NAME.  */
551
552 static inline struct version_info *
553 name_info (struct ivopts_data *data, tree name)
554 {
555   return ver_info (data, SSA_NAME_VERSION (name));
556 }
557
558 /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
559    emitted in LOOP.  */
560
561 static bool
562 stmt_after_ip_normal_pos (struct loop *loop, gimple stmt)
563 {
564   basic_block bb = ip_normal_pos (loop), sbb = gimple_bb (stmt);
565
566   gcc_assert (bb);
567
568   if (sbb == loop->latch)
569     return true;
570
571   if (sbb != bb)
572     return false;
573
574   return stmt == last_stmt (bb);
575 }
576
577 /* Returns true if STMT if after the place where the original induction
578    variable CAND is incremented.  If TRUE_IF_EQUAL is set, we return true
579    if the positions are identical.  */
580
581 static bool
582 stmt_after_inc_pos (struct iv_cand *cand, gimple stmt, bool true_if_equal)
583 {
584   basic_block cand_bb = gimple_bb (cand->incremented_at);
585   basic_block stmt_bb = gimple_bb (stmt);
586
587   if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
588     return false;
589
590   if (stmt_bb != cand_bb)
591     return true;
592
593   if (true_if_equal
594       && gimple_uid (stmt) == gimple_uid (cand->incremented_at))
595     return true;
596   return gimple_uid (stmt) > gimple_uid (cand->incremented_at);
597 }
598
599 /* Returns true if STMT if after the place where the induction variable
600    CAND is incremented in LOOP.  */
601
602 static bool
603 stmt_after_increment (struct loop *loop, struct iv_cand *cand, gimple stmt)
604 {
605   switch (cand->pos)
606     {
607     case IP_END:
608       return false;
609
610     case IP_NORMAL:
611       return stmt_after_ip_normal_pos (loop, stmt);
612
613     case IP_ORIGINAL:
614     case IP_AFTER_USE:
615       return stmt_after_inc_pos (cand, stmt, false);
616
617     case IP_BEFORE_USE:
618       return stmt_after_inc_pos (cand, stmt, true);
619
620     default:
621       gcc_unreachable ();
622     }
623 }
624
625 /* Returns true if EXP is a ssa name that occurs in an abnormal phi node.  */
626
627 static bool
628 abnormal_ssa_name_p (tree exp)
629 {
630   if (!exp)
631     return false;
632
633   if (TREE_CODE (exp) != SSA_NAME)
634     return false;
635
636   return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp) != 0;
637 }
638
639 /* Returns false if BASE or INDEX contains a ssa name that occurs in an
640    abnormal phi node.  Callback for for_each_index.  */
641
642 static bool
643 idx_contains_abnormal_ssa_name_p (tree base, tree *index,
644                                   void *data ATTRIBUTE_UNUSED)
645 {
646   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
647     {
648       if (abnormal_ssa_name_p (TREE_OPERAND (base, 2)))
649         return false;
650       if (abnormal_ssa_name_p (TREE_OPERAND (base, 3)))
651         return false;
652     }
653
654   return !abnormal_ssa_name_p (*index);
655 }
656
657 /* Returns true if EXPR contains a ssa name that occurs in an
658    abnormal phi node.  */
659
660 bool
661 contains_abnormal_ssa_name_p (tree expr)
662 {
663   enum tree_code code;
664   enum tree_code_class codeclass;
665
666   if (!expr)
667     return false;
668
669   code = TREE_CODE (expr);
670   codeclass = TREE_CODE_CLASS (code);
671
672   if (code == SSA_NAME)
673     return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (expr) != 0;
674
675   if (code == INTEGER_CST
676       || is_gimple_min_invariant (expr))
677     return false;
678
679   if (code == ADDR_EXPR)
680     return !for_each_index (&TREE_OPERAND (expr, 0),
681                             idx_contains_abnormal_ssa_name_p,
682                             NULL);
683
684   switch (codeclass)
685     {
686     case tcc_binary:
687     case tcc_comparison:
688       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1)))
689         return true;
690
691       /* Fallthru.  */
692     case tcc_unary:
693       if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0)))
694         return true;
695
696       break;
697
698     default:
699       gcc_unreachable ();
700     }
701
702   return false;
703 }
704
705 /*  Returns tree describing number of iterations determined from
706     EXIT of DATA->current_loop, or NULL if something goes wrong.  */
707
708 static tree
709 niter_for_exit (struct ivopts_data *data, edge exit)
710 {
711   struct tree_niter_desc desc;
712   tree niter;
713   void **slot;
714
715   if (!data->niters)
716     {
717       data->niters = pointer_map_create ();
718       slot = NULL;
719     }
720   else
721     slot = pointer_map_contains (data->niters, exit);
722
723   if (!slot)
724     {
725       /* Try to determine number of iterations.  We must know it
726          unconditionally (i.e., without possibility of # of iterations
727          being zero).  Also, we cannot safely work with ssa names that
728          appear in phi nodes on abnormal edges, so that we do not create
729          overlapping life ranges for them (PR 27283).  */
730       if (number_of_iterations_exit (data->current_loop,
731                                      exit, &desc, true)
732           && integer_zerop (desc.may_be_zero)
733           && !contains_abnormal_ssa_name_p (desc.niter))
734         niter = desc.niter;
735       else
736         niter = NULL_TREE;
737
738       *pointer_map_insert (data->niters, exit) = niter;
739     }
740   else
741     niter = (tree) *slot;
742
743   return niter;
744 }
745
746 /* Returns tree describing number of iterations determined from
747    single dominating exit of DATA->current_loop, or NULL if something
748    goes wrong.  */
749
750 static tree
751 niter_for_single_dom_exit (struct ivopts_data *data)
752 {
753   edge exit = single_dom_exit (data->current_loop);
754
755   if (!exit)
756     return NULL;
757
758   return niter_for_exit (data, exit);
759 }
760
761 /* Initializes data structures used by the iv optimization pass, stored
762    in DATA.  */
763
764 static void
765 tree_ssa_iv_optimize_init (struct ivopts_data *data)
766 {
767   data->version_info_size = 2 * num_ssa_names;
768   data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
769   data->relevant = BITMAP_ALLOC (NULL);
770   data->important_candidates = BITMAP_ALLOC (NULL);
771   data->max_inv_id = 0;
772   data->niters = NULL;
773   data->iv_uses = VEC_alloc (iv_use_p, heap, 20);
774   data->iv_candidates = VEC_alloc (iv_cand_p, heap, 20);
775   decl_rtl_to_reset = VEC_alloc (tree, heap, 20);
776 }
777
778 /* Returns a memory object to that EXPR points.  In case we are able to
779    determine that it does not point to any such object, NULL is returned.  */
780
781 static tree
782 determine_base_object (tree expr)
783 {
784   enum tree_code code = TREE_CODE (expr);
785   tree base, obj;
786
787   /* If this is a pointer casted to any type, we need to determine
788      the base object for the pointer; so handle conversions before
789      throwing away non-pointer expressions.  */
790   if (CONVERT_EXPR_P (expr))
791     return determine_base_object (TREE_OPERAND (expr, 0));
792
793   if (!POINTER_TYPE_P (TREE_TYPE (expr)))
794     return NULL_TREE;
795
796   switch (code)
797     {
798     case INTEGER_CST:
799       return NULL_TREE;
800
801     case ADDR_EXPR:
802       obj = TREE_OPERAND (expr, 0);
803       base = get_base_address (obj);
804
805       if (!base)
806         return expr;
807
808       if (TREE_CODE (base) == INDIRECT_REF)
809         return determine_base_object (TREE_OPERAND (base, 0));
810
811       return fold_convert (ptr_type_node,
812                            build_fold_addr_expr (base));
813
814     case POINTER_PLUS_EXPR:
815       return determine_base_object (TREE_OPERAND (expr, 0));
816
817     case PLUS_EXPR:
818     case MINUS_EXPR:
819       /* Pointer addition is done solely using POINTER_PLUS_EXPR.  */
820       gcc_unreachable ();
821
822     default:
823       return fold_convert (ptr_type_node, expr);
824     }
825 }
826
827 /* Allocates an induction variable with given initial value BASE and step STEP
828    for loop LOOP.  */
829
830 static struct iv *
831 alloc_iv (tree base, tree step)
832 {
833   struct iv *iv = XCNEW (struct iv);
834   gcc_assert (step != NULL_TREE);
835
836   iv->base = base;
837   iv->base_object = determine_base_object (base);
838   iv->step = step;
839   iv->biv_p = false;
840   iv->have_use_for = false;
841   iv->use_id = 0;
842   iv->ssa_name = NULL_TREE;
843
844   return iv;
845 }
846
847 /* Sets STEP and BASE for induction variable IV.  */
848
849 static void
850 set_iv (struct ivopts_data *data, tree iv, tree base, tree step)
851 {
852   struct version_info *info = name_info (data, iv);
853
854   gcc_assert (!info->iv);
855
856   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
857   info->iv = alloc_iv (base, step);
858   info->iv->ssa_name = iv;
859 }
860
861 /* Finds induction variable declaration for VAR.  */
862
863 static struct iv *
864 get_iv (struct ivopts_data *data, tree var)
865 {
866   basic_block bb;
867   tree type = TREE_TYPE (var);
868
869   if (!POINTER_TYPE_P (type)
870       && !INTEGRAL_TYPE_P (type))
871     return NULL;
872
873   if (!name_info (data, var)->iv)
874     {
875       bb = gimple_bb (SSA_NAME_DEF_STMT (var));
876
877       if (!bb
878           || !flow_bb_inside_loop_p (data->current_loop, bb))
879         set_iv (data, var, var, build_int_cst (type, 0));
880     }
881
882   return name_info (data, var)->iv;
883 }
884
885 /* Determines the step of a biv defined in PHI.  Returns NULL if PHI does
886    not define a simple affine biv with nonzero step.  */
887
888 static tree
889 determine_biv_step (gimple phi)
890 {
891   struct loop *loop = gimple_bb (phi)->loop_father;
892   tree name = PHI_RESULT (phi);
893   affine_iv iv;
894
895   if (!is_gimple_reg (name))
896     return NULL_TREE;
897
898   if (!simple_iv (loop, loop, name, &iv, true))
899     return NULL_TREE;
900
901   return integer_zerop (iv.step) ? NULL_TREE : iv.step;
902 }
903
904 /* Finds basic ivs.  */
905
906 static bool
907 find_bivs (struct ivopts_data *data)
908 {
909   gimple phi;
910   tree step, type, base;
911   bool found = false;
912   struct loop *loop = data->current_loop;
913   gimple_stmt_iterator psi;
914
915   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
916     {
917       phi = gsi_stmt (psi);
918
919       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
920         continue;
921
922       step = determine_biv_step (phi);
923       if (!step)
924         continue;
925
926       base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
927       base = expand_simple_operations (base);
928       if (contains_abnormal_ssa_name_p (base)
929           || contains_abnormal_ssa_name_p (step))
930         continue;
931
932       type = TREE_TYPE (PHI_RESULT (phi));
933       base = fold_convert (type, base);
934       if (step)
935         {
936           if (POINTER_TYPE_P (type))
937             step = fold_convert (sizetype, step);
938           else
939             step = fold_convert (type, step);
940         }
941
942       set_iv (data, PHI_RESULT (phi), base, step);
943       found = true;
944     }
945
946   return found;
947 }
948
949 /* Marks basic ivs.  */
950
951 static void
952 mark_bivs (struct ivopts_data *data)
953 {
954   gimple phi;
955   tree var;
956   struct iv *iv, *incr_iv;
957   struct loop *loop = data->current_loop;
958   basic_block incr_bb;
959   gimple_stmt_iterator psi;
960
961   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
962     {
963       phi = gsi_stmt (psi);
964
965       iv = get_iv (data, PHI_RESULT (phi));
966       if (!iv)
967         continue;
968
969       var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
970       incr_iv = get_iv (data, var);
971       if (!incr_iv)
972         continue;
973
974       /* If the increment is in the subloop, ignore it.  */
975       incr_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
976       if (incr_bb->loop_father != data->current_loop
977           || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
978         continue;
979
980       iv->biv_p = true;
981       incr_iv->biv_p = true;
982     }
983 }
984
985 /* Checks whether STMT defines a linear induction variable and stores its
986    parameters to IV.  */
987
988 static bool
989 find_givs_in_stmt_scev (struct ivopts_data *data, gimple stmt, affine_iv *iv)
990 {
991   tree lhs;
992   struct loop *loop = data->current_loop;
993
994   iv->base = NULL_TREE;
995   iv->step = NULL_TREE;
996
997   if (gimple_code (stmt) != GIMPLE_ASSIGN)
998     return false;
999
1000   lhs = gimple_assign_lhs (stmt);
1001   if (TREE_CODE (lhs) != SSA_NAME)
1002     return false;
1003
1004   if (!simple_iv (loop, loop_containing_stmt (stmt), lhs, iv, true))
1005     return false;
1006   iv->base = expand_simple_operations (iv->base);
1007
1008   if (contains_abnormal_ssa_name_p (iv->base)
1009       || contains_abnormal_ssa_name_p (iv->step))
1010     return false;
1011
1012   return true;
1013 }
1014
1015 /* Finds general ivs in statement STMT.  */
1016
1017 static void
1018 find_givs_in_stmt (struct ivopts_data *data, gimple stmt)
1019 {
1020   affine_iv iv;
1021
1022   if (!find_givs_in_stmt_scev (data, stmt, &iv))
1023     return;
1024
1025   set_iv (data, gimple_assign_lhs (stmt), iv.base, iv.step);
1026 }
1027
1028 /* Finds general ivs in basic block BB.  */
1029
1030 static void
1031 find_givs_in_bb (struct ivopts_data *data, basic_block bb)
1032 {
1033   gimple_stmt_iterator bsi;
1034
1035   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1036     find_givs_in_stmt (data, gsi_stmt (bsi));
1037 }
1038
1039 /* Finds general ivs.  */
1040
1041 static void
1042 find_givs (struct ivopts_data *data)
1043 {
1044   struct loop *loop = data->current_loop;
1045   basic_block *body = get_loop_body_in_dom_order (loop);
1046   unsigned i;
1047
1048   for (i = 0; i < loop->num_nodes; i++)
1049     find_givs_in_bb (data, body[i]);
1050   free (body);
1051 }
1052
1053 /* For each ssa name defined in LOOP determines whether it is an induction
1054    variable and if so, its initial value and step.  */
1055
1056 static bool
1057 find_induction_variables (struct ivopts_data *data)
1058 {
1059   unsigned i;
1060   bitmap_iterator bi;
1061
1062   if (!find_bivs (data))
1063     return false;
1064
1065   find_givs (data);
1066   mark_bivs (data);
1067
1068   if (dump_file && (dump_flags & TDF_DETAILS))
1069     {
1070       tree niter = niter_for_single_dom_exit (data);
1071
1072       if (niter)
1073         {
1074           fprintf (dump_file, "  number of iterations ");
1075           print_generic_expr (dump_file, niter, TDF_SLIM);
1076           fprintf (dump_file, "\n\n");
1077         };
1078
1079       fprintf (dump_file, "Induction variables:\n\n");
1080
1081       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1082         {
1083           if (ver_info (data, i)->iv)
1084             dump_iv (dump_file, ver_info (data, i)->iv);
1085         }
1086     }
1087
1088   return true;
1089 }
1090
1091 /* Records a use of type USE_TYPE at *USE_P in STMT whose value is IV.  */
1092
1093 static struct iv_use *
1094 record_use (struct ivopts_data *data, tree *use_p, struct iv *iv,
1095             gimple stmt, enum use_type use_type)
1096 {
1097   struct iv_use *use = XCNEW (struct iv_use);
1098
1099   use->id = n_iv_uses (data);
1100   use->type = use_type;
1101   use->iv = iv;
1102   use->stmt = stmt;
1103   use->op_p = use_p;
1104   use->related_cands = BITMAP_ALLOC (NULL);
1105
1106   /* To avoid showing ssa name in the dumps, if it was not reset by the
1107      caller.  */
1108   iv->ssa_name = NULL_TREE;
1109
1110   if (dump_file && (dump_flags & TDF_DETAILS))
1111     dump_use (dump_file, use);
1112
1113   VEC_safe_push (iv_use_p, heap, data->iv_uses, use);
1114
1115   return use;
1116 }
1117
1118 /* Checks whether OP is a loop-level invariant and if so, records it.
1119    NONLINEAR_USE is true if the invariant is used in a way we do not
1120    handle specially.  */
1121
1122 static void
1123 record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
1124 {
1125   basic_block bb;
1126   struct version_info *info;
1127
1128   if (TREE_CODE (op) != SSA_NAME
1129       || !is_gimple_reg (op))
1130     return;
1131
1132   bb = gimple_bb (SSA_NAME_DEF_STMT (op));
1133   if (bb
1134       && flow_bb_inside_loop_p (data->current_loop, bb))
1135     return;
1136
1137   info = name_info (data, op);
1138   info->name = op;
1139   info->has_nonlin_use |= nonlinear_use;
1140   if (!info->inv_id)
1141     info->inv_id = ++data->max_inv_id;
1142   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
1143 }
1144
1145 /* Checks whether the use OP is interesting and if so, records it.  */
1146
1147 static struct iv_use *
1148 find_interesting_uses_op (struct ivopts_data *data, tree op)
1149 {
1150   struct iv *iv;
1151   struct iv *civ;
1152   gimple stmt;
1153   struct iv_use *use;
1154
1155   if (TREE_CODE (op) != SSA_NAME)
1156     return NULL;
1157
1158   iv = get_iv (data, op);
1159   if (!iv)
1160     return NULL;
1161
1162   if (iv->have_use_for)
1163     {
1164       use = iv_use (data, iv->use_id);
1165
1166       gcc_assert (use->type == USE_NONLINEAR_EXPR);
1167       return use;
1168     }
1169
1170   if (integer_zerop (iv->step))
1171     {
1172       record_invariant (data, op, true);
1173       return NULL;
1174     }
1175   iv->have_use_for = true;
1176
1177   civ = XNEW (struct iv);
1178   *civ = *iv;
1179
1180   stmt = SSA_NAME_DEF_STMT (op);
1181   gcc_assert (gimple_code (stmt) == GIMPLE_PHI
1182               || is_gimple_assign (stmt));
1183
1184   use = record_use (data, NULL, civ, stmt, USE_NONLINEAR_EXPR);
1185   iv->use_id = use->id;
1186
1187   return use;
1188 }
1189
1190 /* Given a condition in statement STMT, checks whether it is a compare
1191    of an induction variable and an invariant.  If this is the case,
1192    CONTROL_VAR is set to location of the iv, BOUND to the location of
1193    the invariant, IV_VAR and IV_BOUND are set to the corresponding
1194    induction variable descriptions, and true is returned.  If this is not
1195    the case, CONTROL_VAR and BOUND are set to the arguments of the
1196    condition and false is returned.  */
1197
1198 static bool
1199 extract_cond_operands (struct ivopts_data *data, gimple stmt,
1200                        tree **control_var, tree **bound,
1201                        struct iv **iv_var, struct iv **iv_bound)
1202 {
1203   /* The objects returned when COND has constant operands.  */
1204   static struct iv const_iv;
1205   static tree zero;
1206   tree *op0 = &zero, *op1 = &zero, *tmp_op;
1207   struct iv *iv0 = &const_iv, *iv1 = &const_iv, *tmp_iv;
1208   bool ret = false;
1209
1210   if (gimple_code (stmt) == GIMPLE_COND)
1211     {
1212       op0 = gimple_cond_lhs_ptr (stmt);
1213       op1 = gimple_cond_rhs_ptr (stmt);
1214     }
1215   else
1216     {
1217       op0 = gimple_assign_rhs1_ptr (stmt);
1218       op1 = gimple_assign_rhs2_ptr (stmt);
1219     }
1220
1221   zero = integer_zero_node;
1222   const_iv.step = integer_zero_node;
1223
1224   if (TREE_CODE (*op0) == SSA_NAME)
1225     iv0 = get_iv (data, *op0);
1226   if (TREE_CODE (*op1) == SSA_NAME)
1227     iv1 = get_iv (data, *op1);
1228
1229   /* Exactly one of the compared values must be an iv, and the other one must
1230      be an invariant.  */
1231   if (!iv0 || !iv1)
1232     goto end;
1233
1234   if (integer_zerop (iv0->step))
1235     {
1236       /* Control variable may be on the other side.  */
1237       tmp_op = op0; op0 = op1; op1 = tmp_op;
1238       tmp_iv = iv0; iv0 = iv1; iv1 = tmp_iv;
1239     }
1240   ret = !integer_zerop (iv0->step) && integer_zerop (iv1->step);
1241
1242 end:
1243   if (control_var)
1244     *control_var = op0;;
1245   if (iv_var)
1246     *iv_var = iv0;;
1247   if (bound)
1248     *bound = op1;
1249   if (iv_bound)
1250     *iv_bound = iv1;
1251
1252   return ret;
1253 }
1254
1255 /* Checks whether the condition in STMT is interesting and if so,
1256    records it.  */
1257
1258 static void
1259 find_interesting_uses_cond (struct ivopts_data *data, gimple stmt)
1260 {
1261   tree *var_p, *bound_p;
1262   struct iv *var_iv, *civ;
1263
1264   if (!extract_cond_operands (data, stmt, &var_p, &bound_p, &var_iv, NULL))
1265     {
1266       find_interesting_uses_op (data, *var_p);
1267       find_interesting_uses_op (data, *bound_p);
1268       return;
1269     }
1270
1271   civ = XNEW (struct iv);
1272   *civ = *var_iv;
1273   record_use (data, NULL, civ, stmt, USE_COMPARE);
1274 }
1275
1276 /* Returns true if expression EXPR is obviously invariant in LOOP,
1277    i.e. if all its operands are defined outside of the LOOP.  LOOP
1278    should not be the function body.  */
1279
1280 bool
1281 expr_invariant_in_loop_p (struct loop *loop, tree expr)
1282 {
1283   basic_block def_bb;
1284   unsigned i, len;
1285
1286   gcc_assert (loop_depth (loop) > 0);
1287
1288   if (is_gimple_min_invariant (expr))
1289     return true;
1290
1291   if (TREE_CODE (expr) == SSA_NAME)
1292     {
1293       def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
1294       if (def_bb
1295           && flow_bb_inside_loop_p (loop, def_bb))
1296         return false;
1297
1298       return true;
1299     }
1300
1301   if (!EXPR_P (expr))
1302     return false;
1303
1304   len = TREE_OPERAND_LENGTH (expr);
1305   for (i = 0; i < len; i++)
1306     if (!expr_invariant_in_loop_p (loop, TREE_OPERAND (expr, i)))
1307       return false;
1308
1309   return true;
1310 }
1311
1312 /* Returns true if statement STMT is obviously invariant in LOOP,
1313    i.e. if all its operands on the RHS are defined outside of the LOOP.
1314    LOOP should not be the function body.  */
1315
1316 bool
1317 stmt_invariant_in_loop_p (struct loop *loop, gimple stmt)
1318 {
1319   unsigned i;
1320   tree lhs;
1321
1322   gcc_assert (loop_depth (loop) > 0);
1323
1324   lhs = gimple_get_lhs (stmt);
1325   for (i = 0; i < gimple_num_ops (stmt); i++)
1326     {
1327       tree op = gimple_op (stmt, i);
1328       if (op != lhs && !expr_invariant_in_loop_p (loop, op))
1329         return false;
1330     }
1331
1332   return true;
1333 }
1334
1335 /* Cumulates the steps of indices into DATA and replaces their values with the
1336    initial ones.  Returns false when the value of the index cannot be determined.
1337    Callback for for_each_index.  */
1338
1339 struct ifs_ivopts_data
1340 {
1341   struct ivopts_data *ivopts_data;
1342   gimple stmt;
1343   tree step;
1344 };
1345
1346 static bool
1347 idx_find_step (tree base, tree *idx, void *data)
1348 {
1349   struct ifs_ivopts_data *dta = (struct ifs_ivopts_data *) data;
1350   struct iv *iv;
1351   tree step, iv_base, iv_step, lbound, off;
1352   struct loop *loop = dta->ivopts_data->current_loop;
1353
1354   if (TREE_CODE (base) == MISALIGNED_INDIRECT_REF
1355       || TREE_CODE (base) == ALIGN_INDIRECT_REF)
1356     return false;
1357
1358   /* If base is a component ref, require that the offset of the reference
1359      be invariant.  */
1360   if (TREE_CODE (base) == COMPONENT_REF)
1361     {
1362       off = component_ref_field_offset (base);
1363       return expr_invariant_in_loop_p (loop, off);
1364     }
1365
1366   /* If base is array, first check whether we will be able to move the
1367      reference out of the loop (in order to take its address in strength
1368      reduction).  In order for this to work we need both lower bound
1369      and step to be loop invariants.  */
1370   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
1371     {
1372       /* Moreover, for a range, the size needs to be invariant as well.  */
1373       if (TREE_CODE (base) == ARRAY_RANGE_REF
1374           && !expr_invariant_in_loop_p (loop, TYPE_SIZE (TREE_TYPE (base))))
1375         return false;
1376
1377       step = array_ref_element_size (base);
1378       lbound = array_ref_low_bound (base);
1379
1380       if (!expr_invariant_in_loop_p (loop, step)
1381           || !expr_invariant_in_loop_p (loop, lbound))
1382         return false;
1383     }
1384
1385   if (TREE_CODE (*idx) != SSA_NAME)
1386     return true;
1387
1388   iv = get_iv (dta->ivopts_data, *idx);
1389   if (!iv)
1390     return false;
1391
1392   /* XXX  We produce for a base of *D42 with iv->base being &x[0]
1393           *&x[0], which is not folded and does not trigger the
1394           ARRAY_REF path below.  */
1395   *idx = iv->base;
1396
1397   if (integer_zerop (iv->step))
1398     return true;
1399
1400   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
1401     {
1402       step = array_ref_element_size (base);
1403
1404       /* We only handle addresses whose step is an integer constant.  */
1405       if (TREE_CODE (step) != INTEGER_CST)
1406         return false;
1407     }
1408   else
1409     /* The step for pointer arithmetics already is 1 byte.  */
1410     step = build_int_cst (sizetype, 1);
1411
1412   iv_base = iv->base;
1413   iv_step = iv->step;
1414   if (!convert_affine_scev (dta->ivopts_data->current_loop,
1415                             sizetype, &iv_base, &iv_step, dta->stmt,
1416                             false))
1417     {
1418       /* The index might wrap.  */
1419       return false;
1420     }
1421
1422   step = fold_build2 (MULT_EXPR, sizetype, step, iv_step);
1423   dta->step = fold_build2 (PLUS_EXPR, sizetype, dta->step, step);
1424
1425   return true;
1426 }
1427
1428 /* Records use in index IDX.  Callback for for_each_index.  Ivopts data
1429    object is passed to it in DATA.  */
1430
1431 static bool
1432 idx_record_use (tree base, tree *idx,
1433                 void *vdata)
1434 {
1435   struct ivopts_data *data = (struct ivopts_data *) vdata;
1436   find_interesting_uses_op (data, *idx);
1437   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
1438     {
1439       find_interesting_uses_op (data, array_ref_element_size (base));
1440       find_interesting_uses_op (data, array_ref_low_bound (base));
1441     }
1442   return true;
1443 }
1444
1445 /* If we can prove that TOP = cst * BOT for some constant cst,
1446    store cst to MUL and return true.  Otherwise return false.
1447    The returned value is always sign-extended, regardless of the
1448    signedness of TOP and BOT.  */
1449
1450 static bool
1451 constant_multiple_of (tree top, tree bot, double_int *mul)
1452 {
1453   tree mby;
1454   enum tree_code code;
1455   double_int res, p0, p1;
1456   unsigned precision = TYPE_PRECISION (TREE_TYPE (top));
1457
1458   STRIP_NOPS (top);
1459   STRIP_NOPS (bot);
1460
1461   if (operand_equal_p (top, bot, 0))
1462     {
1463       *mul = double_int_one;
1464       return true;
1465     }
1466
1467   code = TREE_CODE (top);
1468   switch (code)
1469     {
1470     case MULT_EXPR:
1471       mby = TREE_OPERAND (top, 1);
1472       if (TREE_CODE (mby) != INTEGER_CST)
1473         return false;
1474
1475       if (!constant_multiple_of (TREE_OPERAND (top, 0), bot, &res))
1476         return false;
1477
1478       *mul = double_int_sext (double_int_mul (res, tree_to_double_int (mby)),
1479                               precision);
1480       return true;
1481
1482     case PLUS_EXPR:
1483     case MINUS_EXPR:
1484       if (!constant_multiple_of (TREE_OPERAND (top, 0), bot, &p0)
1485           || !constant_multiple_of (TREE_OPERAND (top, 1), bot, &p1))
1486         return false;
1487
1488       if (code == MINUS_EXPR)
1489         p1 = double_int_neg (p1);
1490       *mul = double_int_sext (double_int_add (p0, p1), precision);
1491       return true;
1492
1493     case INTEGER_CST:
1494       if (TREE_CODE (bot) != INTEGER_CST)
1495         return false;
1496
1497       p0 = double_int_sext (tree_to_double_int (top), precision);
1498       p1 = double_int_sext (tree_to_double_int (bot), precision);
1499       if (double_int_zero_p (p1))
1500         return false;
1501       *mul = double_int_sext (double_int_sdivmod (p0, p1, FLOOR_DIV_EXPR, &res),
1502                               precision);
1503       return double_int_zero_p (res);
1504
1505     default:
1506       return false;
1507     }
1508 }
1509
1510 /* Returns true if memory reference REF with step STEP may be unaligned.  */
1511
1512 static bool
1513 may_be_unaligned_p (tree ref, tree step)
1514 {
1515   tree base;
1516   tree base_type;
1517   HOST_WIDE_INT bitsize;
1518   HOST_WIDE_INT bitpos;
1519   tree toffset;
1520   enum machine_mode mode;
1521   int unsignedp, volatilep;
1522   unsigned base_align;
1523
1524   /* TARGET_MEM_REFs are translated directly to valid MEMs on the target,
1525      thus they are not misaligned.  */
1526   if (TREE_CODE (ref) == TARGET_MEM_REF)
1527     return false;
1528
1529   /* The test below is basically copy of what expr.c:normal_inner_ref
1530      does to check whether the object must be loaded by parts when
1531      STRICT_ALIGNMENT is true.  */
1532   base = get_inner_reference (ref, &bitsize, &bitpos, &toffset, &mode,
1533                               &unsignedp, &volatilep, true);
1534   base_type = TREE_TYPE (base);
1535   base_align = TYPE_ALIGN (base_type);
1536
1537   if (mode != BLKmode)
1538     {
1539       double_int mul;
1540       tree al = build_int_cst (TREE_TYPE (step),
1541                                GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT);
1542
1543       if (base_align < GET_MODE_ALIGNMENT (mode)
1544           || bitpos % GET_MODE_ALIGNMENT (mode) != 0
1545           || bitpos % BITS_PER_UNIT != 0)
1546         return true;
1547
1548       if (!constant_multiple_of (step, al, &mul))
1549         return true;
1550     }
1551
1552   return false;
1553 }
1554
1555 /* Return true if EXPR may be non-addressable.   */
1556
1557 static bool
1558 may_be_nonaddressable_p (tree expr)
1559 {
1560   switch (TREE_CODE (expr))
1561     {
1562     case TARGET_MEM_REF:
1563       /* TARGET_MEM_REFs are translated directly to valid MEMs on the
1564          target, thus they are always addressable.  */
1565       return false;
1566
1567     case COMPONENT_REF:
1568       return DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1))
1569              || may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
1570
1571     case VIEW_CONVERT_EXPR:
1572       /* This kind of view-conversions may wrap non-addressable objects
1573          and make them look addressable.  After some processing the
1574          non-addressability may be uncovered again, causing ADDR_EXPRs
1575          of inappropriate objects to be built.  */
1576       if (is_gimple_reg (TREE_OPERAND (expr, 0))
1577           || !is_gimple_addressable (TREE_OPERAND (expr, 0)))
1578         return true;
1579
1580       /* ... fall through ... */
1581
1582     case ARRAY_REF:
1583     case ARRAY_RANGE_REF:
1584       return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
1585
1586     CASE_CONVERT:
1587       return true;
1588
1589     default:
1590       break;
1591     }
1592
1593   return false;
1594 }
1595
1596 /* Finds addresses in *OP_P inside STMT.  */
1597
1598 static void
1599 find_interesting_uses_address (struct ivopts_data *data, gimple stmt, tree *op_p)
1600 {
1601   tree base = *op_p, step = build_int_cst (sizetype, 0);
1602   struct iv *civ;
1603   struct ifs_ivopts_data ifs_ivopts_data;
1604
1605   /* Do not play with volatile memory references.  A bit too conservative,
1606      perhaps, but safe.  */
1607   if (gimple_has_volatile_ops (stmt))
1608     goto fail;
1609
1610   /* Ignore bitfields for now.  Not really something terribly complicated
1611      to handle.  TODO.  */
1612   if (TREE_CODE (base) == BIT_FIELD_REF)
1613     goto fail;
1614
1615   base = unshare_expr (base);
1616
1617   if (TREE_CODE (base) == TARGET_MEM_REF)
1618     {
1619       tree type = build_pointer_type (TREE_TYPE (base));
1620       tree astep;
1621
1622       if (TMR_BASE (base)
1623           && TREE_CODE (TMR_BASE (base)) == SSA_NAME)
1624         {
1625           civ = get_iv (data, TMR_BASE (base));
1626           if (!civ)
1627             goto fail;
1628
1629           TMR_BASE (base) = civ->base;
1630           step = civ->step;
1631         }
1632       if (TMR_INDEX (base)
1633           && TREE_CODE (TMR_INDEX (base)) == SSA_NAME)
1634         {
1635           civ = get_iv (data, TMR_INDEX (base));
1636           if (!civ)
1637             goto fail;
1638
1639           TMR_INDEX (base) = civ->base;
1640           astep = civ->step;
1641
1642           if (astep)
1643             {
1644               if (TMR_STEP (base))
1645                 astep = fold_build2 (MULT_EXPR, type, TMR_STEP (base), astep);
1646
1647               step = fold_build2 (PLUS_EXPR, type, step, astep);
1648             }
1649         }
1650
1651       if (integer_zerop (step))
1652         goto fail;
1653       base = tree_mem_ref_addr (type, base);
1654     }
1655   else
1656     {
1657       ifs_ivopts_data.ivopts_data = data;
1658       ifs_ivopts_data.stmt = stmt;
1659       ifs_ivopts_data.step = build_int_cst (sizetype, 0);
1660       if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
1661           || integer_zerop (ifs_ivopts_data.step))
1662         goto fail;
1663       step = ifs_ivopts_data.step;
1664
1665       gcc_assert (TREE_CODE (base) != ALIGN_INDIRECT_REF);
1666       gcc_assert (TREE_CODE (base) != MISALIGNED_INDIRECT_REF);
1667
1668       /* Check that the base expression is addressable.  This needs
1669          to be done after substituting bases of IVs into it.  */
1670       if (may_be_nonaddressable_p (base))
1671         goto fail;
1672
1673       /* Moreover, on strict alignment platforms, check that it is
1674          sufficiently aligned.  */
1675       if (STRICT_ALIGNMENT && may_be_unaligned_p (base, step))
1676         goto fail;
1677
1678       base = build_fold_addr_expr (base);
1679
1680       /* Substituting bases of IVs into the base expression might
1681          have caused folding opportunities.  */
1682       if (TREE_CODE (base) == ADDR_EXPR)
1683         {
1684           tree *ref = &TREE_OPERAND (base, 0);
1685           while (handled_component_p (*ref))
1686             ref = &TREE_OPERAND (*ref, 0);
1687           if (TREE_CODE (*ref) == INDIRECT_REF)
1688             {
1689               tree tem = gimple_fold_indirect_ref (TREE_OPERAND (*ref, 0));
1690               if (tem)
1691                 *ref = tem;
1692             }
1693         }
1694     }
1695
1696   civ = alloc_iv (base, step);
1697   record_use (data, op_p, civ, stmt, USE_ADDRESS);
1698   return;
1699
1700 fail:
1701   for_each_index (op_p, idx_record_use, data);
1702 }
1703
1704 /* Finds and records invariants used in STMT.  */
1705
1706 static void
1707 find_invariants_stmt (struct ivopts_data *data, gimple stmt)
1708 {
1709   ssa_op_iter iter;
1710   use_operand_p use_p;
1711   tree op;
1712
1713   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
1714     {
1715       op = USE_FROM_PTR (use_p);
1716       record_invariant (data, op, false);
1717     }
1718 }
1719
1720 /* Finds interesting uses of induction variables in the statement STMT.  */
1721
1722 static void
1723 find_interesting_uses_stmt (struct ivopts_data *data, gimple stmt)
1724 {
1725   struct iv *iv;
1726   tree op, *lhs, *rhs;
1727   ssa_op_iter iter;
1728   use_operand_p use_p;
1729   enum tree_code code;
1730
1731   find_invariants_stmt (data, stmt);
1732
1733   if (gimple_code (stmt) == GIMPLE_COND)
1734     {
1735       find_interesting_uses_cond (data, stmt);
1736       return;
1737     }
1738
1739   if (is_gimple_assign (stmt))
1740     {
1741       lhs = gimple_assign_lhs_ptr (stmt);
1742       rhs = gimple_assign_rhs1_ptr (stmt);
1743
1744       if (TREE_CODE (*lhs) == SSA_NAME)
1745         {
1746           /* If the statement defines an induction variable, the uses are not
1747              interesting by themselves.  */
1748
1749           iv = get_iv (data, *lhs);
1750
1751           if (iv && !integer_zerop (iv->step))
1752             return;
1753         }
1754
1755       code = gimple_assign_rhs_code (stmt);
1756       if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
1757           && (REFERENCE_CLASS_P (*rhs)
1758               || is_gimple_val (*rhs)))
1759         {
1760           if (REFERENCE_CLASS_P (*rhs))
1761             find_interesting_uses_address (data, stmt, rhs);
1762           else
1763             find_interesting_uses_op (data, *rhs);
1764
1765           if (REFERENCE_CLASS_P (*lhs))
1766             find_interesting_uses_address (data, stmt, lhs);
1767           return;
1768         }
1769       else if (TREE_CODE_CLASS (code) == tcc_comparison)
1770         {
1771           find_interesting_uses_cond (data, stmt);
1772           return;
1773         }
1774
1775       /* TODO -- we should also handle address uses of type
1776
1777          memory = call (whatever);
1778
1779          and
1780
1781          call (memory).  */
1782     }
1783
1784   if (gimple_code (stmt) == GIMPLE_PHI
1785       && gimple_bb (stmt) == data->current_loop->header)
1786     {
1787       iv = get_iv (data, PHI_RESULT (stmt));
1788
1789       if (iv && !integer_zerop (iv->step))
1790         return;
1791     }
1792
1793   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
1794     {
1795       op = USE_FROM_PTR (use_p);
1796
1797       if (TREE_CODE (op) != SSA_NAME)
1798         continue;
1799
1800       iv = get_iv (data, op);
1801       if (!iv)
1802         continue;
1803
1804       find_interesting_uses_op (data, op);
1805     }
1806 }
1807
1808 /* Finds interesting uses of induction variables outside of loops
1809    on loop exit edge EXIT.  */
1810
1811 static void
1812 find_interesting_uses_outside (struct ivopts_data *data, edge exit)
1813 {
1814   gimple phi;
1815   gimple_stmt_iterator psi;
1816   tree def;
1817
1818   for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
1819     {
1820       phi = gsi_stmt (psi);
1821       def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1822       if (is_gimple_reg (def))
1823         find_interesting_uses_op (data, def);
1824     }
1825 }
1826
1827 /* Finds uses of the induction variables that are interesting.  */
1828
1829 static void
1830 find_interesting_uses (struct ivopts_data *data)
1831 {
1832   basic_block bb;
1833   gimple_stmt_iterator bsi;
1834   basic_block *body = get_loop_body (data->current_loop);
1835   unsigned i;
1836   struct version_info *info;
1837   edge e;
1838
1839   if (dump_file && (dump_flags & TDF_DETAILS))
1840     fprintf (dump_file, "Uses:\n\n");
1841
1842   for (i = 0; i < data->current_loop->num_nodes; i++)
1843     {
1844       edge_iterator ei;
1845       bb = body[i];
1846
1847       FOR_EACH_EDGE (e, ei, bb->succs)
1848         if (e->dest != EXIT_BLOCK_PTR
1849             && !flow_bb_inside_loop_p (data->current_loop, e->dest))
1850           find_interesting_uses_outside (data, e);
1851
1852       for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1853         find_interesting_uses_stmt (data, gsi_stmt (bsi));
1854       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1855         if (!is_gimple_debug (gsi_stmt (bsi)))
1856           find_interesting_uses_stmt (data, gsi_stmt (bsi));
1857     }
1858
1859   if (dump_file && (dump_flags & TDF_DETAILS))
1860     {
1861       bitmap_iterator bi;
1862
1863       fprintf (dump_file, "\n");
1864
1865       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
1866         {
1867           info = ver_info (data, i);
1868           if (info->inv_id)
1869             {
1870               fprintf (dump_file, "  ");
1871               print_generic_expr (dump_file, info->name, TDF_SLIM);
1872               fprintf (dump_file, " is invariant (%d)%s\n",
1873                        info->inv_id, info->has_nonlin_use ? "" : ", eliminable");
1874             }
1875         }
1876
1877       fprintf (dump_file, "\n");
1878     }
1879
1880   free (body);
1881 }
1882
1883 /* Strips constant offsets from EXPR and stores them to OFFSET.  If INSIDE_ADDR
1884    is true, assume we are inside an address.  If TOP_COMPREF is true, assume
1885    we are at the top-level of the processed address.  */
1886
1887 static tree
1888 strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
1889                 unsigned HOST_WIDE_INT *offset)
1890 {
1891   tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
1892   enum tree_code code;
1893   tree type, orig_type = TREE_TYPE (expr);
1894   unsigned HOST_WIDE_INT off0, off1, st;
1895   tree orig_expr = expr;
1896
1897   STRIP_NOPS (expr);
1898
1899   type = TREE_TYPE (expr);
1900   code = TREE_CODE (expr);
1901   *offset = 0;
1902
1903   switch (code)
1904     {
1905     case INTEGER_CST:
1906       if (!cst_and_fits_in_hwi (expr)
1907           || integer_zerop (expr))
1908         return orig_expr;
1909
1910       *offset = int_cst_value (expr);
1911       return build_int_cst (orig_type, 0);
1912
1913     case POINTER_PLUS_EXPR:
1914     case PLUS_EXPR:
1915     case MINUS_EXPR:
1916       op0 = TREE_OPERAND (expr, 0);
1917       op1 = TREE_OPERAND (expr, 1);
1918
1919       op0 = strip_offset_1 (op0, false, false, &off0);
1920       op1 = strip_offset_1 (op1, false, false, &off1);
1921
1922       *offset = (code == MINUS_EXPR ? off0 - off1 : off0 + off1);
1923       if (op0 == TREE_OPERAND (expr, 0)
1924           && op1 == TREE_OPERAND (expr, 1))
1925         return orig_expr;
1926
1927       if (integer_zerop (op1))
1928         expr = op0;
1929       else if (integer_zerop (op0))
1930         {
1931           if (code == MINUS_EXPR)
1932             expr = fold_build1 (NEGATE_EXPR, type, op1);
1933           else
1934             expr = op1;
1935         }
1936       else
1937         expr = fold_build2 (code, type, op0, op1);
1938
1939       return fold_convert (orig_type, expr);
1940
1941     case MULT_EXPR:
1942       op1 = TREE_OPERAND (expr, 1);
1943       if (!cst_and_fits_in_hwi (op1))
1944         return orig_expr;
1945
1946       op0 = TREE_OPERAND (expr, 0);
1947       op0 = strip_offset_1 (op0, false, false, &off0);
1948       if (op0 == TREE_OPERAND (expr, 0))
1949         return orig_expr;
1950
1951       *offset = off0 * int_cst_value (op1);
1952       if (integer_zerop (op0))
1953         expr = op0;
1954       else
1955         expr = fold_build2 (MULT_EXPR, type, op0, op1);
1956
1957       return fold_convert (orig_type, expr);
1958
1959     case ARRAY_REF:
1960     case ARRAY_RANGE_REF:
1961       if (!inside_addr)
1962         return orig_expr;
1963
1964       step = array_ref_element_size (expr);
1965       if (!cst_and_fits_in_hwi (step))
1966         break;
1967
1968       st = int_cst_value (step);
1969       op1 = TREE_OPERAND (expr, 1);
1970       op1 = strip_offset_1 (op1, false, false, &off1);
1971       *offset = off1 * st;
1972
1973       if (top_compref
1974           && integer_zerop (op1))
1975         {
1976           /* Strip the component reference completely.  */
1977           op0 = TREE_OPERAND (expr, 0);
1978           op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
1979           *offset += off0;
1980           return op0;
1981         }
1982       break;
1983
1984     case COMPONENT_REF:
1985       if (!inside_addr)
1986         return orig_expr;
1987
1988       tmp = component_ref_field_offset (expr);
1989       if (top_compref
1990           && cst_and_fits_in_hwi (tmp))
1991         {
1992           /* Strip the component reference completely.  */
1993           op0 = TREE_OPERAND (expr, 0);
1994           op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
1995           *offset = off0 + int_cst_value (tmp);
1996           return op0;
1997         }
1998       break;
1999
2000     case ADDR_EXPR:
2001       op0 = TREE_OPERAND (expr, 0);
2002       op0 = strip_offset_1 (op0, true, true, &off0);
2003       *offset += off0;
2004
2005       if (op0 == TREE_OPERAND (expr, 0))
2006         return orig_expr;
2007
2008       expr = build_fold_addr_expr (op0);
2009       return fold_convert (orig_type, expr);
2010
2011     case INDIRECT_REF:
2012       inside_addr = false;
2013       break;
2014
2015     default:
2016       return orig_expr;
2017     }
2018
2019   /* Default handling of expressions for that we want to recurse into
2020      the first operand.  */
2021   op0 = TREE_OPERAND (expr, 0);
2022   op0 = strip_offset_1 (op0, inside_addr, false, &off0);
2023   *offset += off0;
2024
2025   if (op0 == TREE_OPERAND (expr, 0)
2026       && (!op1 || op1 == TREE_OPERAND (expr, 1)))
2027     return orig_expr;
2028
2029   expr = copy_node (expr);
2030   TREE_OPERAND (expr, 0) = op0;
2031   if (op1)
2032     TREE_OPERAND (expr, 1) = op1;
2033
2034   /* Inside address, we might strip the top level component references,
2035      thus changing type of the expression.  Handling of ADDR_EXPR
2036      will fix that.  */
2037   expr = fold_convert (orig_type, expr);
2038
2039   return expr;
2040 }
2041
2042 /* Strips constant offsets from EXPR and stores them to OFFSET.  */
2043
2044 static tree
2045 strip_offset (tree expr, unsigned HOST_WIDE_INT *offset)
2046 {
2047   return strip_offset_1 (expr, false, false, offset);
2048 }
2049
2050 /* Returns variant of TYPE that can be used as base for different uses.
2051    We return unsigned type with the same precision, which avoids problems
2052    with overflows.  */
2053
2054 static tree
2055 generic_type_for (tree type)
2056 {
2057   if (POINTER_TYPE_P (type))
2058     return unsigned_type_for (type);
2059
2060   if (TYPE_UNSIGNED (type))
2061     return type;
2062
2063   return unsigned_type_for (type);
2064 }
2065
2066 /* Records invariants in *EXPR_P.  Callback for walk_tree.  DATA contains
2067    the bitmap to that we should store it.  */
2068
2069 static struct ivopts_data *fd_ivopts_data;
2070 static tree
2071 find_depends (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
2072 {
2073   bitmap *depends_on = (bitmap *) data;
2074   struct version_info *info;
2075
2076   if (TREE_CODE (*expr_p) != SSA_NAME)
2077     return NULL_TREE;
2078   info = name_info (fd_ivopts_data, *expr_p);
2079
2080   if (!info->inv_id || info->has_nonlin_use)
2081     return NULL_TREE;
2082
2083   if (!*depends_on)
2084     *depends_on = BITMAP_ALLOC (NULL);
2085   bitmap_set_bit (*depends_on, info->inv_id);
2086
2087   return NULL_TREE;
2088 }
2089
2090 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
2091    position to POS.  If USE is not NULL, the candidate is set as related to
2092    it.  If both BASE and STEP are NULL, we add a pseudocandidate for the
2093    replacement of the final value of the iv by a direct computation.  */
2094
2095 static struct iv_cand *
2096 add_candidate_1 (struct ivopts_data *data,
2097                  tree base, tree step, bool important, enum iv_position pos,
2098                  struct iv_use *use, gimple incremented_at)
2099 {
2100   unsigned i;
2101   struct iv_cand *cand = NULL;
2102   tree type, orig_type;
2103
2104   if (base)
2105     {
2106       orig_type = TREE_TYPE (base);
2107       type = generic_type_for (orig_type);
2108       if (type != orig_type)
2109         {
2110           base = fold_convert (type, base);
2111           step = fold_convert (type, step);
2112         }
2113     }
2114
2115   for (i = 0; i < n_iv_cands (data); i++)
2116     {
2117       cand = iv_cand (data, i);
2118
2119       if (cand->pos != pos)
2120         continue;
2121
2122       if (cand->incremented_at != incremented_at
2123           || ((pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
2124               && cand->ainc_use != use))
2125         continue;
2126
2127       if (!cand->iv)
2128         {
2129           if (!base && !step)
2130             break;
2131
2132           continue;
2133         }
2134
2135       if (!base && !step)
2136         continue;
2137
2138       if (operand_equal_p (base, cand->iv->base, 0)
2139           && operand_equal_p (step, cand->iv->step, 0))
2140         break;
2141     }
2142
2143   if (i == n_iv_cands (data))
2144     {
2145       cand = XCNEW (struct iv_cand);
2146       cand->id = i;
2147
2148       if (!base && !step)
2149         cand->iv = NULL;
2150       else
2151         cand->iv = alloc_iv (base, step);
2152
2153       cand->pos = pos;
2154       if (pos != IP_ORIGINAL && cand->iv)
2155         {
2156           cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
2157           cand->var_after = cand->var_before;
2158         }
2159       cand->important = important;
2160       cand->incremented_at = incremented_at;
2161       VEC_safe_push (iv_cand_p, heap, data->iv_candidates, cand);
2162
2163       if (step
2164           && TREE_CODE (step) != INTEGER_CST)
2165         {
2166           fd_ivopts_data = data;
2167           walk_tree (&step, find_depends, &cand->depends_on, NULL);
2168         }
2169
2170       if (pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
2171         cand->ainc_use = use;
2172       else
2173         cand->ainc_use = NULL;
2174
2175       if (dump_file && (dump_flags & TDF_DETAILS))
2176         dump_cand (dump_file, cand);
2177     }
2178
2179   if (important && !cand->important)
2180     {
2181       cand->important = true;
2182       if (dump_file && (dump_flags & TDF_DETAILS))
2183         fprintf (dump_file, "Candidate %d is important\n", cand->id);
2184     }
2185
2186   if (use)
2187     {
2188       bitmap_set_bit (use->related_cands, i);
2189       if (dump_file && (dump_flags & TDF_DETAILS))
2190         fprintf (dump_file, "Candidate %d is related to use %d\n",
2191                  cand->id, use->id);
2192     }
2193
2194   return cand;
2195 }
2196
2197 /* Returns true if incrementing the induction variable at the end of the LOOP
2198    is allowed.
2199
2200    The purpose is to avoid splitting latch edge with a biv increment, thus
2201    creating a jump, possibly confusing other optimization passes and leaving
2202    less freedom to scheduler.  So we allow IP_END_POS only if IP_NORMAL_POS
2203    is not available (so we do not have a better alternative), or if the latch
2204    edge is already nonempty.  */
2205
2206 static bool
2207 allow_ip_end_pos_p (struct loop *loop)
2208 {
2209   if (!ip_normal_pos (loop))
2210     return true;
2211
2212   if (!empty_block_p (ip_end_pos (loop)))
2213     return true;
2214
2215   return false;
2216 }
2217
2218 /* If possible, adds autoincrement candidates BASE + STEP * i based on use USE.
2219    Important field is set to IMPORTANT.  */
2220
2221 static void
2222 add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
2223                         bool important, struct iv_use *use)
2224 {
2225   basic_block use_bb = gimple_bb (use->stmt);
2226   enum machine_mode mem_mode;
2227   unsigned HOST_WIDE_INT cstepi;
2228
2229   /* If we insert the increment in any position other than the standard
2230      ones, we must ensure that it is incremented once per iteration.
2231      It must not be in an inner nested loop, or one side of an if
2232      statement.  */
2233   if (use_bb->loop_father != data->current_loop
2234       || !dominated_by_p (CDI_DOMINATORS, data->current_loop->latch, use_bb)
2235       || stmt_could_throw_p (use->stmt)
2236       || !cst_and_fits_in_hwi (step))
2237     return;
2238
2239   cstepi = int_cst_value (step);
2240
2241   mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
2242   if ((HAVE_PRE_INCREMENT && GET_MODE_SIZE (mem_mode) == cstepi)
2243       || (HAVE_PRE_DECREMENT && GET_MODE_SIZE (mem_mode) == -cstepi))
2244     {
2245       enum tree_code code = MINUS_EXPR;
2246       tree new_base;
2247       tree new_step = step;
2248
2249       if (POINTER_TYPE_P (TREE_TYPE (base)))
2250         {
2251           new_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
2252           code = POINTER_PLUS_EXPR;
2253         }
2254       else
2255         new_step = fold_convert (TREE_TYPE (base), new_step);
2256       new_base = fold_build2 (code, TREE_TYPE (base), base, new_step);
2257       add_candidate_1 (data, new_base, step, important, IP_BEFORE_USE, use,
2258                        use->stmt);
2259     }
2260   if ((HAVE_POST_INCREMENT && GET_MODE_SIZE (mem_mode) == cstepi)
2261       || (HAVE_POST_DECREMENT && GET_MODE_SIZE (mem_mode) == -cstepi))
2262     {
2263       add_candidate_1 (data, base, step, important, IP_AFTER_USE, use,
2264                        use->stmt);
2265     }
2266 }
2267
2268 /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
2269    position to POS.  If USE is not NULL, the candidate is set as related to
2270    it.  The candidate computation is scheduled on all available positions.  */
2271
2272 static void
2273 add_candidate (struct ivopts_data *data,
2274                tree base, tree step, bool important, struct iv_use *use)
2275 {
2276   if (ip_normal_pos (data->current_loop))
2277     add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL);
2278   if (ip_end_pos (data->current_loop)
2279       && allow_ip_end_pos_p (data->current_loop))
2280     add_candidate_1 (data, base, step, important, IP_END, use, NULL);
2281
2282   if (use != NULL && use->type == USE_ADDRESS)
2283     add_autoinc_candidates (data, base, step, important, use);
2284 }
2285
2286 /* Add a standard "0 + 1 * iteration" iv candidate for a
2287    type with SIZE bits.  */
2288
2289 static void
2290 add_standard_iv_candidates_for_size (struct ivopts_data *data,
2291                                      unsigned int size)
2292 {
2293   tree type = lang_hooks.types.type_for_size (size, true);
2294   add_candidate (data, build_int_cst (type, 0), build_int_cst (type, 1),
2295                  true, NULL);
2296 }
2297
2298 /* Adds standard iv candidates.  */
2299
2300 static void
2301 add_standard_iv_candidates (struct ivopts_data *data)
2302 {
2303   add_standard_iv_candidates_for_size (data, INT_TYPE_SIZE);
2304
2305   /* The same for a double-integer type if it is still fast enough.  */
2306   if (BITS_PER_WORD >= INT_TYPE_SIZE * 2)
2307     add_standard_iv_candidates_for_size (data, INT_TYPE_SIZE * 2);
2308 }
2309
2310
2311 /* Adds candidates bases on the old induction variable IV.  */
2312
2313 static void
2314 add_old_iv_candidates (struct ivopts_data *data, struct iv *iv)
2315 {
2316   gimple phi;
2317   tree def;
2318   struct iv_cand *cand;
2319
2320   add_candidate (data, iv->base, iv->step, true, NULL);
2321
2322   /* The same, but with initial value zero.  */
2323   if (POINTER_TYPE_P (TREE_TYPE (iv->base)))
2324     add_candidate (data, size_int (0), iv->step, true, NULL);
2325   else
2326     add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
2327                    iv->step, true, NULL);
2328
2329   phi = SSA_NAME_DEF_STMT (iv->ssa_name);
2330   if (gimple_code (phi) == GIMPLE_PHI)
2331     {
2332       /* Additionally record the possibility of leaving the original iv
2333          untouched.  */
2334       def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
2335       cand = add_candidate_1 (data,
2336                               iv->base, iv->step, true, IP_ORIGINAL, NULL,
2337                               SSA_NAME_DEF_STMT (def));
2338       cand->var_before = iv->ssa_name;
2339       cand->var_after = def;
2340     }
2341 }
2342
2343 /* Adds candidates based on the old induction variables.  */
2344
2345 static void
2346 add_old_ivs_candidates (struct ivopts_data *data)
2347 {
2348   unsigned i;
2349   struct iv *iv;
2350   bitmap_iterator bi;
2351
2352   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
2353     {
2354       iv = ver_info (data, i)->iv;
2355       if (iv && iv->biv_p && !integer_zerop (iv->step))
2356         add_old_iv_candidates (data, iv);
2357     }
2358 }
2359
2360 /* Adds candidates based on the value of the induction variable IV and USE.  */
2361
2362 static void
2363 add_iv_value_candidates (struct ivopts_data *data,
2364                          struct iv *iv, struct iv_use *use)
2365 {
2366   unsigned HOST_WIDE_INT offset;
2367   tree base;
2368   tree basetype;
2369
2370   add_candidate (data, iv->base, iv->step, false, use);
2371
2372   /* The same, but with initial value zero.  Make such variable important,
2373      since it is generic enough so that possibly many uses may be based
2374      on it.  */
2375   basetype = TREE_TYPE (iv->base);
2376   if (POINTER_TYPE_P (basetype))
2377     basetype = sizetype;
2378   add_candidate (data, build_int_cst (basetype, 0),
2379                  iv->step, true, use);
2380
2381   /* Third, try removing the constant offset.  Make sure to even
2382      add a candidate for &a[0] vs. (T *)&a.  */
2383   base = strip_offset (iv->base, &offset);
2384   if (offset
2385       || base != iv->base)
2386     add_candidate (data, base, iv->step, false, use);
2387 }
2388
2389 /* Adds candidates based on the uses.  */
2390
2391 static void
2392 add_derived_ivs_candidates (struct ivopts_data *data)
2393 {
2394   unsigned i;
2395
2396   for (i = 0; i < n_iv_uses (data); i++)
2397     {
2398       struct iv_use *use = iv_use (data, i);
2399
2400       if (!use)
2401         continue;
2402
2403       switch (use->type)
2404         {
2405         case USE_NONLINEAR_EXPR:
2406         case USE_COMPARE:
2407         case USE_ADDRESS:
2408           /* Just add the ivs based on the value of the iv used here.  */
2409           add_iv_value_candidates (data, use->iv, use);
2410           break;
2411
2412         default:
2413           gcc_unreachable ();
2414         }
2415     }
2416 }
2417
2418 /* Record important candidates and add them to related_cands bitmaps
2419    if needed.  */
2420
2421 static void
2422 record_important_candidates (struct ivopts_data *data)
2423 {
2424   unsigned i;
2425   struct iv_use *use;
2426
2427   for (i = 0; i < n_iv_cands (data); i++)
2428     {
2429       struct iv_cand *cand = iv_cand (data, i);
2430
2431       if (cand->important)
2432         bitmap_set_bit (data->important_candidates, i);
2433     }
2434
2435   data->consider_all_candidates = (n_iv_cands (data)
2436                                    <= CONSIDER_ALL_CANDIDATES_BOUND);
2437
2438   if (data->consider_all_candidates)
2439     {
2440       /* We will not need "related_cands" bitmaps in this case,
2441          so release them to decrease peak memory consumption.  */
2442       for (i = 0; i < n_iv_uses (data); i++)
2443         {
2444           use = iv_use (data, i);
2445           BITMAP_FREE (use->related_cands);
2446         }
2447     }
2448   else
2449     {
2450       /* Add important candidates to the related_cands bitmaps.  */
2451       for (i = 0; i < n_iv_uses (data); i++)
2452         bitmap_ior_into (iv_use (data, i)->related_cands,
2453                          data->important_candidates);
2454     }
2455 }
2456
2457 /* Allocates the data structure mapping the (use, candidate) pairs to costs.
2458    If consider_all_candidates is true, we use a two-dimensional array, otherwise
2459    we allocate a simple list to every use.  */
2460
2461 static void
2462 alloc_use_cost_map (struct ivopts_data *data)
2463 {
2464   unsigned i, size, s, j;
2465
2466   for (i = 0; i < n_iv_uses (data); i++)
2467     {
2468       struct iv_use *use = iv_use (data, i);
2469       bitmap_iterator bi;
2470
2471       if (data->consider_all_candidates)
2472         size = n_iv_cands (data);
2473       else
2474         {
2475           s = 0;
2476           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j, bi)
2477             {
2478               s++;
2479             }
2480
2481           /* Round up to the power of two, so that moduling by it is fast.  */
2482           for (size = 1; size < s; size <<= 1)
2483             continue;
2484         }
2485
2486       use->n_map_members = size;
2487       use->cost_map = XCNEWVEC (struct cost_pair, size);
2488     }
2489 }
2490
2491 /* Returns description of computation cost of expression whose runtime
2492    cost is RUNTIME and complexity corresponds to COMPLEXITY.  */
2493
2494 static comp_cost
2495 new_cost (unsigned runtime, unsigned complexity)
2496 {
2497   comp_cost cost;
2498
2499   cost.cost = runtime;
2500   cost.complexity = complexity;
2501
2502   return cost;
2503 }
2504
2505 /* Adds costs COST1 and COST2.  */
2506
2507 static comp_cost
2508 add_costs (comp_cost cost1, comp_cost cost2)
2509 {
2510   cost1.cost += cost2.cost;
2511   cost1.complexity += cost2.complexity;
2512
2513   return cost1;
2514 }
2515 /* Subtracts costs COST1 and COST2.  */
2516
2517 static comp_cost
2518 sub_costs (comp_cost cost1, comp_cost cost2)
2519 {
2520   cost1.cost -= cost2.cost;
2521   cost1.complexity -= cost2.complexity;
2522
2523   return cost1;
2524 }
2525
2526 /* Returns a negative number if COST1 < COST2, a positive number if
2527    COST1 > COST2, and 0 if COST1 = COST2.  */
2528
2529 static int
2530 compare_costs (comp_cost cost1, comp_cost cost2)
2531 {
2532   if (cost1.cost == cost2.cost)
2533     return cost1.complexity - cost2.complexity;
2534
2535   return cost1.cost - cost2.cost;
2536 }
2537
2538 /* Returns true if COST is infinite.  */
2539
2540 static bool
2541 infinite_cost_p (comp_cost cost)
2542 {
2543   return cost.cost == INFTY;
2544 }
2545
2546 /* Sets cost of (USE, CANDIDATE) pair to COST and record that it depends
2547    on invariants DEPENDS_ON and that the value used in expressing it
2548    is VALUE.  */
2549
2550 static void
2551 set_use_iv_cost (struct ivopts_data *data,
2552                  struct iv_use *use, struct iv_cand *cand,
2553                  comp_cost cost, bitmap depends_on, tree value)
2554 {
2555   unsigned i, s;
2556
2557   if (infinite_cost_p (cost))
2558     {
2559       BITMAP_FREE (depends_on);
2560       return;
2561     }
2562
2563   if (data->consider_all_candidates)
2564     {
2565       use->cost_map[cand->id].cand = cand;
2566       use->cost_map[cand->id].cost = cost;
2567       use->cost_map[cand->id].depends_on = depends_on;
2568       use->cost_map[cand->id].value = value;
2569       return;
2570     }
2571
2572   /* n_map_members is a power of two, so this computes modulo.  */
2573   s = cand->id & (use->n_map_members - 1);
2574   for (i = s; i < use->n_map_members; i++)
2575     if (!use->cost_map[i].cand)
2576       goto found;
2577   for (i = 0; i < s; i++)
2578     if (!use->cost_map[i].cand)
2579       goto found;
2580
2581   gcc_unreachable ();
2582
2583 found:
2584   use->cost_map[i].cand = cand;
2585   use->cost_map[i].cost = cost;
2586   use->cost_map[i].depends_on = depends_on;
2587   use->cost_map[i].value = value;
2588 }
2589
2590 /* Gets cost of (USE, CANDIDATE) pair.  */
2591
2592 static struct cost_pair *
2593 get_use_iv_cost (struct ivopts_data *data, struct iv_use *use,
2594                  struct iv_cand *cand)
2595 {
2596   unsigned i, s;
2597   struct cost_pair *ret;
2598
2599   if (!cand)
2600     return NULL;
2601
2602   if (data->consider_all_candidates)
2603     {
2604       ret = use->cost_map + cand->id;
2605       if (!ret->cand)
2606         return NULL;
2607
2608       return ret;
2609     }
2610
2611   /* n_map_members is a power of two, so this computes modulo.  */
2612   s = cand->id & (use->n_map_members - 1);
2613   for (i = s; i < use->n_map_members; i++)
2614     if (use->cost_map[i].cand == cand)
2615       return use->cost_map + i;
2616
2617   for (i = 0; i < s; i++)
2618     if (use->cost_map[i].cand == cand)
2619       return use->cost_map + i;
2620
2621   return NULL;
2622 }
2623
2624 /* Returns estimate on cost of computing SEQ.  */
2625
2626 static unsigned
2627 seq_cost (rtx seq, bool speed)
2628 {
2629   unsigned cost = 0;
2630   rtx set;
2631
2632   for (; seq; seq = NEXT_INSN (seq))
2633     {
2634       set = single_set (seq);
2635       if (set)
2636         cost += rtx_cost (set, SET,speed);
2637       else
2638         cost++;
2639     }
2640
2641   return cost;
2642 }
2643
2644 /* Produce DECL_RTL for object obj so it looks like it is stored in memory.  */
2645 static rtx
2646 produce_memory_decl_rtl (tree obj, int *regno)
2647 {
2648   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (obj));
2649   enum machine_mode address_mode = targetm.addr_space.address_mode (as);
2650   rtx x;
2651
2652   gcc_assert (obj);
2653   if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
2654     {
2655       const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
2656       x = gen_rtx_SYMBOL_REF (address_mode, name);
2657       SET_SYMBOL_REF_DECL (x, obj);
2658       x = gen_rtx_MEM (DECL_MODE (obj), x);
2659       set_mem_addr_space (x, as);
2660       targetm.encode_section_info (obj, x, true);
2661     }
2662   else
2663     {
2664       x = gen_raw_REG (address_mode, (*regno)++);
2665       x = gen_rtx_MEM (DECL_MODE (obj), x);
2666       set_mem_addr_space (x, as);
2667     }
2668
2669   return x;
2670 }
2671
2672 /* Prepares decl_rtl for variables referred in *EXPR_P.  Callback for
2673    walk_tree.  DATA contains the actual fake register number.  */
2674
2675 static tree
2676 prepare_decl_rtl (tree *expr_p, int *ws, void *data)
2677 {
2678   tree obj = NULL_TREE;
2679   rtx x = NULL_RTX;
2680   int *regno = (int *) data;
2681
2682   switch (TREE_CODE (*expr_p))
2683     {
2684     case ADDR_EXPR:
2685       for (expr_p = &TREE_OPERAND (*expr_p, 0);
2686            handled_component_p (*expr_p);
2687            expr_p = &TREE_OPERAND (*expr_p, 0))
2688         continue;
2689       obj = *expr_p;
2690       if (DECL_P (obj) && !DECL_RTL_SET_P (obj))
2691         x = produce_memory_decl_rtl (obj, regno);
2692       break;
2693
2694     case SSA_NAME:
2695       *ws = 0;
2696       obj = SSA_NAME_VAR (*expr_p);
2697       if (!DECL_RTL_SET_P (obj))
2698         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
2699       break;
2700
2701     case VAR_DECL:
2702     case PARM_DECL:
2703     case RESULT_DECL:
2704       *ws = 0;
2705       obj = *expr_p;
2706
2707       if (DECL_RTL_SET_P (obj))
2708         break;
2709
2710       if (DECL_MODE (obj) == BLKmode)
2711         x = produce_memory_decl_rtl (obj, regno);
2712       else
2713         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
2714
2715       break;
2716
2717     default:
2718       break;
2719     }
2720
2721   if (x)
2722     {
2723       VEC_safe_push (tree, heap, decl_rtl_to_reset, obj);
2724       SET_DECL_RTL (obj, x);
2725     }
2726
2727   return NULL_TREE;
2728 }
2729
2730 /* Determines cost of the computation of EXPR.  */
2731
2732 static unsigned
2733 computation_cost (tree expr, bool speed)
2734 {
2735   rtx seq, rslt;
2736   tree type = TREE_TYPE (expr);
2737   unsigned cost;
2738   /* Avoid using hard regs in ways which may be unsupported.  */
2739   int regno = LAST_VIRTUAL_REGISTER + 1;
2740   struct cgraph_node *node = cgraph_node (current_function_decl);
2741   enum node_frequency real_frequency = node->frequency;
2742
2743   node->frequency = NODE_FREQUENCY_NORMAL;
2744   crtl->maybe_hot_insn_p = speed;
2745   walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
2746   start_sequence ();
2747   rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
2748   seq = get_insns ();
2749   end_sequence ();
2750   default_rtl_profile ();
2751   node->frequency = real_frequency;
2752
2753   cost = seq_cost (seq, speed);
2754   if (MEM_P (rslt))
2755     cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type),
2756                           TYPE_ADDR_SPACE (type), speed);
2757
2758   return cost;
2759 }
2760
2761 /* Returns variable containing the value of candidate CAND at statement AT.  */
2762
2763 static tree
2764 var_at_stmt (struct loop *loop, struct iv_cand *cand, gimple stmt)
2765 {
2766   if (stmt_after_increment (loop, cand, stmt))
2767     return cand->var_after;
2768   else
2769     return cand->var_before;
2770 }
2771
2772 /* Return the most significant (sign) bit of T.  Similar to tree_int_cst_msb,
2773    but the bit is determined from TYPE_PRECISION, not MODE_BITSIZE.  */
2774
2775 int
2776 tree_int_cst_sign_bit (const_tree t)
2777 {
2778   unsigned bitno = TYPE_PRECISION (TREE_TYPE (t)) - 1;
2779   unsigned HOST_WIDE_INT w;
2780
2781   if (bitno < HOST_BITS_PER_WIDE_INT)
2782     w = TREE_INT_CST_LOW (t);
2783   else
2784     {
2785       w = TREE_INT_CST_HIGH (t);
2786       bitno -= HOST_BITS_PER_WIDE_INT;
2787     }
2788
2789   return (w >> bitno) & 1;
2790 }
2791
2792 /* If A is (TYPE) BA and B is (TYPE) BB, and the types of BA and BB have the
2793    same precision that is at least as wide as the precision of TYPE, stores
2794    BA to A and BB to B, and returns the type of BA.  Otherwise, returns the
2795    type of A and B.  */
2796
2797 static tree
2798 determine_common_wider_type (tree *a, tree *b)
2799 {
2800   tree wider_type = NULL;
2801   tree suba, subb;
2802   tree atype = TREE_TYPE (*a);
2803
2804   if (CONVERT_EXPR_P (*a))
2805     {
2806       suba = TREE_OPERAND (*a, 0);
2807       wider_type = TREE_TYPE (suba);
2808       if (TYPE_PRECISION (wider_type) < TYPE_PRECISION (atype))
2809         return atype;
2810     }
2811   else
2812     return atype;
2813
2814   if (CONVERT_EXPR_P (*b))
2815     {
2816       subb = TREE_OPERAND (*b, 0);
2817       if (TYPE_PRECISION (wider_type) != TYPE_PRECISION (TREE_TYPE (subb)))
2818         return atype;
2819     }
2820   else
2821     return atype;
2822
2823   *a = suba;
2824   *b = subb;
2825   return wider_type;
2826 }
2827
2828 /* Determines the expression by that USE is expressed from induction variable
2829    CAND at statement AT in LOOP.  The expression is stored in a decomposed
2830    form into AFF.  Returns false if USE cannot be expressed using CAND.  */
2831
2832 static bool
2833 get_computation_aff (struct loop *loop,
2834                      struct iv_use *use, struct iv_cand *cand, gimple at,
2835                      struct affine_tree_combination *aff)
2836 {
2837   tree ubase = use->iv->base;
2838   tree ustep = use->iv->step;
2839   tree cbase = cand->iv->base;
2840   tree cstep = cand->iv->step, cstep_common;
2841   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
2842   tree common_type, var;
2843   tree uutype;
2844   aff_tree cbase_aff, var_aff;
2845   double_int rat;
2846
2847   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
2848     {
2849       /* We do not have a precision to express the values of use.  */
2850       return false;
2851     }
2852
2853   var = var_at_stmt (loop, cand, at);
2854   uutype = unsigned_type_for (utype);
2855
2856   /* If the conversion is not noop, perform it.  */
2857   if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
2858     {
2859       cstep = fold_convert (uutype, cstep);
2860       cbase = fold_convert (uutype, cbase);
2861       var = fold_convert (uutype, var);
2862     }
2863
2864   if (!constant_multiple_of (ustep, cstep, &rat))
2865     return false;
2866
2867   /* In case both UBASE and CBASE are shortened to UUTYPE from some common
2868      type, we achieve better folding by computing their difference in this
2869      wider type, and cast the result to UUTYPE.  We do not need to worry about
2870      overflows, as all the arithmetics will in the end be performed in UUTYPE
2871      anyway.  */
2872   common_type = determine_common_wider_type (&ubase, &cbase);
2873
2874   /* use = ubase - ratio * cbase + ratio * var.  */
2875   tree_to_aff_combination (ubase, common_type, aff);
2876   tree_to_aff_combination (cbase, common_type, &cbase_aff);
2877   tree_to_aff_combination (var, uutype, &var_aff);
2878
2879   /* We need to shift the value if we are after the increment.  */
2880   if (stmt_after_increment (loop, cand, at))
2881     {
2882       aff_tree cstep_aff;
2883
2884       if (common_type != uutype)
2885         cstep_common = fold_convert (common_type, cstep);
2886       else
2887         cstep_common = cstep;
2888
2889       tree_to_aff_combination (cstep_common, common_type, &cstep_aff);
2890       aff_combination_add (&cbase_aff, &cstep_aff);
2891     }
2892
2893   aff_combination_scale (&cbase_aff, double_int_neg (rat));
2894   aff_combination_add (aff, &cbase_aff);
2895   if (common_type != uutype)
2896     aff_combination_convert (aff, uutype);
2897
2898   aff_combination_scale (&var_aff, rat);
2899   aff_combination_add (aff, &var_aff);
2900
2901   return true;
2902 }
2903
2904 /* Determines the expression by that USE is expressed from induction variable
2905    CAND at statement AT in LOOP.  The computation is unshared.  */
2906
2907 static tree
2908 get_computation_at (struct loop *loop,
2909                     struct iv_use *use, struct iv_cand *cand, gimple at)
2910 {
2911   aff_tree aff;
2912   tree type = TREE_TYPE (use->iv->base);
2913
2914   if (!get_computation_aff (loop, use, cand, at, &aff))
2915     return NULL_TREE;
2916   unshare_aff_combination (&aff);
2917   return fold_convert (type, aff_combination_to_tree (&aff));
2918 }
2919
2920 /* Determines the expression by that USE is expressed from induction variable
2921    CAND in LOOP.  The computation is unshared.  */
2922
2923 static tree
2924 get_computation (struct loop *loop, struct iv_use *use, struct iv_cand *cand)
2925 {
2926   return get_computation_at (loop, use, cand, use->stmt);
2927 }
2928
2929 /* Returns cost of addition in MODE.  */
2930
2931 static unsigned
2932 add_cost (enum machine_mode mode, bool speed)
2933 {
2934   static unsigned costs[NUM_MACHINE_MODES];
2935   rtx seq;
2936   unsigned cost;
2937
2938   if (costs[mode])
2939     return costs[mode];
2940
2941   start_sequence ();
2942   force_operand (gen_rtx_fmt_ee (PLUS, mode,
2943                                  gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 1),
2944                                  gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 2)),
2945                  NULL_RTX);
2946   seq = get_insns ();
2947   end_sequence ();
2948
2949   cost = seq_cost (seq, speed);
2950   if (!cost)
2951     cost = 1;
2952
2953   costs[mode] = cost;
2954
2955   if (dump_file && (dump_flags & TDF_DETAILS))
2956     fprintf (dump_file, "Addition in %s costs %d\n",
2957              GET_MODE_NAME (mode), cost);
2958   return cost;
2959 }
2960
2961 /* Entry in a hashtable of already known costs for multiplication.  */
2962 struct mbc_entry
2963 {
2964   HOST_WIDE_INT cst;            /* The constant to multiply by.  */
2965   enum machine_mode mode;       /* In mode.  */
2966   unsigned cost;                /* The cost.  */
2967 };
2968
2969 /* Counts hash value for the ENTRY.  */
2970
2971 static hashval_t
2972 mbc_entry_hash (const void *entry)
2973 {
2974   const struct mbc_entry *e = (const struct mbc_entry *) entry;
2975
2976   return 57 * (hashval_t) e->mode + (hashval_t) (e->cst % 877);
2977 }
2978
2979 /* Compares the hash table entries ENTRY1 and ENTRY2.  */
2980
2981 static int
2982 mbc_entry_eq (const void *entry1, const void *entry2)
2983 {
2984   const struct mbc_entry *e1 = (const struct mbc_entry *) entry1;
2985   const struct mbc_entry *e2 = (const struct mbc_entry *) entry2;
2986
2987   return (e1->mode == e2->mode
2988           && e1->cst == e2->cst);
2989 }
2990
2991 /* Returns cost of multiplication by constant CST in MODE.  */
2992
2993 unsigned
2994 multiply_by_cost (HOST_WIDE_INT cst, enum machine_mode mode, bool speed)
2995 {
2996   static htab_t costs;
2997   struct mbc_entry **cached, act;
2998   rtx seq;
2999   unsigned cost;
3000
3001   if (!costs)
3002     costs = htab_create (100, mbc_entry_hash, mbc_entry_eq, free);
3003
3004   act.mode = mode;
3005   act.cst = cst;
3006   cached = (struct mbc_entry **) htab_find_slot (costs, &act, INSERT);
3007   if (*cached)
3008     return (*cached)->cost;
3009
3010   *cached = XNEW (struct mbc_entry);
3011   (*cached)->mode = mode;
3012   (*cached)->cst = cst;
3013
3014   start_sequence ();
3015   expand_mult (mode, gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 1),
3016                gen_int_mode (cst, mode), NULL_RTX, 0);
3017   seq = get_insns ();
3018   end_sequence ();
3019
3020   cost = seq_cost (seq, speed);
3021
3022   if (dump_file && (dump_flags & TDF_DETAILS))
3023     fprintf (dump_file, "Multiplication by %d in %s costs %d\n",
3024              (int) cst, GET_MODE_NAME (mode), cost);
3025
3026   (*cached)->cost = cost;
3027
3028   return cost;
3029 }
3030
3031 /* Returns true if multiplying by RATIO is allowed in an address.  Test the
3032    validity for a memory reference accessing memory of mode MODE in
3033    address space AS.  */
3034
3035 DEF_VEC_P (sbitmap);
3036 DEF_VEC_ALLOC_P (sbitmap, heap);
3037
3038 bool
3039 multiplier_allowed_in_address_p (HOST_WIDE_INT ratio, enum machine_mode mode,
3040                                  addr_space_t as)
3041 {
3042 #define MAX_RATIO 128
3043   unsigned int data_index = (int) as * MAX_MACHINE_MODE + (int) mode;
3044   static VEC (sbitmap, heap) *valid_mult_list;
3045   sbitmap valid_mult;
3046
3047   if (data_index >= VEC_length (sbitmap, valid_mult_list))
3048     VEC_safe_grow_cleared (sbitmap, heap, valid_mult_list, data_index + 1);
3049
3050   valid_mult = VEC_index (sbitmap, valid_mult_list, data_index);
3051   if (!valid_mult)
3052     {
3053       enum machine_mode address_mode = targetm.addr_space.address_mode (as);
3054       rtx reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
3055       rtx addr;
3056       HOST_WIDE_INT i;
3057
3058       valid_mult = sbitmap_alloc (2 * MAX_RATIO + 1);
3059       sbitmap_zero (valid_mult);
3060       addr = gen_rtx_fmt_ee (MULT, address_mode, reg1, NULL_RTX);
3061       for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3062         {
3063           XEXP (addr, 1) = gen_int_mode (i, address_mode);
3064           if (memory_address_addr_space_p (mode, addr, as))
3065             SET_BIT (valid_mult, i + MAX_RATIO);
3066         }
3067
3068       if (dump_file && (dump_flags & TDF_DETAILS))
3069         {
3070           fprintf (dump_file, "  allowed multipliers:");
3071           for (i = -MAX_RATIO; i <= MAX_RATIO; i++)
3072             if (TEST_BIT (valid_mult, i + MAX_RATIO))
3073               fprintf (dump_file, " %d", (int) i);
3074           fprintf (dump_file, "\n");
3075           fprintf (dump_file, "\n");
3076         }
3077
3078       VEC_replace (sbitmap, valid_mult_list, data_index, valid_mult);
3079     }
3080
3081   if (ratio > MAX_RATIO || ratio < -MAX_RATIO)
3082     return false;
3083
3084   return TEST_BIT (valid_mult, ratio + MAX_RATIO);
3085 }
3086
3087 /* Returns cost of address in shape symbol + var + OFFSET + RATIO * index.
3088    If SYMBOL_PRESENT is false, symbol is omitted.  If VAR_PRESENT is false,
3089    variable is omitted.  Compute the cost for a memory reference that accesses
3090    a memory location of mode MEM_MODE in address space AS.
3091
3092    MAY_AUTOINC is set to true if the autoincrement (increasing index by
3093    size of MEM_MODE / RATIO) is available.  To make this determination, we
3094    look at the size of the increment to be made, which is given in CSTEP.
3095    CSTEP may be zero if the step is unknown.
3096    STMT_AFTER_INC is true iff the statement we're looking at is after the
3097    increment of the original biv.
3098
3099    TODO -- there must be some better way.  This all is quite crude.  */
3100
3101 typedef struct
3102 {
3103   HOST_WIDE_INT min_offset, max_offset;
3104   unsigned costs[2][2][2][2];
3105 } *address_cost_data;
3106
3107 DEF_VEC_P (address_cost_data);
3108 DEF_VEC_ALLOC_P (address_cost_data, heap);
3109
3110 static comp_cost
3111 get_address_cost (bool symbol_present, bool var_present,
3112                   unsigned HOST_WIDE_INT offset, HOST_WIDE_INT ratio,
3113                   HOST_WIDE_INT cstep, enum machine_mode mem_mode,
3114                   addr_space_t as, bool speed,
3115                   bool stmt_after_inc, bool *may_autoinc)
3116 {
3117   enum machine_mode address_mode = targetm.addr_space.address_mode (as);
3118   static VEC(address_cost_data, heap) *address_cost_data_list;
3119   unsigned int data_index = (int) as * MAX_MACHINE_MODE + (int) mem_mode;
3120   address_cost_data data;
3121   static bool has_preinc[MAX_MACHINE_MODE], has_postinc[MAX_MACHINE_MODE];
3122   static bool has_predec[MAX_MACHINE_MODE], has_postdec[MAX_MACHINE_MODE];
3123   unsigned cost, acost, complexity;
3124   bool offset_p, ratio_p, autoinc;
3125   HOST_WIDE_INT s_offset, autoinc_offset, msize;
3126   unsigned HOST_WIDE_INT mask;
3127   unsigned bits;
3128
3129   if (data_index >= VEC_length (address_cost_data, address_cost_data_list))
3130     VEC_safe_grow_cleared (address_cost_data, heap, address_cost_data_list,
3131                            data_index + 1);
3132
3133   data = VEC_index (address_cost_data, address_cost_data_list, data_index);
3134   if (!data)
3135     {
3136       HOST_WIDE_INT i;
3137       HOST_WIDE_INT start = BIGGEST_ALIGNMENT / BITS_PER_UNIT;
3138       HOST_WIDE_INT rat, off;
3139       int old_cse_not_expected;
3140       unsigned sym_p, var_p, off_p, rat_p, add_c;
3141       rtx seq, addr, base;
3142       rtx reg0, reg1;
3143
3144       data = (address_cost_data) xcalloc (1, sizeof (*data));
3145
3146       reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
3147
3148       addr = gen_rtx_fmt_ee (PLUS, address_mode, reg1, NULL_RTX);
3149       for (i = start; i <= 1 << 20; i <<= 1)
3150         {
3151           XEXP (addr, 1) = gen_int_mode (i, address_mode);
3152           if (!memory_address_addr_space_p (mem_mode, addr, as))
3153             break;
3154         }
3155       data->max_offset = i == start ? 0 : i >> 1;
3156       off = data->max_offset;
3157
3158       for (i = start; i <= 1 << 20; i <<= 1)
3159         {
3160           XEXP (addr, 1) = gen_int_mode (-i, address_mode);
3161           if (!memory_address_addr_space_p (mem_mode, addr, as))
3162             break;
3163         }
3164       data->min_offset = i == start ? 0 : -(i >> 1);
3165
3166       if (dump_file && (dump_flags & TDF_DETAILS))
3167         {
3168           fprintf (dump_file, "get_address_cost:\n");
3169           fprintf (dump_file, "  min offset %s %d\n",
3170                    GET_MODE_NAME (mem_mode),
3171                    (int) data->min_offset);
3172           fprintf (dump_file, "  max offset %s %d\n",
3173                    GET_MODE_NAME (mem_mode),
3174                    (int) data->max_offset);
3175         }
3176
3177       rat = 1;
3178       for (i = 2; i <= MAX_RATIO; i++)
3179         if (multiplier_allowed_in_address_p (i, mem_mode, as))
3180           {
3181             rat = i;
3182             break;
3183           }
3184
3185       /* Compute the cost of various addressing modes.  */
3186       acost = 0;
3187       reg0 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 1);
3188       reg1 = gen_raw_REG (address_mode, LAST_VIRTUAL_REGISTER + 2);
3189
3190       if (HAVE_PRE_DECREMENT)
3191         {
3192           addr = gen_rtx_PRE_DEC (address_mode, reg0);
3193           has_predec[mem_mode]
3194             = memory_address_addr_space_p (mem_mode, addr, as);
3195         }
3196       if (HAVE_POST_DECREMENT)
3197         {
3198           addr = gen_rtx_POST_DEC (address_mode, reg0);
3199           has_postdec[mem_mode]
3200             = memory_address_addr_space_p (mem_mode, addr, as);
3201         }
3202       if (HAVE_PRE_INCREMENT)
3203         {
3204           addr = gen_rtx_PRE_INC (address_mode, reg0);
3205           has_preinc[mem_mode]
3206             = memory_address_addr_space_p (mem_mode, addr, as);
3207         }
3208       if (HAVE_POST_INCREMENT)
3209         {
3210           addr = gen_rtx_POST_INC (address_mode, reg0);
3211           has_postinc[mem_mode]
3212             = memory_address_addr_space_p (mem_mode, addr, as);
3213         }
3214       for (i = 0; i < 16; i++)
3215         {
3216           sym_p = i & 1;
3217           var_p = (i >> 1) & 1;
3218           off_p = (i >> 2) & 1;
3219           rat_p = (i >> 3) & 1;
3220
3221           addr = reg0;
3222           if (rat_p)
3223             addr = gen_rtx_fmt_ee (MULT, address_mode, addr,
3224                                    gen_int_mode (rat, address_mode));
3225
3226           if (var_p)
3227             addr = gen_rtx_fmt_ee (PLUS, address_mode, addr, reg1);
3228
3229           if (sym_p)
3230             {
3231               base = gen_rtx_SYMBOL_REF (address_mode, ggc_strdup (""));
3232               /* ??? We can run into trouble with some backends by presenting
3233                  it with symbols which haven't been properly passed through
3234                  targetm.encode_section_info.  By setting the local bit, we
3235                  enhance the probability of things working.  */
3236               SYMBOL_REF_FLAGS (base) = SYMBOL_FLAG_LOCAL;
3237
3238               if (off_p)
3239                 base = gen_rtx_fmt_e (CONST, address_mode,
3240                                       gen_rtx_fmt_ee
3241                                         (PLUS, address_mode, base,
3242                                          gen_int_mode (off, address_mode)));
3243             }
3244           else if (off_p)
3245             base = gen_int_mode (off, address_mode);
3246           else
3247             base = NULL_RTX;
3248
3249           if (base)
3250             addr = gen_rtx_fmt_ee (PLUS, address_mode, addr, base);
3251
3252           start_sequence ();
3253           /* To avoid splitting addressing modes, pretend that no cse will
3254              follow.  */
3255           old_cse_not_expected = cse_not_expected;
3256           cse_not_expected = true;
3257           addr = memory_address_addr_space (mem_mode, addr, as);
3258           cse_not_expected = old_cse_not_expected;
3259           seq = get_insns ();
3260           end_sequence ();
3261
3262           acost = seq_cost (seq, speed);
3263           acost += address_cost (addr, mem_mode, as, speed);
3264
3265           if (!acost)
3266             acost = 1;
3267           data->costs[sym_p][var_p][off_p][rat_p] = acost;
3268         }
3269
3270       /* On some targets, it is quite expensive to load symbol to a register,
3271          which makes addresses that contain symbols look much more expensive.
3272          However, the symbol will have to be loaded in any case before the
3273          loop (and quite likely we have it in register already), so it does not
3274          make much sense to penalize them too heavily.  So make some final
3275          tweaks for the SYMBOL_PRESENT modes:
3276
3277          If VAR_PRESENT is false, and the mode obtained by changing symbol to
3278          var is cheaper, use this mode with small penalty.
3279          If VAR_PRESENT is true, try whether the mode with
3280          SYMBOL_PRESENT = false is cheaper even with cost of addition, and
3281          if this is the case, use it.  */
3282       add_c = add_cost (address_mode, speed);
3283       for (i = 0; i < 8; i++)
3284         {
3285           var_p = i & 1;
3286           off_p = (i >> 1) & 1;
3287           rat_p = (i >> 2) & 1;
3288
3289           acost = data->costs[0][1][off_p][rat_p] + 1;
3290           if (var_p)
3291             acost += add_c;
3292
3293           if (acost < data->costs[1][var_p][off_p][rat_p])
3294             data->costs[1][var_p][off_p][rat_p] = acost;
3295         }
3296
3297       if (dump_file && (dump_flags & TDF_DETAILS))
3298         {
3299           fprintf (dump_file, "Address costs:\n");
3300
3301           for (i = 0; i < 16; i++)
3302             {
3303               sym_p = i & 1;
3304               var_p = (i >> 1) & 1;
3305               off_p = (i >> 2) & 1;
3306               rat_p = (i >> 3) & 1;
3307
3308               fprintf (dump_file, "  ");
3309               if (sym_p)
3310                 fprintf (dump_file, "sym + ");
3311               if (var_p)
3312                 fprintf (dump_file, "var + ");
3313               if (off_p)
3314                 fprintf (dump_file, "cst + ");
3315               if (rat_p)
3316                 fprintf (dump_file, "rat * ");
3317
3318               acost = data->costs[sym_p][var_p][off_p][rat_p];
3319               fprintf (dump_file, "index costs %d\n", acost);
3320             }
3321           if (has_predec[mem_mode] || has_postdec[mem_mode]
3322               || has_preinc[mem_mode] || has_postinc[mem_mode])
3323             fprintf (dump_file, "  May include autoinc/dec\n");
3324           fprintf (dump_file, "\n");
3325         }
3326
3327       VEC_replace (address_cost_data, address_cost_data_list,
3328                    data_index, data);
3329     }
3330
3331   bits = GET_MODE_BITSIZE (address_mode);
3332   mask = ~(~(unsigned HOST_WIDE_INT) 0 << (bits - 1) << 1);
3333   offset &= mask;
3334   if ((offset >> (bits - 1) & 1))
3335     offset |= ~mask;
3336   s_offset = offset;
3337
3338   autoinc = false;
3339   msize = GET_MODE_SIZE (mem_mode);
3340   autoinc_offset = offset;
3341   if (stmt_after_inc)
3342     autoinc_offset += ratio * cstep;
3343   if (symbol_present || var_present || ratio != 1)
3344     autoinc = false;
3345   else if ((has_postinc[mem_mode] && autoinc_offset == 0
3346                && msize == cstep)
3347            || (has_postdec[mem_mode] && autoinc_offset == 0
3348                && msize == -cstep)
3349            || (has_preinc[mem_mode] && autoinc_offset == msize
3350                && msize == cstep)
3351            || (has_predec[mem_mode] && autoinc_offset == -msize
3352                && msize == -cstep))
3353     autoinc = true;
3354
3355   cost = 0;
3356   offset_p = (s_offset != 0
3357               && data->min_offset <= s_offset
3358               && s_offset <= data->max_offset);
3359   ratio_p = (ratio != 1
3360              && multiplier_allowed_in_address_p (ratio, mem_mode, as));
3361
3362   if (ratio != 1 && !ratio_p)
3363     cost += multiply_by_cost (ratio, address_mode, speed);
3364
3365   if (s_offset && !offset_p && !symbol_present)
3366     cost += add_cost (address_mode, speed);
3367
3368   if (may_autoinc)
3369     *may_autoinc = autoinc;
3370   acost = data->costs[symbol_present][var_present][offset_p][ratio_p];
3371   complexity = (symbol_present != 0) + (var_present != 0) + offset_p + ratio_p;
3372   return new_cost (cost + acost, complexity);
3373 }
3374
3375 /* Estimates cost of forcing expression EXPR into a variable.  */
3376
3377 static comp_cost
3378 force_expr_to_var_cost (tree expr, bool speed)
3379 {
3380   static bool costs_initialized = false;
3381   static unsigned integer_cost [2];
3382   static unsigned symbol_cost [2];
3383   static unsigned address_cost [2];
3384   tree op0, op1;
3385   comp_cost cost0, cost1, cost;
3386   enum machine_mode mode;
3387
3388   if (!costs_initialized)
3389     {
3390       tree type = build_pointer_type (integer_type_node);
3391       tree var, addr;
3392       rtx x;
3393       int i;
3394
3395       var = create_tmp_var_raw (integer_type_node, "test_var");
3396       TREE_STATIC (var) = 1;
3397       x = produce_memory_decl_rtl (var, NULL);
3398       SET_DECL_RTL (var, x);
3399
3400       addr = build1 (ADDR_EXPR, type, var);
3401
3402
3403       for (i = 0; i < 2; i++)
3404         {
3405           integer_cost[i] = computation_cost (build_int_cst (integer_type_node,
3406                                                              2000), i);
3407
3408           symbol_cost[i] = computation_cost (addr, i) + 1;
3409
3410           address_cost[i]
3411             = computation_cost (build2 (POINTER_PLUS_EXPR, type,
3412                                         addr,
3413                                         build_int_cst (sizetype, 2000)), i) + 1;
3414           if (dump_file && (dump_flags & TDF_DETAILS))
3415             {
3416               fprintf (dump_file, "force_expr_to_var_cost %s costs:\n", i ? "speed" : "size");
3417               fprintf (dump_file, "  integer %d\n", (int) integer_cost[i]);
3418               fprintf (dump_file, "  symbol %d\n", (int) symbol_cost[i]);
3419               fprintf (dump_file, "  address %d\n", (int) address_cost[i]);
3420               fprintf (dump_file, "  other %d\n", (int) target_spill_cost[i]);
3421               fprintf (dump_file, "\n");
3422             }
3423         }
3424
3425       costs_initialized = true;
3426     }
3427
3428   STRIP_NOPS (expr);
3429
3430   if (SSA_VAR_P (expr))
3431     return zero_cost;
3432
3433   if (is_gimple_min_invariant (expr))
3434     {
3435       if (TREE_CODE (expr) == INTEGER_CST)
3436         return new_cost (integer_cost [speed], 0);
3437
3438       if (TREE_CODE (expr) == ADDR_EXPR)
3439         {
3440           tree obj = TREE_OPERAND (expr, 0);
3441
3442           if (TREE_CODE (obj) == VAR_DECL
3443               || TREE_CODE (obj) == PARM_DECL
3444               || TREE_CODE (obj) == RESULT_DECL)
3445             return new_cost (symbol_cost [speed], 0);
3446         }
3447
3448       return new_cost (address_cost [speed], 0);
3449     }
3450
3451   switch (TREE_CODE (expr))
3452     {
3453     case POINTER_PLUS_EXPR:
3454     case PLUS_EXPR:
3455     case MINUS_EXPR:
3456     case MULT_EXPR:
3457       op0 = TREE_OPERAND (expr, 0);
3458       op1 = TREE_OPERAND (expr, 1);
3459       STRIP_NOPS (op0);
3460       STRIP_NOPS (op1);
3461
3462       if (is_gimple_val (op0))
3463         cost0 = zero_cost;
3464       else
3465         cost0 = force_expr_to_var_cost (op0, speed);
3466
3467       if (is_gimple_val (op1))
3468         cost1 = zero_cost;
3469       else
3470         cost1 = force_expr_to_var_cost (op1, speed);
3471
3472       break;
3473
3474     case NEGATE_EXPR:
3475       op0 = TREE_OPERAND (expr, 0);
3476       STRIP_NOPS (op0);
3477       op1 = NULL_TREE;
3478
3479       if (is_gimple_val (op0))
3480         cost0 = zero_cost;
3481       else
3482         cost0 = force_expr_to_var_cost (op0, speed);
3483
3484       cost1 = zero_cost;
3485       break;
3486
3487     default:
3488       /* Just an arbitrary value, FIXME.  */
3489       return new_cost (target_spill_cost[speed], 0);
3490     }
3491
3492   mode = TYPE_MODE (TREE_TYPE (expr));
3493   switch (TREE_CODE (expr))
3494     {
3495     case POINTER_PLUS_EXPR:
3496     case PLUS_EXPR:
3497     case MINUS_EXPR:
3498     case NEGATE_EXPR:
3499       cost = new_cost (add_cost (mode, speed), 0);
3500       break;
3501
3502     case MULT_EXPR:
3503       if (cst_and_fits_in_hwi (op0))
3504         cost = new_cost (multiply_by_cost (int_cst_value (op0), mode, speed), 0);
3505       else if (cst_and_fits_in_hwi (op1))
3506         cost = new_cost (multiply_by_cost (int_cst_value (op1), mode, speed), 0);
3507       else
3508         return new_cost (target_spill_cost [speed], 0);
3509       break;
3510
3511     default:
3512       gcc_unreachable ();
3513     }
3514
3515   cost = add_costs (cost, cost0);
3516   cost = add_costs (cost, cost1);
3517
3518   /* Bound the cost by target_spill_cost.  The parts of complicated
3519      computations often are either loop invariant or at least can
3520      be shared between several iv uses, so letting this grow without
3521      limits would not give reasonable results.  */
3522   if (cost.cost > (int) target_spill_cost [speed])
3523     cost.cost = target_spill_cost [speed];
3524
3525   return cost;
3526 }
3527
3528 /* Estimates cost of forcing EXPR into a variable.  DEPENDS_ON is a set of the
3529    invariants the computation depends on.  */
3530
3531 static comp_cost
3532 force_var_cost (struct ivopts_data *data,
3533                 tree expr, bitmap *depends_on)
3534 {
3535   if (depends_on)
3536     {
3537       fd_ivopts_data = data;
3538       walk_tree (&expr, find_depends, depends_on, NULL);
3539     }
3540
3541   return force_expr_to_var_cost (expr, data->speed);
3542 }
3543
3544 /* Estimates cost of expressing address ADDR  as var + symbol + offset.  The
3545    value of offset is added to OFFSET, SYMBOL_PRESENT and VAR_PRESENT are set
3546    to false if the corresponding part is missing.  DEPENDS_ON is a set of the
3547    invariants the computation depends on.  */
3548
3549 static comp_cost
3550 split_address_cost (struct ivopts_data *data,
3551                     tree addr, bool *symbol_present, bool *var_present,
3552                     unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3553 {
3554   tree core;
3555   HOST_WIDE_INT bitsize;
3556   HOST_WIDE_INT bitpos;
3557   tree toffset;
3558   enum machine_mode mode;
3559   int unsignedp, volatilep;
3560
3561   core = get_inner_reference (addr, &bitsize, &bitpos, &toffset, &mode,
3562                               &unsignedp, &volatilep, false);
3563
3564   if (toffset != 0
3565       || bitpos % BITS_PER_UNIT != 0
3566       || TREE_CODE (core) != VAR_DECL)
3567     {
3568       *symbol_present = false;
3569       *var_present = true;
3570       fd_ivopts_data = data;
3571       walk_tree (&addr, find_depends, depends_on, NULL);
3572       return new_cost (target_spill_cost[data->speed], 0);
3573     }
3574
3575   *offset += bitpos / BITS_PER_UNIT;
3576   if (TREE_STATIC (core)
3577       || DECL_EXTERNAL (core))
3578     {
3579       *symbol_present = true;
3580       *var_present = false;
3581       return zero_cost;
3582     }
3583
3584   *symbol_present = false;
3585   *var_present = true;
3586   return zero_cost;
3587 }
3588
3589 /* Estimates cost of expressing difference of addresses E1 - E2 as
3590    var + symbol + offset.  The value of offset is added to OFFSET,
3591    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
3592    part is missing.  DEPENDS_ON is a set of the invariants the computation
3593    depends on.  */
3594
3595 static comp_cost
3596 ptr_difference_cost (struct ivopts_data *data,
3597                      tree e1, tree e2, bool *symbol_present, bool *var_present,
3598                      unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3599 {
3600   HOST_WIDE_INT diff = 0;
3601   aff_tree aff_e1, aff_e2;
3602   tree type;
3603
3604   gcc_assert (TREE_CODE (e1) == ADDR_EXPR);
3605
3606   if (ptr_difference_const (e1, e2, &diff))
3607     {
3608       *offset += diff;
3609       *symbol_present = false;
3610       *var_present = false;
3611       return zero_cost;
3612     }
3613
3614   if (integer_zerop (e2))
3615     return split_address_cost (data, TREE_OPERAND (e1, 0),
3616                                symbol_present, var_present, offset, depends_on);
3617
3618   *symbol_present = false;
3619   *var_present = true;
3620
3621   type = signed_type_for (TREE_TYPE (e1));
3622   tree_to_aff_combination (e1, type, &aff_e1);
3623   tree_to_aff_combination (e2, type, &aff_e2);
3624   aff_combination_scale (&aff_e2, double_int_minus_one);
3625   aff_combination_add (&aff_e1, &aff_e2);
3626
3627   return force_var_cost (data, aff_combination_to_tree (&aff_e1), depends_on);
3628 }
3629
3630 /* Estimates cost of expressing difference E1 - E2 as
3631    var + symbol + offset.  The value of offset is added to OFFSET,
3632    SYMBOL_PRESENT and VAR_PRESENT are set to false if the corresponding
3633    part is missing.  DEPENDS_ON is a set of the invariants the computation
3634    depends on.  */
3635
3636 static comp_cost
3637 difference_cost (struct ivopts_data *data,
3638                  tree e1, tree e2, bool *symbol_present, bool *var_present,
3639                  unsigned HOST_WIDE_INT *offset, bitmap *depends_on)
3640 {
3641   enum machine_mode mode = TYPE_MODE (TREE_TYPE (e1));
3642   unsigned HOST_WIDE_INT off1, off2;
3643   aff_tree aff_e1, aff_e2;
3644   tree type;
3645
3646   e1 = strip_offset (e1, &off1);
3647   e2 = strip_offset (e2, &off2);
3648   *offset += off1 - off2;
3649
3650   STRIP_NOPS (e1);
3651   STRIP_NOPS (e2);
3652
3653   if (TREE_CODE (e1) == ADDR_EXPR)
3654     return ptr_difference_cost (data, e1, e2, symbol_present, var_present,
3655                                 offset, depends_on);
3656   *symbol_present = false;
3657
3658   if (operand_equal_p (e1, e2, 0))
3659     {
3660       *var_present = false;
3661       return zero_cost;
3662     }
3663
3664   *var_present = true;
3665
3666   if (integer_zerop (e2))
3667     return force_var_cost (data, e1, depends_on);
3668
3669   if (integer_zerop (e1))
3670     {
3671       comp_cost cost = force_var_cost (data, e2, depends_on);
3672       cost.cost += multiply_by_cost (-1, mode, data->speed);
3673       return cost;
3674     }
3675
3676   type = signed_type_for (TREE_TYPE (e1));
3677   tree_to_aff_combination (e1, type, &aff_e1);
3678   tree_to_aff_combination (e2, type, &aff_e2);
3679   aff_combination_scale (&aff_e2, double_int_minus_one);
3680   aff_combination_add (&aff_e1, &aff_e2);
3681
3682   return force_var_cost (data, aff_combination_to_tree (&aff_e1), depends_on);
3683 }
3684
3685 /* Determines the cost of the computation by that USE is expressed
3686    from induction variable CAND.  If ADDRESS_P is true, we just need
3687    to create an address from it, otherwise we want to get it into
3688    register.  A set of invariants we depend on is stored in
3689    DEPENDS_ON.  AT is the statement at that the value is computed.
3690    If CAN_AUTOINC is nonnull, use it to record whether autoinc
3691    addressing is likely.  */
3692
3693 static comp_cost
3694 get_computation_cost_at (struct ivopts_data *data,
3695                          struct iv_use *use, struct iv_cand *cand,
3696                          bool address_p, bitmap *depends_on, gimple at,
3697                          bool *can_autoinc)
3698 {
3699   tree ubase = use->iv->base, ustep = use->iv->step;
3700   tree cbase, cstep;
3701   tree utype = TREE_TYPE (ubase), ctype;
3702   unsigned HOST_WIDE_INT cstepi, offset = 0;
3703   HOST_WIDE_INT ratio, aratio;
3704   bool var_present, symbol_present, stmt_is_after_inc;
3705   comp_cost cost;
3706   double_int rat;
3707   bool speed = optimize_bb_for_speed_p (gimple_bb (at));
3708
3709   *depends_on = NULL;
3710
3711   /* Only consider real candidates.  */
3712   if (!cand->iv)
3713     return infinite_cost;
3714
3715   cbase = cand->iv->base;
3716   cstep = cand->iv->step;
3717   ctype = TREE_TYPE (cbase);
3718
3719   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
3720     {
3721       /* We do not have a precision to express the values of use.  */
3722       return infinite_cost;
3723     }
3724
3725   if (address_p)
3726     {
3727       /* Do not try to express address of an object with computation based
3728          on address of a different object.  This may cause problems in rtl
3729          level alias analysis (that does not expect this to be happening,
3730          as this is illegal in C), and would be unlikely to be useful
3731          anyway.  */
3732       if (use->iv->base_object
3733           && cand->iv->base_object
3734           && !operand_equal_p (use->iv->base_object, cand->iv->base_object, 0))
3735         return infinite_cost;
3736     }
3737
3738   if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
3739     {
3740       /* TODO -- add direct handling of this case.  */
3741       goto fallback;
3742     }
3743
3744   /* CSTEPI is removed from the offset in case statement is after the
3745      increment.  If the step is not constant, we use zero instead.
3746      This is a bit imprecise (there is the extra addition), but
3747      redundancy elimination is likely to transform the code so that
3748      it uses value of the variable before increment anyway,
3749      so it is not that much unrealistic.  */
3750   if (cst_and_fits_in_hwi (cstep))
3751     cstepi = int_cst_value (cstep);
3752   else
3753     cstepi = 0;
3754
3755   if (!constant_multiple_of (ustep, cstep, &rat))
3756     return infinite_cost;
3757
3758   if (double_int_fits_in_shwi_p (rat))
3759     ratio = double_int_to_shwi (rat);
3760   else
3761     return infinite_cost;
3762
3763   STRIP_NOPS (cbase);
3764   ctype = TREE_TYPE (cbase);
3765
3766   /* use = ubase + ratio * (var - cbase).  If either cbase is a constant
3767      or ratio == 1, it is better to handle this like
3768
3769      ubase - ratio * cbase + ratio * var
3770
3771      (also holds in the case ratio == -1, TODO.  */
3772
3773   if (cst_and_fits_in_hwi (cbase))
3774     {
3775       offset = - ratio * int_cst_value (cbase);
3776       cost = difference_cost (data,
3777                               ubase, build_int_cst (utype, 0),
3778                               &symbol_present, &var_present, &offset,
3779                               depends_on);
3780     }
3781   else if (ratio == 1)
3782     {
3783       cost = difference_cost (data,
3784                               ubase, cbase,
3785                               &symbol_present, &var_present, &offset,
3786                               depends_on);
3787     }
3788   else if (address_p
3789            && !POINTER_TYPE_P (ctype)
3790            && multiplier_allowed_in_address_p
3791                 (ratio, TYPE_MODE (TREE_TYPE (utype)),
3792                         TYPE_ADDR_SPACE (TREE_TYPE (utype))))
3793     {
3794       cbase
3795         = fold_build2 (MULT_EXPR, ctype, cbase, build_int_cst (ctype, ratio));
3796       cost = difference_cost (data,
3797                               ubase, cbase,
3798                               &symbol_present, &var_present, &offset,
3799                               depends_on);
3800     }
3801   else
3802     {
3803       cost = force_var_cost (data, cbase, depends_on);
3804       cost.cost += add_cost (TYPE_MODE (ctype), data->speed);
3805       cost = add_costs (cost,
3806                         difference_cost (data,
3807                                          ubase, build_int_cst (utype, 0),
3808                                          &symbol_present, &var_present,
3809                                          &offset, depends_on));
3810     }
3811
3812   /* If we are after the increment, the value of the candidate is higher by
3813      one iteration.  */
3814   stmt_is_after_inc = stmt_after_increment (data->current_loop, cand, at);
3815   if (stmt_is_after_inc)
3816     offset -= ratio * cstepi;
3817
3818   /* Now the computation is in shape symbol + var1 + const + ratio * var2.
3819      (symbol/var1/const parts may be omitted).  If we are looking for an
3820      address, find the cost of addressing this.  */
3821   if (address_p)
3822     return add_costs (cost,
3823                       get_address_cost (symbol_present, var_present,
3824                                         offset, ratio, cstepi,
3825                                         TYPE_MODE (TREE_TYPE (utype)),
3826                                         TYPE_ADDR_SPACE (TREE_TYPE (utype)),
3827                                         speed, stmt_is_after_inc,
3828                                         can_autoinc));
3829
3830   /* Otherwise estimate the costs for computing the expression.  */
3831   if (!symbol_present && !var_present && !offset)
3832     {
3833       if (ratio != 1)
3834         cost.cost += multiply_by_cost (ratio, TYPE_MODE (ctype), speed);
3835       return cost;
3836     }
3837
3838   /* Symbol + offset should be compile-time computable so consider that they
3839       are added once to the variable, if present.  */
3840   if (var_present && (symbol_present || offset))
3841     cost.cost += add_cost (TYPE_MODE (ctype), speed)
3842                  / AVG_LOOP_NITER (data->current_loop);
3843
3844   /* Having offset does not affect runtime cost in case it is added to
3845      symbol, but it increases complexity.  */
3846   if (offset)
3847     cost.complexity++;
3848
3849   cost.cost += add_cost (TYPE_MODE (ctype), speed);
3850
3851   aratio = ratio > 0 ? ratio : -ratio;
3852   if (aratio != 1)
3853     cost.cost += multiply_by_cost (aratio, TYPE_MODE (ctype), speed);
3854
3855 fallback:
3856   if (can_autoinc)
3857     *can_autoinc = false;
3858
3859   {
3860     /* Just get the expression, expand it and measure the cost.  */
3861     tree comp = get_computation_at (data->current_loop, use, cand, at);
3862
3863     if (!comp)
3864       return infinite_cost;
3865
3866     if (address_p)
3867       comp = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (comp)), comp);
3868
3869     return new_cost (computation_cost (comp, speed), 0);
3870   }
3871 }
3872
3873 /* Determines the cost of the computation by that USE is expressed
3874    from induction variable CAND.  If ADDRESS_P is true, we just need
3875    to create an address from it, otherwise we want to get it into
3876    register.  A set of invariants we depend on is stored in
3877    DEPENDS_ON.  If CAN_AUTOINC is nonnull, use it to record whether
3878    autoinc addressing is likely.  */
3879
3880 static comp_cost
3881 get_computation_cost (struct ivopts_data *data,
3882                       struct iv_use *use, struct iv_cand *cand,
3883                       bool address_p, bitmap *depends_on, bool *can_autoinc)
3884 {
3885   return get_computation_cost_at (data,
3886                                   use, cand, address_p, depends_on, use->stmt,
3887                                   can_autoinc);
3888 }
3889
3890 /* Determines cost of basing replacement of USE on CAND in a generic
3891    expression.  */
3892
3893 static bool
3894 determine_use_iv_cost_generic (struct ivopts_data *data,
3895                                struct iv_use *use, struct iv_cand *cand)
3896 {
3897   bitmap depends_on;
3898   comp_cost cost;
3899
3900   /* The simple case first -- if we need to express value of the preserved
3901      original biv, the cost is 0.  This also prevents us from counting the
3902      cost of increment twice -- once at this use and once in the cost of
3903      the candidate.  */
3904   if (cand->pos == IP_ORIGINAL
3905       && cand->incremented_at == use->stmt)
3906     {
3907       set_use_iv_cost (data, use, cand, zero_cost, NULL, NULL_TREE);
3908       return true;
3909     }
3910
3911   cost = get_computation_cost (data, use, cand, false, &depends_on, NULL);
3912   set_use_iv_cost (data, use, cand, cost, depends_on, NULL_TREE);
3913
3914   return !infinite_cost_p (cost);
3915 }
3916
3917 /* Determines cost of basing replacement of USE on CAND in an address.  */
3918
3919 static bool
3920 determine_use_iv_cost_address (struct ivopts_data *data,
3921                                struct iv_use *use, struct iv_cand *cand)
3922 {
3923   bitmap depends_on;
3924   bool can_autoinc;
3925   comp_cost cost = get_computation_cost (data, use, cand, true, &depends_on,
3926                                          &can_autoinc);
3927
3928   if (cand->ainc_use == use)
3929     {
3930       if (can_autoinc)
3931         cost.cost -= cand->cost_step;
3932       /* If we generated the candidate solely for exploiting autoincrement
3933          opportunities, and it turns out it can't be used, set the cost to
3934          infinity to make sure we ignore it.  */
3935       else if (cand->pos == IP_AFTER_USE || cand->pos == IP_BEFORE_USE)
3936         cost = infinite_cost;
3937     }
3938   set_use_iv_cost (data, use, cand, cost, depends_on, NULL_TREE);
3939
3940   return !infinite_cost_p (cost);
3941 }
3942
3943 /* Computes value of candidate CAND at position AT in iteration NITER, and
3944    stores it to VAL.  */
3945
3946 static void
3947 cand_value_at (struct loop *loop, struct iv_cand *cand, gimple at, tree niter,
3948                aff_tree *val)
3949 {
3950   aff_tree step, delta, nit;
3951   struct iv *iv = cand->iv;
3952   tree type = TREE_TYPE (iv->base);
3953   tree steptype = type;
3954   if (POINTER_TYPE_P (type))
3955     steptype = sizetype;
3956
3957   tree_to_aff_combination (iv->step, steptype, &step);
3958   tree_to_aff_combination (niter, TREE_TYPE (niter), &nit);
3959   aff_combination_convert (&nit, steptype);
3960   aff_combination_mult (&nit, &step, &delta);
3961   if (stmt_after_increment (loop, cand, at))
3962     aff_combination_add (&delta, &step);
3963
3964   tree_to_aff_combination (iv->base, type, val);
3965   aff_combination_add (val, &delta);
3966 }
3967
3968 /* Returns period of induction variable iv.  */
3969
3970 static tree
3971 iv_period (struct iv *iv)
3972 {
3973   tree step = iv->step, period, type;
3974   tree pow2div;
3975
3976   gcc_assert (step && TREE_CODE (step) == INTEGER_CST);
3977
3978   /* Period of the iv is gcd (step, type range).  Since type range is power
3979      of two, it suffices to determine the maximum power of two that divides
3980      step.  */
3981   pow2div = num_ending_zeros (step);
3982   type = unsigned_type_for (TREE_TYPE (step));
3983
3984   period = build_low_bits_mask (type,
3985                                 (TYPE_PRECISION (type)
3986                                  - tree_low_cst (pow2div, 1)));
3987
3988   return period;
3989 }
3990
3991 /* Returns the comparison operator used when eliminating the iv USE.  */
3992
3993 static enum tree_code
3994 iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
3995 {
3996   struct loop *loop = data->current_loop;
3997   basic_block ex_bb;
3998   edge exit;
3999
4000   ex_bb = gimple_bb (use->stmt);
4001   exit = EDGE_SUCC (ex_bb, 0);
4002   if (flow_bb_inside_loop_p (loop, exit->dest))
4003     exit = EDGE_SUCC (ex_bb, 1);
4004
4005   return (exit->flags & EDGE_TRUE_VALUE ? EQ_EXPR : NE_EXPR);
4006 }
4007
4008 /* Check whether it is possible to express the condition in USE by comparison
4009    of candidate CAND.  If so, store the value compared with to BOUND.  */
4010
4011 static bool
4012 may_eliminate_iv (struct ivopts_data *data,
4013                   struct iv_use *use, struct iv_cand *cand, tree *bound)
4014 {
4015   basic_block ex_bb;
4016   edge exit;
4017   tree nit, period;
4018   struct loop *loop = data->current_loop;
4019   aff_tree bnd;
4020
4021   if (TREE_CODE (cand->iv->step) != INTEGER_CST)
4022     return false;
4023
4024   /* For now works only for exits that dominate the loop latch.
4025      TODO: extend to other conditions inside loop body.  */
4026   ex_bb = gimple_bb (use->stmt);
4027   if (use->stmt != last_stmt (ex_bb)
4028       || gimple_code (use->stmt) != GIMPLE_COND
4029       || !dominated_by_p (CDI_DOMINATORS, loop->latch, ex_bb))
4030     return false;
4031
4032   exit = EDGE_SUCC (ex_bb, 0);
4033   if (flow_bb_inside_loop_p (loop, exit->dest))
4034     exit = EDGE_SUCC (ex_bb, 1);
4035   if (flow_bb_inside_loop_p (loop, exit->dest))
4036     return false;
4037
4038   nit = niter_for_exit (data, exit);
4039   if (!nit)
4040     return false;
4041
4042   /* Determine whether we can use the variable to test the exit condition.
4043      This is the case iff the period of the induction variable is greater
4044      than the number of iterations for which the exit condition is true.  */
4045   period = iv_period (cand->iv);
4046
4047   /* If the number of iterations is constant, compare against it directly.  */
4048   if (TREE_CODE (nit) == INTEGER_CST)
4049     {
4050       if (!tree_int_cst_lt (nit, period))
4051         return false;
4052     }
4053
4054   /* If not, and if this is the only possible exit of the loop, see whether
4055      we can get a conservative estimate on the number of iterations of the
4056      entire loop and compare against that instead.  */
4057   else if (loop_only_exit_p (loop, exit))
4058     {
4059       double_int period_value, max_niter;
4060       if (!estimated_loop_iterations (loop, true, &max_niter))
4061         return false;
4062       period_value = tree_to_double_int (period);
4063       if (double_int_ucmp (max_niter, period_value) >= 0)
4064         return false;
4065     }
4066
4067   /* Otherwise, punt.  */
4068   else
4069     return false;
4070
4071   cand_value_at (loop, cand, use->stmt, nit, &bnd);
4072
4073   *bound = aff_combination_to_tree (&bnd);
4074   /* It is unlikely that computing the number of iterations using division
4075      would be more profitable than keeping the original induction variable.  */
4076   if (expression_expensive_p (*bound))
4077     return false;
4078   return true;
4079 }
4080
4081 /* Determines cost of basing replacement of USE on CAND in a condition.  */
4082
4083 static bool
4084 determine_use_iv_cost_condition (struct ivopts_data *data,
4085                                  struct iv_use *use, struct iv_cand *cand)
4086 {
4087   tree bound = NULL_TREE;
4088   struct iv *cmp_iv;
4089   bitmap depends_on_elim = NULL, depends_on_express = NULL, depends_on;
4090   comp_cost elim_cost, express_cost, cost;
4091   bool ok;
4092   tree *control_var, *bound_cst;
4093
4094   /* Only consider real candidates.  */
4095   if (!cand->iv)
4096     {
4097       set_use_iv_cost (data, use, cand, infinite_cost, NULL, NULL_TREE);
4098       return false;
4099     }
4100
4101   /* Try iv elimination.  */
4102   if (may_eliminate_iv (data, use, cand, &bound))
4103     {
4104       elim_cost = force_var_cost (data, bound, &depends_on_elim);
4105       /* The bound is a loop invariant, so it will be only computed
4106          once.  */
4107       elim_cost.cost /= AVG_LOOP_NITER (data->current_loop);
4108     }
4109   else
4110     elim_cost = infinite_cost;
4111
4112   /* Try expressing the original giv.  If it is compared with an invariant,
4113      note that we cannot get rid of it.  */
4114   ok = extract_cond_operands (data, use->stmt, &control_var, &bound_cst,
4115                               NULL, &cmp_iv);
4116   gcc_assert (ok);
4117
4118   /* When the condition is a comparison of the candidate IV against
4119      zero, prefer this IV.
4120
4121      TODO: The constant that we're substracting from the cost should
4122      be target-dependent.  This information should be added to the
4123      target costs for each backend.  */
4124   if (!infinite_cost_p (elim_cost) /* Do not try to decrease infinite! */
4125       && integer_zerop (*bound_cst)
4126       && (operand_equal_p (*control_var, cand->var_after, 0)
4127           || operand_equal_p (*control_var, cand->var_before, 0)))
4128     elim_cost.cost -= 1;
4129
4130   express_cost = get_computation_cost (data, use, cand, false,
4131                                        &depends_on_express, NULL);
4132   fd_ivopts_data = data;
4133   walk_tree (&cmp_iv->base, find_depends, &depends_on_express, NULL);
4134
4135   /* Choose the better approach, preferring the eliminated IV. */
4136   if (compare_costs (elim_cost, express_cost) <= 0)
4137     {
4138       cost = elim_cost;
4139       depends_on = depends_on_elim;
4140       depends_on_elim = NULL;
4141     }
4142   else
4143     {
4144       cost = express_cost;
4145       depends_on = depends_on_express;
4146       depends_on_express = NULL;
4147       bound = NULL_TREE;
4148     }
4149
4150   set_use_iv_cost (data, use, cand, cost, depends_on, bound);
4151
4152   if (depends_on_elim)
4153     BITMAP_FREE (depends_on_elim);
4154   if (depends_on_express)
4155     BITMAP_FREE (depends_on_express);
4156
4157   return !infinite_cost_p (cost);
4158 }
4159
4160 /* Determines cost of basing replacement of USE on CAND.  Returns false
4161    if USE cannot be based on CAND.  */
4162
4163 static bool
4164 determine_use_iv_cost (struct ivopts_data *data,
4165                        struct iv_use *use, struct iv_cand *cand)
4166 {
4167   switch (use->type)
4168     {
4169     case USE_NONLINEAR_EXPR:
4170       return determine_use_iv_cost_generic (data, use, cand);
4171
4172     case USE_ADDRESS:
4173       return determine_use_iv_cost_address (data, use, cand);
4174
4175     case USE_COMPARE:
4176       return determine_use_iv_cost_condition (data, use, cand);
4177
4178     default:
4179       gcc_unreachable ();
4180     }
4181 }
4182
4183 /* Return true if get_computation_cost indicates that autoincrement is
4184    a possibility for the pair of USE and CAND, false otherwise.  */
4185
4186 static bool
4187 autoinc_possible_for_pair (struct ivopts_data *data, struct iv_use *use,
4188                            struct iv_cand *cand)
4189 {
4190   bitmap depends_on;
4191   bool can_autoinc;
4192   comp_cost cost;
4193
4194   if (use->type != USE_ADDRESS)
4195     return false;
4196
4197   cost = get_computation_cost (data, use, cand, true, &depends_on,
4198                                &can_autoinc);
4199
4200   BITMAP_FREE (depends_on);
4201
4202   return !infinite_cost_p (cost) && can_autoinc;
4203 }
4204
4205 /* Examine IP_ORIGINAL candidates to see if they are incremented next to a
4206    use that allows autoincrement, and set their AINC_USE if possible.  */
4207
4208 static void
4209 set_autoinc_for_original_candidates (struct ivopts_data *data)
4210 {
4211   unsigned i, j;
4212
4213   for (i = 0; i < n_iv_cands (data); i++)
4214     {
4215       struct iv_cand *cand = iv_cand (data, i);
4216       struct iv_use *closest = NULL;
4217       if (cand->pos != IP_ORIGINAL)
4218         continue;
4219       for (j = 0; j < n_iv_uses (data); j++)
4220         {
4221           struct iv_use *use = iv_use (data, j);
4222           unsigned uid = gimple_uid (use->stmt);
4223           if (gimple_bb (use->stmt) != gimple_bb (cand->incremented_at)
4224               || uid > gimple_uid (cand->incremented_at))
4225             continue;
4226           if (closest == NULL || uid > gimple_uid (closest->stmt))
4227             closest = use;
4228         }
4229       if (closest == NULL || !autoinc_possible_for_pair (data, closest, cand))
4230         continue;
4231       cand->ainc_use = closest;
4232     }
4233 }
4234
4235 /* Finds the candidates for the induction variables.  */
4236
4237 static void
4238 find_iv_candidates (struct ivopts_data *data)
4239 {
4240   /* Add commonly used ivs.  */
4241   add_standard_iv_candidates (data);
4242
4243   /* Add old induction variables.  */
4244   add_old_ivs_candidates (data);
4245
4246   /* Add induction variables derived from uses.  */
4247   add_derived_ivs_candidates (data);
4248
4249   set_autoinc_for_original_candidates (data);
4250
4251   /* Record the important candidates.  */
4252   record_important_candidates (data);
4253 }
4254
4255 /* Determines costs of basing the use of the iv on an iv candidate.  */
4256
4257 static void
4258 determine_use_iv_costs (struct ivopts_data *data)
4259 {
4260   unsigned i, j;
4261   struct iv_use *use;
4262   struct iv_cand *cand;
4263   bitmap to_clear = BITMAP_ALLOC (NULL);
4264
4265   alloc_use_cost_map (data);
4266
4267   for (i = 0; i < n_iv_uses (data); i++)
4268     {
4269       use = iv_use (data, i);
4270
4271       if (data->consider_all_candidates)
4272         {
4273           for (j = 0; j < n_iv_cands (data); j++)
4274             {
4275               cand = iv_cand (data, j);
4276               determine_use_iv_cost (data, use, cand);
4277             }
4278         }
4279       else
4280         {
4281           bitmap_iterator bi;
4282
4283           EXECUTE_IF_SET_IN_BITMAP (use->related_cands, 0, j, bi)
4284             {
4285               cand = iv_cand (data, j);
4286               if (!determine_use_iv_cost (data, use, cand))
4287                 bitmap_set_bit (to_clear, j);
4288             }
4289
4290           /* Remove the candidates for that the cost is infinite from
4291              the list of related candidates.  */
4292           bitmap_and_compl_into (use->related_cands, to_clear);
4293           bitmap_clear (to_clear);
4294         }
4295     }
4296
4297   BITMAP_FREE (to_clear);
4298
4299   if (dump_file && (dump_flags & TDF_DETAILS))
4300     {
4301       fprintf (dump_file, "Use-candidate costs:\n");
4302
4303       for (i = 0; i < n_iv_uses (data); i++)
4304         {
4305           use = iv_use (data, i);
4306
4307           fprintf (dump_file, "Use %d:\n", i);
4308           fprintf (dump_file, "  cand\tcost\tcompl.\tdepends on\n");
4309           for (j = 0; j < use->n_map_members; j++)
4310             {
4311               if (!use->cost_map[j].cand
4312                   || infinite_cost_p (use->cost_map[j].cost))
4313                 continue;
4314
4315               fprintf (dump_file, "  %d\t%d\t%d\t",
4316                        use->cost_map[j].cand->id,
4317                        use->cost_map[j].cost.cost,
4318                        use->cost_map[j].cost.complexity);
4319               if (use->cost_map[j].depends_on)
4320                 bitmap_print (dump_file,
4321                               use->cost_map[j].depends_on, "","");
4322               fprintf (dump_file, "\n");
4323             }
4324
4325           fprintf (dump_file, "\n");
4326         }
4327       fprintf (dump_file, "\n");
4328     }
4329 }
4330
4331 /* Determines cost of the candidate CAND.  */
4332
4333 static void
4334 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
4335 {
4336   comp_cost cost_base;
4337   unsigned cost, cost_step;
4338   tree base;
4339
4340   if (!cand->iv)
4341     {
4342       cand->cost = 0;
4343       return;
4344     }
4345
4346   /* There are two costs associated with the candidate -- its increment
4347      and its initialization.  The second is almost negligible for any loop
4348      that rolls enough, so we take it just very little into account.  */
4349
4350   base = cand->iv->base;
4351   cost_base = force_var_cost (data, base, NULL);
4352   cost_step = add_cost (TYPE_MODE (TREE_TYPE (base)), data->speed);
4353
4354   cost = cost_step + cost_base.cost / AVG_LOOP_NITER (current_loop);
4355
4356   /* Prefer the original ivs unless we may gain something by replacing it.
4357      The reason is to make debugging simpler; so this is not relevant for
4358      artificial ivs created by other optimization passes.  */
4359   if (cand->pos != IP_ORIGINAL
4360       || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
4361     cost++;
4362
4363   /* Prefer not to insert statements into latch unless there are some
4364      already (so that we do not create unnecessary jumps).  */
4365   if (cand->pos == IP_END
4366       && empty_block_p (ip_end_pos (data->current_loop)))
4367     cost++;
4368
4369   cand->cost = cost;
4370   cand->cost_step = cost_step;
4371 }
4372
4373 /* Determines costs of computation of the candidates.  */
4374
4375 static void
4376 determine_iv_costs (struct ivopts_data *data)
4377 {
4378   unsigned i;
4379
4380   if (dump_file && (dump_flags & TDF_DETAILS))
4381     {
4382       fprintf (dump_file, "Candidate costs:\n");
4383       fprintf (dump_file, "  cand\tcost\n");
4384     }
4385
4386   for (i = 0; i < n_iv_cands (data); i++)
4387     {
4388       struct iv_cand *cand = iv_cand (data, i);
4389
4390       determine_iv_cost (data, cand);
4391
4392       if (dump_file && (dump_flags & TDF_DETAILS))
4393         fprintf (dump_file, "  %d\t%d\n", i, cand->cost);
4394     }
4395
4396   if (dump_file && (dump_flags & TDF_DETAILS))
4397     fprintf (dump_file, "\n");
4398 }
4399
4400 /* Calculates cost for having SIZE induction variables.  */
4401
4402 static unsigned
4403 ivopts_global_cost_for_size (struct ivopts_data *data, unsigned size)
4404 {
4405   /* We add size to the cost, so that we prefer eliminating ivs
4406      if possible.  */
4407   return size + estimate_reg_pressure_cost (size, data->regs_used, data->speed);
4408 }
4409
4410 /* For each size of the induction variable set determine the penalty.  */
4411
4412 static void
4413 determine_set_costs (struct ivopts_data *data)
4414 {
4415   unsigned j, n;
4416   gimple phi;
4417   gimple_stmt_iterator psi;
4418   tree op;
4419   struct loop *loop = data->current_loop;
4420   bitmap_iterator bi;
4421
4422   /* We use the following model (definitely improvable, especially the
4423      cost function -- TODO):
4424
4425      We estimate the number of registers available (using MD data), name it A.
4426
4427      We estimate the number of registers used by the loop, name it U.  This
4428      number is obtained as the number of loop phi nodes (not counting virtual
4429      registers and bivs) + the number of variables from outside of the loop.
4430
4431      We set a reserve R (free regs that are used for temporary computations,
4432      etc.).  For now the reserve is a constant 3.
4433
4434      Let I be the number of induction variables.
4435
4436      -- if U + I + R <= A, the cost is I * SMALL_COST (just not to encourage
4437         make a lot of ivs without a reason).
4438      -- if A - R < U + I <= A, the cost is I * PRES_COST
4439      -- if U + I > A, the cost is I * PRES_COST and
4440         number of uses * SPILL_COST * (U + I - A) / (U + I) is added.  */
4441
4442   if (dump_file && (dump_flags & TDF_DETAILS))
4443     {
4444       fprintf (dump_file, "Global costs:\n");
4445       fprintf (dump_file, "  target_avail_regs %d\n", target_avail_regs);
4446       fprintf (dump_file, "  target_reg_cost %d\n", target_reg_cost[data->speed]);
4447       fprintf (dump_file, "  target_spill_cost %d\n", target_spill_cost[data->speed]);
4448     }
4449
4450   n = 0;
4451   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
4452     {
4453       phi = gsi_stmt (psi);
4454       op = PHI_RESULT (phi);
4455
4456       if (!is_gimple_reg (op))
4457         continue;
4458
4459       if (get_iv (data, op))
4460         continue;
4461
4462       n++;
4463     }
4464
4465   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
4466     {
4467       struct version_info *info = ver_info (data, j);
4468
4469       if (info->inv_id && info->has_nonlin_use)
4470         n++;
4471     }
4472
4473   data->regs_used = n;
4474   if (dump_file && (dump_flags & TDF_DETAILS))
4475     fprintf (dump_file, "  regs_used %d\n", n);
4476
4477   if (dump_file && (dump_flags & TDF_DETAILS))
4478     {
4479       fprintf (dump_file, "  cost for size:\n");
4480       fprintf (dump_file, "  ivs\tcost\n");
4481       for (j = 0; j <= 2 * target_avail_regs; j++)
4482         fprintf (dump_file, "  %d\t%d\n", j,
4483                  ivopts_global_cost_for_size (data, j));
4484       fprintf (dump_file, "\n");
4485     }
4486 }
4487
4488 /* Returns true if A is a cheaper cost pair than B.  */
4489
4490 static bool
4491 cheaper_cost_pair (struct cost_pair *a, struct cost_pair *b)
4492 {
4493   int cmp;
4494
4495   if (!a)
4496     return false;
4497
4498   if (!b)
4499     return true;
4500
4501   cmp = compare_costs (a->cost, b->cost);
4502   if (cmp < 0)
4503     return true;
4504
4505   if (cmp > 0)
4506     return false;
4507
4508   /* In case the costs are the same, prefer the cheaper candidate.  */
4509   if (a->cand->cost < b->cand->cost)
4510     return true;
4511
4512   return false;
4513 }
4514
4515 /* Computes the cost field of IVS structure.  */
4516
4517 static void
4518 iv_ca_recount_cost (struct ivopts_data *data, struct iv_ca *ivs)
4519 {
4520   comp_cost cost = ivs->cand_use_cost;
4521   cost.cost += ivs->cand_cost;
4522   cost.cost += ivopts_global_cost_for_size (data, ivs->n_regs);
4523
4524   ivs->cost = cost;
4525 }
4526
4527 /* Remove invariants in set INVS to set IVS.  */
4528
4529 static void
4530 iv_ca_set_remove_invariants (struct iv_ca *ivs, bitmap invs)
4531 {
4532   bitmap_iterator bi;
4533   unsigned iid;
4534
4535   if (!invs)
4536     return;
4537
4538   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
4539     {
4540       ivs->n_invariant_uses[iid]--;
4541       if (ivs->n_invariant_uses[iid] == 0)
4542         ivs->n_regs--;
4543     }
4544 }
4545
4546 /* Set USE not to be expressed by any candidate in IVS.  */
4547
4548 static void
4549 iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
4550                  struct iv_use *use)
4551 {
4552   unsigned uid = use->id, cid;
4553   struct cost_pair *cp;
4554
4555   cp = ivs->cand_for_use[uid];
4556   if (!cp)
4557     return;
4558   cid = cp->cand->id;
4559
4560   ivs->bad_uses++;
4561   ivs->cand_for_use[uid] = NULL;
4562   ivs->n_cand_uses[cid]--;
4563
4564   if (ivs->n_cand_uses[cid] == 0)
4565     {
4566       bitmap_clear_bit (ivs->cands, cid);
4567       /* Do not count the pseudocandidates.  */
4568       if (cp->cand->iv)
4569         ivs->n_regs--;
4570       ivs->n_cands--;
4571       ivs->cand_cost -= cp->cand->cost;
4572
4573       iv_ca_set_remove_invariants (ivs, cp->cand->depends_on);
4574     }
4575
4576   ivs->cand_use_cost = sub_costs (ivs->cand_use_cost, cp->cost);
4577
4578   iv_ca_set_remove_invariants (ivs, cp->depends_on);
4579   iv_ca_recount_cost (data, ivs);
4580 }
4581
4582 /* Add invariants in set INVS to set IVS.  */
4583
4584 static void
4585 iv_ca_set_add_invariants (struct iv_ca *ivs, bitmap invs)
4586 {
4587   bitmap_iterator bi;
4588   unsigned iid;
4589
4590   if (!invs)
4591     return;
4592
4593   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
4594     {
4595       ivs->n_invariant_uses[iid]++;
4596       if (ivs->n_invariant_uses[iid] == 1)
4597         ivs->n_regs++;
4598     }
4599 }
4600
4601 /* Set cost pair for USE in set IVS to CP.  */
4602
4603 static void
4604 iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
4605               struct iv_use *use, struct cost_pair *cp)
4606 {
4607   unsigned uid = use->id, cid;
4608
4609   if (ivs->cand_for_use[uid] == cp)
4610     return;
4611
4612   if (ivs->cand_for_use[uid])
4613     iv_ca_set_no_cp (data, ivs, use);
4614
4615   if (cp)
4616     {
4617       cid = cp->cand->id;
4618
4619       ivs->bad_uses--;
4620       ivs->cand_for_use[uid] = cp;
4621       ivs->n_cand_uses[cid]++;
4622       if (ivs->n_cand_uses[cid] == 1)
4623         {
4624           bitmap_set_bit (ivs->cands, cid);
4625           /* Do not count the pseudocandidates.  */
4626           if (cp->cand->iv)
4627             ivs->n_regs++;
4628           ivs->n_cands++;
4629           ivs->cand_cost += cp->cand->cost;
4630
4631           iv_ca_set_add_invariants (ivs, cp->cand->depends_on);
4632         }
4633
4634       ivs->cand_use_cost = add_costs (ivs->cand_use_cost, cp->cost);
4635       iv_ca_set_add_invariants (ivs, cp->depends_on);
4636       iv_ca_recount_cost (data, ivs);
4637     }
4638 }
4639
4640 /* Extend set IVS by expressing USE by some of the candidates in it
4641    if possible.  */
4642
4643 static void
4644 iv_ca_add_use (struct ivopts_data *data, struct iv_ca *ivs,
4645                struct iv_use *use)
4646 {
4647   struct cost_pair *best_cp = NULL, *cp;
4648   bitmap_iterator bi;
4649   unsigned i;
4650
4651   gcc_assert (ivs->upto >= use->id);
4652
4653   if (ivs->upto == use->id)
4654     {
4655       ivs->upto++;
4656       ivs->bad_uses++;
4657     }
4658
4659   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
4660     {
4661       cp = get_use_iv_cost (data, use, iv_cand (data, i));
4662
4663       if (cheaper_cost_pair (cp, best_cp))
4664         best_cp = cp;
4665     }
4666
4667   iv_ca_set_cp (data, ivs, use, best_cp);
4668 }
4669
4670 /* Get cost for assignment IVS.  */
4671
4672 static comp_cost
4673 iv_ca_cost (struct iv_ca *ivs)
4674 {
4675   /* This was a conditional expression but it triggered a bug in
4676      Sun C 5.5.  */
4677   if (ivs->bad_uses)
4678     return infinite_cost;
4679   else
4680     return ivs->cost;
4681 }
4682
4683 /* Returns true if all dependences of CP are among invariants in IVS.  */
4684
4685 static bool
4686 iv_ca_has_deps (struct iv_ca *ivs, struct cost_pair *cp)
4687 {
4688   unsigned i;
4689   bitmap_iterator bi;
4690
4691   if (!cp->depends_on)
4692     return true;
4693
4694   EXECUTE_IF_SET_IN_BITMAP (cp->depends_on, 0, i, bi)
4695     {
4696       if (ivs->n_invariant_uses[i] == 0)
4697         return false;
4698     }
4699
4700   return true;
4701 }
4702
4703 /* Creates change of expressing USE by NEW_CP instead of OLD_CP and chains
4704    it before NEXT_CHANGE.  */
4705
4706 static struct iv_ca_delta *
4707 iv_ca_delta_add (struct iv_use *use, struct cost_pair *old_cp,
4708                  struct cost_pair *new_cp, struct iv_ca_delta *next_change)
4709 {
4710   struct iv_ca_delta *change = XNEW (struct iv_ca_delta);
4711
4712   change->use = use;
4713   change->old_cp = old_cp;
4714   change->new_cp = new_cp;
4715   change->next_change = next_change;
4716
4717   return change;
4718 }
4719
4720 /* Joins two lists of changes L1 and L2.  Destructive -- old lists
4721    are rewritten.  */
4722
4723 static struct iv_ca_delta *
4724 iv_ca_delta_join (struct iv_ca_delta *l1, struct iv_ca_delta *l2)
4725 {
4726   struct iv_ca_delta *last;
4727
4728   if (!l2)
4729     return l1;
4730
4731   if (!l1)
4732     return l2;
4733
4734   for (last = l1; last->next_change; last = last->next_change)
4735     continue;
4736   last->next_change = l2;
4737
4738   return l1;
4739 }
4740
4741 /* Returns candidate by that USE is expressed in IVS.  */
4742
4743 static struct cost_pair *
4744 iv_ca_cand_for_use (struct iv_ca *ivs, struct iv_use *use)
4745 {
4746   return ivs->cand_for_use[use->id];
4747 }
4748
4749 /* Reverse the list of changes DELTA, forming the inverse to it.  */
4750
4751 static struct iv_ca_delta *
4752 iv_ca_delta_reverse (struct iv_ca_delta *delta)
4753 {
4754   struct iv_ca_delta *act, *next, *prev = NULL;
4755   struct cost_pair *tmp;
4756
4757   for (act = delta; act; act = next)
4758     {
4759       next = act->next_change;
4760       act->next_change = prev;
4761       prev = act;
4762
4763       tmp = act->old_cp;
4764       act->old_cp = act->new_cp;
4765       act->new_cp = tmp;
4766     }
4767
4768   return prev;
4769 }
4770
4771 /* Commit changes in DELTA to IVS.  If FORWARD is false, the changes are
4772    reverted instead.  */
4773
4774 static void
4775 iv_ca_delta_commit (struct ivopts_data *data, struct iv_ca *ivs,
4776                     struct iv_ca_delta *delta, bool forward)
4777 {
4778   struct cost_pair *from, *to;
4779   struct iv_ca_delta *act;
4780
4781   if (!forward)
4782     delta = iv_ca_delta_reverse (delta);
4783
4784   for (act = delta; act; act = act->next_change)
4785     {
4786       from = act->old_cp;
4787       to = act->new_cp;
4788       gcc_assert (iv_ca_cand_for_use (ivs, act->use) == from);
4789       iv_ca_set_cp (data, ivs, act->use, to);
4790     }
4791
4792   if (!forward)
4793     iv_ca_delta_reverse (delta);
4794 }
4795
4796 /* Returns true if CAND is used in IVS.  */
4797
4798 static bool
4799 iv_ca_cand_used_p (struct iv_ca *ivs, struct iv_cand *cand)
4800 {
4801   return ivs->n_cand_uses[cand->id] > 0;
4802 }
4803
4804 /* Returns number of induction variable candidates in the set IVS.  */
4805
4806 static unsigned
4807 iv_ca_n_cands (struct iv_ca *ivs)
4808 {
4809   return ivs->n_cands;
4810 }
4811
4812 /* Free the list of changes DELTA.  */
4813
4814 static void
4815 iv_ca_delta_free (struct iv_ca_delta **delta)
4816 {
4817   struct iv_ca_delta *act, *next;
4818
4819   for (act = *delta; act; act = next)
4820     {
4821       next = act->next_change;
4822       free (act);
4823     }
4824
4825   *delta = NULL;
4826 }
4827
4828 /* Allocates new iv candidates assignment.  */
4829
4830 static struct iv_ca *
4831 iv_ca_new (struct ivopts_data *data)
4832 {
4833   struct iv_ca *nw = XNEW (struct iv_ca);
4834
4835   nw->upto = 0;
4836   nw->bad_uses = 0;
4837   nw->cand_for_use = XCNEWVEC (struct cost_pair *, n_iv_uses (data));
4838   nw->n_cand_uses = XCNEWVEC (unsigned, n_iv_cands (data));
4839   nw->cands = BITMAP_ALLOC (NULL);
4840   nw->n_cands = 0;
4841   nw->n_regs = 0;
4842   nw->cand_use_cost = zero_cost;
4843   nw->cand_cost = 0;
4844   nw->n_invariant_uses = XCNEWVEC (unsigned, data->max_inv_id + 1);
4845   nw->cost = zero_cost;
4846
4847   return nw;
4848 }
4849
4850 /* Free memory occupied by the set IVS.  */
4851
4852 static void
4853 iv_ca_free (struct iv_ca **ivs)
4854 {
4855   free ((*ivs)->cand_for_use);
4856   free ((*ivs)->n_cand_uses);
4857   BITMAP_FREE ((*ivs)->cands);
4858   free ((*ivs)->n_invariant_uses);
4859   free (*ivs);
4860   *ivs = NULL;
4861 }
4862
4863 /* Dumps IVS to FILE.  */
4864
4865 static void
4866 iv_ca_dump (struct ivopts_data *data, FILE *file, struct iv_ca *ivs)
4867 {
4868   const char *pref = "  invariants ";
4869   unsigned i;
4870   comp_cost cost = iv_ca_cost (ivs);
4871
4872   fprintf (file, "  cost %d (complexity %d)\n", cost.cost, cost.complexity);
4873   bitmap_print (file, ivs->cands, "  candidates ","\n");
4874
4875   for (i = 1; i <= data->max_inv_id; i++)
4876     if (ivs->n_invariant_uses[i])
4877       {
4878         fprintf (file, "%s%d", pref, i);
4879         pref = ", ";
4880       }
4881   fprintf (file, "\n");
4882 }
4883
4884 /* Try changing candidate in IVS to CAND for each use.  Return cost of the
4885    new set, and store differences in DELTA.  Number of induction variables
4886    in the new set is stored to N_IVS.  */
4887
4888 static comp_cost
4889 iv_ca_extend (struct ivopts_data *data, struct iv_ca *ivs,
4890               struct iv_cand *cand, struct iv_ca_delta **delta,
4891               unsigned *n_ivs)
4892 {
4893   unsigned i;
4894   comp_cost cost;
4895   struct iv_use *use;
4896   struct cost_pair *old_cp, *new_cp;
4897
4898   *delta = NULL;
4899   for (i = 0; i < ivs->upto; i++)
4900     {
4901       use = iv_use (data, i);
4902       old_cp = iv_ca_cand_for_use (ivs, use);
4903
4904       if (old_cp
4905           && old_cp->cand == cand)
4906         continue;
4907
4908       new_cp = get_use_iv_cost (data, use, cand);
4909       if (!new_cp)
4910         continue;
4911
4912       if (!iv_ca_has_deps (ivs, new_cp))
4913         continue;
4914
4915       if (!cheaper_cost_pair (new_cp, old_cp))
4916         continue;
4917
4918       *delta = iv_ca_delta_add (use, old_cp, new_cp, *delta);
4919     }
4920
4921   iv_ca_delta_commit (data, ivs, *delta, true);
4922   cost = iv_ca_cost (ivs);
4923   if (n_ivs)
4924     *n_ivs = iv_ca_n_cands (ivs);
4925   iv_ca_delta_commit (data, ivs, *delta, false);
4926
4927   return cost;
4928 }
4929
4930 /* Try narrowing set IVS by removing CAND.  Return the cost of
4931    the new set and store the differences in DELTA.  */
4932
4933 static comp_cost
4934 iv_ca_narrow (struct ivopts_data *data, struct iv_ca *ivs,
4935               struct iv_cand *cand, struct iv_ca_delta **delta)
4936 {
4937   unsigned i, ci;
4938   struct iv_use *use;
4939   struct cost_pair *old_cp, *new_cp, *cp;
4940   bitmap_iterator bi;
4941   struct iv_cand *cnd;
4942   comp_cost cost;
4943
4944   *delta = NULL;
4945   for (i = 0; i < n_iv_uses (data); i++)
4946     {
4947       use = iv_use (data, i);
4948
4949       old_cp = iv_ca_cand_for_use (ivs, use);
4950       if (old_cp->cand != cand)
4951         continue;
4952
4953       new_cp = NULL;
4954
4955       if (data->consider_all_candidates)
4956         {
4957           EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, ci, bi)
4958             {
4959               if (ci == cand->id)
4960                 continue;
4961
4962               cnd = iv_cand (data, ci);
4963
4964               cp = get_use_iv_cost (data, use, cnd);
4965               if (!cp)
4966                 continue;
4967               if (!iv_ca_has_deps (ivs, cp))
4968                 continue;
4969
4970               if (!cheaper_cost_pair (cp, new_cp))
4971                 continue;
4972
4973               new_cp = cp;
4974             }
4975         }
4976       else
4977         {
4978           EXECUTE_IF_AND_IN_BITMAP (use->related_cands, ivs->cands, 0, ci, bi)
4979             {
4980               if (ci == cand->id)
4981                 continue;
4982
4983               cnd = iv_cand (data, ci);
4984
4985               cp = get_use_iv_cost (data, use, cnd);
4986               if (!cp)
4987                 continue;
4988               if (!iv_ca_has_deps (ivs, cp))
4989                 continue;
4990
4991               if (!cheaper_cost_pair (cp, new_cp))
4992                 continue;
4993
4994               new_cp = cp;
4995             }
4996         }
4997
4998       if (!new_cp)
4999         {
5000           iv_ca_delta_free (delta);
5001           return infinite_cost;
5002         }
5003
5004       *delta = iv_ca_delta_add (use, old_cp, new_cp, *delta);
5005     }
5006
5007   iv_ca_delta_commit (data, ivs, *delta, true);
5008   cost = iv_ca_cost (ivs);
5009   iv_ca_delta_commit (data, ivs, *delta, false);
5010
5011   return cost;
5012 }
5013
5014 /* Try optimizing the set of candidates IVS by removing candidates different
5015    from to EXCEPT_CAND from it.  Return cost of the new set, and store
5016    differences in DELTA.  */
5017
5018 static comp_cost
5019 iv_ca_prune (struct ivopts_data *data, struct iv_ca *ivs,
5020              struct iv_cand *except_cand, struct iv_ca_delta **delta)
5021 {
5022   bitmap_iterator bi;
5023   struct iv_ca_delta *act_delta, *best_delta;
5024   unsigned i;
5025   comp_cost best_cost, acost;
5026   struct iv_cand *cand;
5027
5028   best_delta = NULL;
5029   best_cost = iv_ca_cost (ivs);
5030
5031   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
5032     {
5033       cand = iv_cand (data, i);
5034
5035       if (cand == except_cand)
5036         continue;
5037
5038       acost = iv_ca_narrow (data, ivs, cand, &act_delta);
5039
5040       if (compare_costs (acost, best_cost) < 0)
5041         {
5042           best_cost = acost;
5043           iv_ca_delta_free (&best_delta);
5044           best_delta = act_delta;
5045         }
5046       else
5047         iv_ca_delta_free (&act_delta);
5048     }
5049
5050   if (!best_delta)
5051     {
5052       *delta = NULL;
5053       return best_cost;
5054     }
5055
5056   /* Recurse to possibly remove other unnecessary ivs.  */
5057   iv_ca_delta_commit (data, ivs, best_delta, true);
5058   best_cost = iv_ca_prune (data, ivs, except_cand, delta);
5059   iv_ca_delta_commit (data, ivs, best_delta, false);
5060   *delta = iv_ca_delta_join (best_delta, *delta);
5061   return best_cost;
5062 }
5063
5064 /* Tries to extend the sets IVS in the best possible way in order
5065    to express the USE.  */
5066
5067 static bool
5068 try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
5069                   struct iv_use *use)
5070 {
5071   comp_cost best_cost, act_cost;
5072   unsigned i;
5073   bitmap_iterator bi;
5074   struct iv_cand *cand;
5075   struct iv_ca_delta *best_delta = NULL, *act_delta;
5076   struct cost_pair *cp;
5077
5078   iv_ca_add_use (data, ivs, use);
5079   best_cost = iv_ca_cost (ivs);
5080
5081   cp = iv_ca_cand_for_use (ivs, use);
5082   if (cp)
5083     {
5084       best_delta = iv_ca_delta_add (use, NULL, cp, NULL);
5085       iv_ca_set_no_cp (data, ivs, use);
5086     }
5087
5088   /* First try important candidates not based on any memory object.  Only if
5089      this fails, try the specific ones.  Rationale -- in loops with many
5090      variables the best choice often is to use just one generic biv.  If we
5091      added here many ivs specific to the uses, the optimization algorithm later
5092      would be likely to get stuck in a local minimum, thus causing us to create
5093      too many ivs.  The approach from few ivs to more seems more likely to be
5094      successful -- starting from few ivs, replacing an expensive use by a
5095      specific iv should always be a win.  */
5096   EXECUTE_IF_SET_IN_BITMAP (data->important_candidates, 0, i, bi)
5097     {
5098       cand = iv_cand (data, i);
5099
5100       if (cand->iv->base_object != NULL_TREE)
5101         continue;
5102
5103       if (iv_ca_cand_used_p (ivs, cand))
5104         continue;
5105
5106       cp = get_use_iv_cost (data, use, cand);
5107       if (!cp)
5108         continue;
5109
5110       iv_ca_set_cp (data, ivs, use, cp);
5111       act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL);
5112       iv_ca_set_no_cp (data, ivs, use);
5113       act_delta = iv_ca_delta_add (use, NULL, cp, act_delta);
5114
5115       if (compare_costs (act_cost, best_cost) < 0)
5116         {
5117           best_cost = act_cost;
5118
5119           iv_ca_delta_free (&best_delta);
5120           best_delta = act_delta;
5121         }
5122       else
5123         iv_ca_delta_free (&act_delta);
5124     }
5125
5126   if (infinite_cost_p (best_cost))
5127     {
5128       for (i = 0; i < use->n_map_members; i++)
5129         {
5130           cp = use->cost_map + i;
5131           cand = cp->cand;
5132           if (!cand)
5133             continue;
5134
5135           /* Already tried this.  */
5136           if (cand->important && cand->iv->base_object == NULL_TREE)
5137             continue;
5138
5139           if (iv_ca_cand_used_p (ivs, cand))
5140             continue;
5141
5142           act_delta = NULL;
5143           iv_ca_set_cp (data, ivs, use, cp);
5144           act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL);
5145           iv_ca_set_no_cp (data, ivs, use);
5146           act_delta = iv_ca_delta_add (use, iv_ca_cand_for_use (ivs, use),
5147                                        cp, act_delta);
5148
5149           if (compare_costs (act_cost, best_cost) < 0)
5150             {
5151               best_cost = act_cost;
5152
5153               if (best_delta)
5154                 iv_ca_delta_free (&best_delta);
5155               best_delta = act_delta;
5156             }
5157           else
5158             iv_ca_delta_free (&act_delta);
5159         }
5160     }
5161
5162   iv_ca_delta_commit (data, ivs, best_delta, true);
5163   iv_ca_delta_free (&best_delta);
5164
5165   return !infinite_cost_p (best_cost);
5166 }
5167
5168 /* Finds an initial assignment of candidates to uses.  */
5169
5170 static struct iv_ca *
5171 get_initial_solution (struct ivopts_data *data)
5172 {
5173   struct iv_ca *ivs = iv_ca_new (data);
5174   unsigned i;
5175
5176   for (i = 0; i < n_iv_uses (data); i++)
5177     if (!try_add_cand_for (data, ivs, iv_use (data, i)))
5178       {
5179         iv_ca_free (&ivs);
5180         return NULL;
5181       }
5182
5183   return ivs;
5184 }
5185
5186 /* Tries to improve set of induction variables IVS.  */
5187
5188 static bool
5189 try_improve_iv_set (struct ivopts_data *data, struct iv_ca *ivs)
5190 {
5191   unsigned i, n_ivs;
5192   comp_cost acost, best_cost = iv_ca_cost (ivs);
5193   struct iv_ca_delta *best_delta = NULL, *act_delta, *tmp_delta;
5194   struct iv_cand *cand;
5195
5196   /* Try extending the set of induction variables by one.  */
5197   for (i = 0; i < n_iv_cands (data); i++)
5198     {
5199       cand = iv_cand (data, i);
5200
5201       if (iv_ca_cand_used_p (ivs, cand))
5202         continue;
5203
5204       acost = iv_ca_extend (data, ivs, cand, &act_delta, &n_ivs);
5205       if (!act_delta)
5206         continue;
5207
5208       /* If we successfully added the candidate and the set is small enough,
5209          try optimizing it by removing other candidates.  */
5210       if (n_ivs <= ALWAYS_PRUNE_CAND_SET_BOUND)
5211         {
5212           iv_ca_delta_commit (data, ivs, act_delta, true);
5213           acost = iv_ca_prune (data, ivs, cand, &tmp_delta);
5214           iv_ca_delta_commit (data, ivs, act_delta, false);
5215           act_delta = iv_ca_delta_join (act_delta, tmp_delta);
5216         }
5217
5218       if (compare_costs (acost, best_cost) < 0)
5219         {
5220           best_cost = acost;
5221           iv_ca_delta_free (&best_delta);
5222           best_delta = act_delta;
5223         }
5224       else
5225         iv_ca_delta_free (&act_delta);
5226     }
5227
5228   if (!best_delta)
5229     {
5230       /* Try removing the candidates from the set instead.  */
5231       best_cost = iv_ca_prune (data, ivs, NULL, &best_delta);
5232
5233       /* Nothing more we can do.  */
5234       if (!best_delta)
5235         return false;
5236     }
5237
5238   iv_ca_delta_commit (data, ivs, best_delta, true);
5239   gcc_assert (compare_costs (best_cost, iv_ca_cost (ivs)) == 0);
5240   iv_ca_delta_free (&best_delta);
5241   return true;
5242 }
5243
5244 /* Attempts to find the optimal set of induction variables.  We do simple
5245    greedy heuristic -- we try to replace at most one candidate in the selected
5246    solution and remove the unused ivs while this improves the cost.  */
5247
5248 static struct iv_ca *
5249 find_optimal_iv_set (struct ivopts_data *data)
5250 {
5251   unsigned i;
5252   struct iv_ca *set;
5253   struct iv_use *use;
5254
5255   /* Get the initial solution.  */
5256   set = get_initial_solution (data);
5257   if (!set)
5258     {
5259       if (dump_file && (dump_flags & TDF_DETAILS))
5260         fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
5261       return NULL;
5262     }
5263
5264   if (dump_file && (dump_flags & TDF_DETAILS))
5265     {
5266       fprintf (dump_file, "Initial set of candidates:\n");
5267       iv_ca_dump (data, dump_file, set);
5268     }
5269
5270   while (try_improve_iv_set (data, set))
5271     {
5272       if (dump_file && (dump_flags & TDF_DETAILS))
5273         {
5274           fprintf (dump_file, "Improved to:\n");
5275           iv_ca_dump (data, dump_file, set);
5276         }
5277     }
5278
5279   if (dump_file && (dump_flags & TDF_DETAILS))
5280     {
5281       comp_cost cost = iv_ca_cost (set);
5282       fprintf (dump_file, "Final cost %d (complexity %d)\n\n", cost.cost, cost.complexity);
5283     }
5284
5285   for (i = 0; i < n_iv_uses (data); i++)
5286     {
5287       use = iv_use (data, i);
5288       use->selected = iv_ca_cand_for_use (set, use)->cand;
5289     }
5290
5291   return set;
5292 }
5293
5294 /* Creates a new induction variable corresponding to CAND.  */
5295
5296 static void
5297 create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
5298 {
5299   gimple_stmt_iterator incr_pos;
5300   tree base;
5301   bool after = false;
5302
5303   if (!cand->iv)
5304     return;
5305
5306   switch (cand->pos)
5307     {
5308     case IP_NORMAL:
5309       incr_pos = gsi_last_bb (ip_normal_pos (data->current_loop));
5310       break;
5311
5312     case IP_END:
5313       incr_pos = gsi_last_bb (ip_end_pos (data->current_loop));
5314       after = true;
5315       break;
5316
5317     case IP_AFTER_USE:
5318       after = true;
5319       /* fall through */
5320     case IP_BEFORE_USE:
5321       incr_pos = gsi_for_stmt (cand->incremented_at);
5322       break;
5323
5324     case IP_ORIGINAL:
5325       /* Mark that the iv is preserved.  */
5326       name_info (data, cand->var_before)->preserve_biv = true;
5327       name_info (data, cand->var_after)->preserve_biv = true;
5328
5329       /* Rewrite the increment so that it uses var_before directly.  */
5330       find_interesting_uses_op (data, cand->var_after)->selected = cand;
5331
5332       return;
5333     }
5334
5335   gimple_add_tmp_var (cand->var_before);
5336   add_referenced_var (cand->var_before);
5337
5338   base = unshare_expr (cand->iv->base);
5339
5340   create_iv (base, unshare_expr (cand->iv->step),
5341              cand->var_before, data->current_loop,
5342              &incr_pos, after, &cand->var_before, &cand->var_after);
5343 }
5344
5345 /* Creates new induction variables described in SET.  */
5346
5347 static void
5348 create_new_ivs (struct ivopts_data *data, struct iv_ca *set)
5349 {
5350   unsigned i;
5351   struct iv_cand *cand;
5352   bitmap_iterator bi;
5353
5354   EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
5355     {
5356       cand = iv_cand (data, i);
5357       create_new_iv (data, cand);
5358     }
5359 }
5360
5361
5362 /* Rewrites USE (definition of iv used in a nonlinear expression)
5363    using candidate CAND.  */
5364
5365 static void
5366 rewrite_use_nonlinear_expr (struct ivopts_data *data,
5367                             struct iv_use *use, struct iv_cand *cand)
5368 {
5369   tree comp;
5370   tree op, tgt;
5371   gimple ass;
5372   gimple_stmt_iterator bsi;
5373
5374   /* An important special case -- if we are asked to express value of
5375      the original iv by itself, just exit; there is no need to
5376      introduce a new computation (that might also need casting the
5377      variable to unsigned and back).  */
5378   if (cand->pos == IP_ORIGINAL
5379       && cand->incremented_at == use->stmt)
5380     {
5381       tree step, ctype, utype;
5382       enum tree_code incr_code = PLUS_EXPR, old_code;
5383
5384       gcc_assert (is_gimple_assign (use->stmt));
5385       gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
5386
5387       step = cand->iv->step;
5388       ctype = TREE_TYPE (step);
5389       utype = TREE_TYPE (cand->var_after);
5390       if (TREE_CODE (step) == NEGATE_EXPR)
5391         {
5392           incr_code = MINUS_EXPR;
5393           step = TREE_OPERAND (step, 0);
5394         }
5395
5396       /* Check whether we may leave the computation unchanged.
5397          This is the case only if it does not rely on other
5398          computations in the loop -- otherwise, the computation
5399          we rely upon may be removed in remove_unused_ivs,
5400          thus leading to ICE.  */
5401       old_code = gimple_assign_rhs_code (use->stmt);
5402       if (old_code == PLUS_EXPR
5403           || old_code == MINUS_EXPR
5404           || old_code == POINTER_PLUS_EXPR)
5405         {
5406           if (gimple_assign_rhs1 (use->stmt) == cand->var_before)
5407             op = gimple_assign_rhs2 (use->stmt);
5408           else if (old_code != MINUS_EXPR
5409                    && gimple_assign_rhs2 (use->stmt) == cand->var_before)
5410             op = gimple_assign_rhs1 (use->stmt);
5411           else
5412             op = NULL_TREE;
5413         }
5414       else
5415         op = NULL_TREE;
5416
5417       if (op
5418           && (TREE_CODE (op) == INTEGER_CST
5419               || operand_equal_p (op, step, 0)))
5420         return;
5421
5422       /* Otherwise, add the necessary computations to express
5423          the iv.  */
5424       op = fold_convert (ctype, cand->var_before);
5425       comp = fold_convert (utype,
5426                            build2 (incr_code, ctype, op,
5427                                    unshare_expr (step)));
5428     }
5429   else
5430     {
5431       comp = get_computation (data->current_loop, use, cand);
5432       gcc_assert (comp != NULL_TREE);
5433     }
5434
5435   switch (gimple_code (use->stmt))
5436     {
5437     case GIMPLE_PHI:
5438       tgt = PHI_RESULT (use->stmt);
5439
5440       /* If we should keep the biv, do not replace it.  */
5441       if (name_info (data, tgt)->preserve_biv)
5442         return;
5443
5444       bsi = gsi_after_labels (gimple_bb (use->stmt));
5445       break;
5446
5447     case GIMPLE_ASSIGN:
5448       tgt = gimple_assign_lhs (use->stmt);
5449       bsi = gsi_for_stmt (use->stmt);
5450       break;
5451
5452     default:
5453       gcc_unreachable ();
5454     }
5455
5456   op = force_gimple_operand_gsi (&bsi, comp, false, SSA_NAME_VAR (tgt),
5457                                  true, GSI_SAME_STMT);
5458
5459   if (gimple_code (use->stmt) == GIMPLE_PHI)
5460     {
5461       ass = gimple_build_assign (tgt, op);
5462       gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
5463
5464       bsi = gsi_for_stmt (use->stmt);
5465       remove_phi_node (&bsi, false);
5466     }
5467   else
5468     {
5469       gimple_assign_set_rhs_from_tree (&bsi, op);
5470       use->stmt = gsi_stmt (bsi);
5471     }
5472 }
5473
5474 /* Replaces ssa name in index IDX by its basic variable.  Callback for
5475    for_each_index.  */
5476
5477 static bool
5478 idx_remove_ssa_names (tree base, tree *idx,
5479                       void *data ATTRIBUTE_UNUSED)
5480 {
5481   tree *op;
5482
5483   if (TREE_CODE (*idx) == SSA_NAME)
5484     *idx = SSA_NAME_VAR (*idx);
5485
5486   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
5487     {
5488       op = &TREE_OPERAND (base, 2);
5489       if (*op
5490           && TREE_CODE (*op) == SSA_NAME)
5491         *op = SSA_NAME_VAR (*op);
5492       op = &TREE_OPERAND (base, 3);
5493       if (*op
5494           && TREE_CODE (*op) == SSA_NAME)
5495         *op = SSA_NAME_VAR (*op);
5496     }
5497
5498   return true;
5499 }
5500
5501 /* Unshares REF and replaces ssa names inside it by their basic variables.  */
5502
5503 static tree
5504 unshare_and_remove_ssa_names (tree ref)
5505 {
5506   ref = unshare_expr (ref);
5507   for_each_index (&ref, idx_remove_ssa_names, NULL);
5508
5509   return ref;
5510 }
5511
5512 /* Copies the reference information from OLD_REF to NEW_REF.  */
5513
5514 static void
5515 copy_ref_info (tree new_ref, tree old_ref)
5516 {
5517   if (TREE_CODE (old_ref) == TARGET_MEM_REF)
5518     copy_mem_ref_info (new_ref, old_ref);
5519   else
5520     {
5521       TMR_ORIGINAL (new_ref) = unshare_and_remove_ssa_names (old_ref);
5522       TREE_SIDE_EFFECTS (new_ref) = TREE_SIDE_EFFECTS (old_ref);
5523       TREE_THIS_VOLATILE (new_ref) = TREE_THIS_VOLATILE (old_ref);
5524     }
5525 }
5526
5527 /* Rewrites USE (address that is an iv) using candidate CAND.  */
5528
5529 static void
5530 rewrite_use_address (struct ivopts_data *data,
5531                      struct iv_use *use, struct iv_cand *cand)
5532 {
5533   aff_tree aff;
5534   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
5535   tree base_hint = NULL_TREE;
5536   tree ref;
5537   bool ok;
5538
5539   ok = get_computation_aff (data->current_loop, use, cand, use->stmt, &aff);
5540   gcc_assert (ok);
5541   unshare_aff_combination (&aff);
5542
5543   /* To avoid undefined overflow problems, all IV candidates use unsigned
5544      integer types.  The drawback is that this makes it impossible for
5545      create_mem_ref to distinguish an IV that is based on a memory object
5546      from one that represents simply an offset.
5547
5548      To work around this problem, we pass a hint to create_mem_ref that
5549      indicates which variable (if any) in aff is an IV based on a memory
5550      object.  Note that we only consider the candidate.  If this is not
5551      based on an object, the base of the reference is in some subexpression
5552      of the use -- but these will use pointer types, so they are recognized
5553      by the create_mem_ref heuristics anyway.  */
5554   if (cand->iv->base_object)
5555     base_hint = var_at_stmt (data->current_loop, cand, use->stmt);
5556
5557   ref = create_mem_ref (&bsi, TREE_TYPE (*use->op_p), &aff, base_hint,
5558                         data->speed);
5559   copy_ref_info (ref, *use->op_p);
5560   *use->op_p = ref;
5561 }
5562
5563 /* Rewrites USE (the condition such that one of the arguments is an iv) using
5564    candidate CAND.  */
5565
5566 static void
5567 rewrite_use_compare (struct ivopts_data *data,
5568                      struct iv_use *use, struct iv_cand *cand)
5569 {
5570   tree comp, *var_p, op, bound;
5571   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
5572   enum tree_code compare;
5573   struct cost_pair *cp = get_use_iv_cost (data, use, cand);
5574   bool ok;
5575
5576   bound = cp->value;
5577   if (bound)
5578     {
5579       tree var = var_at_stmt (data->current_loop, cand, use->stmt);
5580       tree var_type = TREE_TYPE (var);
5581       gimple_seq stmts;
5582
5583       compare = iv_elimination_compare (data, use);
5584       bound = unshare_expr (fold_convert (var_type, bound));
5585       op = force_gimple_operand (bound, &stmts, true, NULL_TREE);
5586       if (stmts)
5587         gsi_insert_seq_on_edge_immediate (
5588                 loop_preheader_edge (data->current_loop),
5589                 stmts);
5590
5591       gimple_cond_set_lhs (use->stmt, var);
5592       gimple_cond_set_code (use->stmt, compare);
5593       gimple_cond_set_rhs (use->stmt, op);
5594       return;
5595     }
5596
5597   /* The induction variable elimination failed; just express the original
5598      giv.  */
5599   comp = get_computation (data->current_loop, use, cand);
5600   gcc_assert (comp != NULL_TREE);
5601
5602   ok = extract_cond_operands (data, use->stmt, &var_p, NULL, NULL, NULL);
5603   gcc_assert (ok);
5604
5605   *var_p = force_gimple_operand_gsi (&bsi, comp, true, SSA_NAME_VAR (*var_p),
5606                                      true, GSI_SAME_STMT);
5607 }
5608
5609 /* Rewrites USE using candidate CAND.  */
5610
5611 static void
5612 rewrite_use (struct ivopts_data *data, struct iv_use *use, struct iv_cand *cand)
5613 {
5614   switch (use->type)
5615     {
5616       case USE_NONLINEAR_EXPR:
5617         rewrite_use_nonlinear_expr (data, use, cand);
5618         break;
5619
5620       case USE_ADDRESS:
5621         rewrite_use_address (data, use, cand);
5622         break;
5623
5624       case USE_COMPARE:
5625         rewrite_use_compare (data, use, cand);
5626         break;
5627
5628       default:
5629         gcc_unreachable ();
5630     }
5631
5632   update_stmt (use->stmt);
5633 }
5634
5635 /* Rewrite the uses using the selected induction variables.  */
5636
5637 static void
5638 rewrite_uses (struct ivopts_data *data)
5639 {
5640   unsigned i;
5641   struct iv_cand *cand;
5642   struct iv_use *use;
5643
5644   for (i = 0; i < n_iv_uses (data); i++)
5645     {
5646       use = iv_use (data, i);
5647       cand = use->selected;
5648       gcc_assert (cand);
5649
5650       rewrite_use (data, use, cand);
5651     }
5652 }
5653
5654 /* Removes the ivs that are not used after rewriting.  */
5655
5656 static void
5657 remove_unused_ivs (struct ivopts_data *data)
5658 {
5659   unsigned j;
5660   bitmap_iterator bi;
5661   bitmap toremove = BITMAP_ALLOC (NULL);
5662
5663   /* Figure out an order in which to release SSA DEFs so that we don't
5664      release something that we'd have to propagate into a debug stmt
5665      afterwards.  */
5666   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
5667     {
5668       struct version_info *info;
5669
5670       info = ver_info (data, j);
5671       if (info->iv
5672           && !integer_zerop (info->iv->step)
5673           && !info->inv_id
5674           && !info->iv->have_use_for
5675           && !info->preserve_biv)
5676         bitmap_set_bit (toremove, SSA_NAME_VERSION (info->iv->ssa_name));
5677     }
5678
5679   release_defs_bitset (toremove);
5680
5681   BITMAP_FREE (toremove);
5682 }
5683
5684 /* Frees data allocated by the optimization of a single loop.  */
5685
5686 static void
5687 free_loop_data (struct ivopts_data *data)
5688 {
5689   unsigned i, j;
5690   bitmap_iterator bi;
5691   tree obj;
5692
5693   if (data->niters)
5694     {
5695       pointer_map_destroy (data->niters);
5696       data->niters = NULL;
5697     }
5698
5699   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
5700     {
5701       struct version_info *info;
5702
5703       info = ver_info (data, i);
5704       if (info->iv)
5705         free (info->iv);
5706       info->iv = NULL;
5707       info->has_nonlin_use = false;
5708       info->preserve_biv = false;
5709       info->inv_id = 0;
5710     }
5711   bitmap_clear (data->relevant);
5712   bitmap_clear (data->important_candidates);
5713
5714   for (i = 0; i < n_iv_uses (data); i++)
5715     {
5716       struct iv_use *use = iv_use (data, i);
5717
5718       free (use->iv);
5719       BITMAP_FREE (use->related_cands);
5720       for (j = 0; j < use->n_map_members; j++)
5721         if (use->cost_map[j].depends_on)
5722           BITMAP_FREE (use->cost_map[j].depends_on);
5723       free (use->cost_map);
5724       free (use);
5725     }
5726   VEC_truncate (iv_use_p, data->iv_uses, 0);
5727
5728   for (i = 0; i < n_iv_cands (data); i++)
5729     {
5730       struct iv_cand *cand = iv_cand (data, i);
5731
5732       if (cand->iv)
5733         free (cand->iv);
5734       if (cand->depends_on)
5735         BITMAP_FREE (cand->depends_on);
5736       free (cand);
5737     }
5738   VEC_truncate (iv_cand_p, data->iv_candidates, 0);
5739
5740   if (data->version_info_size < num_ssa_names)
5741     {
5742       data->version_info_size = 2 * num_ssa_names;
5743       free (data->version_info);
5744       data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
5745     }
5746
5747   data->max_inv_id = 0;
5748
5749   for (i = 0; VEC_iterate (tree, decl_rtl_to_reset, i, obj); i++)
5750     SET_DECL_RTL (obj, NULL_RTX);
5751
5752   VEC_truncate (tree, decl_rtl_to_reset, 0);
5753 }
5754
5755 /* Finalizes data structures used by the iv optimization pass.  LOOPS is the
5756    loop tree.  */
5757
5758 static void
5759 tree_ssa_iv_optimize_finalize (struct ivopts_data *data)
5760 {
5761   free_loop_data (data);
5762   free (data->version_info);
5763   BITMAP_FREE (data->relevant);
5764   BITMAP_FREE (data->important_candidates);
5765
5766   VEC_free (tree, heap, decl_rtl_to_reset);
5767   VEC_free (iv_use_p, heap, data->iv_uses);
5768   VEC_free (iv_cand_p, heap, data->iv_candidates);
5769 }
5770
5771 /* Optimizes the LOOP.  Returns true if anything changed.  */
5772
5773 static bool
5774 tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
5775 {
5776   bool changed = false;
5777   struct iv_ca *iv_ca;
5778   edge exit;
5779   basic_block *body;
5780
5781   gcc_assert (!data->niters);
5782   data->current_loop = loop;
5783   data->speed = optimize_loop_for_speed_p (loop);
5784
5785   if (dump_file && (dump_flags & TDF_DETAILS))
5786     {
5787       fprintf (dump_file, "Processing loop %d\n", loop->num);
5788
5789       exit = single_dom_exit (loop);
5790       if (exit)
5791         {
5792           fprintf (dump_file, "  single exit %d -> %d, exit condition ",
5793                    exit->src->index, exit->dest->index);
5794           print_gimple_stmt (dump_file, last_stmt (exit->src), 0, TDF_SLIM);
5795           fprintf (dump_file, "\n");
5796         }
5797
5798       fprintf (dump_file, "\n");
5799     }
5800
5801   body = get_loop_body (loop);
5802   renumber_gimple_stmt_uids_in_blocks (body, loop->num_nodes);
5803   free (body);
5804
5805   /* For each ssa name determines whether it behaves as an induction variable
5806      in some loop.  */
5807   if (!find_induction_variables (data))
5808     goto finish;
5809
5810   /* Finds interesting uses (item 1).  */
5811   find_interesting_uses (data);
5812   if (n_iv_uses (data) > MAX_CONSIDERED_USES)
5813     goto finish;
5814
5815   /* Finds candidates for the induction variables (item 2).  */
5816   find_iv_candidates (data);
5817
5818   /* Calculates the costs (item 3, part 1).  */
5819   determine_iv_costs (data);
5820   determine_use_iv_costs (data);
5821   determine_set_costs (data);
5822
5823   /* Find the optimal set of induction variables (item 3, part 2).  */
5824   iv_ca = find_optimal_iv_set (data);
5825   if (!iv_ca)
5826     goto finish;
5827   changed = true;
5828
5829   /* Create the new induction variables (item 4, part 1).  */
5830   create_new_ivs (data, iv_ca);
5831   iv_ca_free (&iv_ca);
5832
5833   /* Rewrite the uses (item 4, part 2).  */
5834   rewrite_uses (data);
5835
5836   /* Remove the ivs that are unused after rewriting.  */
5837   remove_unused_ivs (data);
5838
5839   /* We have changed the structure of induction variables; it might happen
5840      that definitions in the scev database refer to some of them that were
5841      eliminated.  */
5842   scev_reset ();
5843
5844 finish:
5845   free_loop_data (data);
5846
5847   return changed;
5848 }
5849
5850 /* Main entry point.  Optimizes induction variables in loops.  */
5851
5852 void
5853 tree_ssa_iv_optimize (void)
5854 {
5855   struct loop *loop;
5856   struct ivopts_data data;
5857   loop_iterator li;
5858
5859   tree_ssa_iv_optimize_init (&data);
5860
5861   /* Optimize the loops starting with the innermost ones.  */
5862   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
5863     {
5864       if (dump_file && (dump_flags & TDF_DETAILS))
5865         flow_loop_dump (loop, dump_file, NULL, 1);
5866
5867       tree_ssa_iv_optimize_loop (&data, loop);
5868     }
5869
5870   tree_ssa_iv_optimize_finalize (&data);
5871 }