]> git.ipfire.org Git - thirdparty/gcc.git/blobdiff - gcc/tree-ssa-loop-ivopts.c
Correct a function pre/postcondition [PR102403].
[thirdparty/gcc.git] / gcc / tree-ssa-loop-ivopts.c
index 008df2e549c6ee88cc763616c0533106d3ce88e2..4a498abe3b018b68f25c4fec3ae6321f7ad15bc3 100644 (file)
@@ -1,5 +1,5 @@
 /* Induction variable optimizations.
-   Copyright (C) 2003-2017 Free Software Foundation, Inc.
+   Copyright (C) 2003-2021 Free Software Foundation, Inc.
 
 This file is part of GCC.
 
@@ -64,7 +64,30 @@ along with GCC; see the file COPYING3.  If not see
    All of this is done loop by loop.  Doing it globally is theoretically
    possible, it might give a better performance and it might enable us
    to decide costs more precisely, but getting all the interactions right
-   would be complicated.  */
+   would be complicated.
+
+   For the targets supporting low-overhead loops, IVOPTs has to take care of
+   the loops which will probably be transformed in RTL doloop optimization,
+   to try to make selected IV candidate set optimal.  The process of doloop
+   support includes:
+
+   1) Analyze the current loop will be transformed to doloop or not, find and
+      mark its compare type IV use as doloop use (iv_group field doloop_p), and
+      set flag doloop_use_p of ivopts_data to notify subsequent processings on
+      doloop.  See analyze_and_mark_doloop_use and its callees for the details.
+      The target hook predict_doloop_p can be used for target specific checks.
+
+   2) Add one doloop dedicated IV cand {(may_be_zero ? 1 : (niter + 1)), +, -1},
+      set flag doloop_p of iv_cand, step cost is set as zero and no extra cost
+      like biv.  For cost determination between doloop IV cand and IV use, the
+      target hooks doloop_cost_for_generic and doloop_cost_for_address are
+      provided to add on extra costs for generic type and address type IV use.
+      Zero cost is assigned to the pair between doloop IV cand and doloop IV
+      use, and bound zero is set for IV elimination.
+
+   3) With the cost setting in step 2), the current cost model based IV
+      selection algorithm will process as usual, pick up doloop dedicated IV if
+      profitable.  */
 
 #include "config.h"
 #include "system.h"
@@ -102,34 +125,37 @@ along with GCC; see the file COPYING3.  If not see
 #include "tree-ssa.h"
 #include "cfgloop.h"
 #include "tree-scalar-evolution.h"
-#include "params.h"
 #include "tree-affine.h"
 #include "tree-ssa-propagate.h"
 #include "tree-ssa-address.h"
 #include "builtins.h"
 #include "tree-vectorizer.h"
+#include "dbgcnt.h"
+
+/* For lang_hooks.types.type_for_mode.  */
+#include "langhooks.h"
 
 /* FIXME: Expressions are expanded to RTL in this pass to determine the
    cost of different addressing modes.  This should be moved to a TBD
    interface between the GIMPLE and RTL worlds.  */
 
 /* The infinite cost.  */
-#define INFTY 10000000
+#define INFTY 1000000000
 
 /* Returns the expected number of loop iterations for LOOP.
    The average trip count is computed from profile data if it
    exists. */
 
 static inline HOST_WIDE_INT
-avg_loop_niter (struct loop *loop)
+avg_loop_niter (class loop *loop)
 {
   HOST_WIDE_INT niter = estimated_stmt_executions_int (loop);
   if (niter == -1)
     {
       niter = likely_max_stmt_executions_int (loop);
 
-      if (niter == -1 || niter > PARAM_VALUE (PARAM_AVG_LOOP_NITER))
-       return PARAM_VALUE (PARAM_AVG_LOOP_NITER);
+      if (niter == -1 || niter > param_avg_loop_niter)
+       return param_avg_loop_niter;
     }
 
   return niter;
@@ -166,17 +192,22 @@ struct version_info
 enum use_type
 {
   USE_NONLINEAR_EXPR,  /* Use in a nonlinear expression.  */
-  USE_ADDRESS,         /* Use in an address.  */
+  USE_REF_ADDRESS,     /* Use is an address for an explicit memory
+                          reference.  */
+  USE_PTR_ADDRESS,     /* Use is a pointer argument to a function in
+                          cases where the expansion of the function
+                          will turn the argument into a normal address.  */
   USE_COMPARE          /* Use is a compare.  */
 };
 
 /* Cost of a computation.  */
-struct comp_cost
+class comp_cost
 {
+public:
   comp_cost (): cost (0), complexity (0), scratch (0)
   {}
 
-  comp_cost (int cost, unsigned complexity, int scratch = 0)
+  comp_cost (int64_t cost, unsigned complexity, int64_t scratch = 0)
     : cost (cost), complexity (complexity), scratch (scratch)
   {}
 
@@ -216,16 +247,16 @@ struct comp_cost
   /* Returns true if COST1 is smaller or equal than COST2.  */
   friend bool operator<= (comp_cost cost1, comp_cost cost2);
 
-  int cost;            /* The runtime cost.  */
+  int64_t cost;                /* The runtime cost.  */
   unsigned complexity;  /* The estimate of the complexity of the code for
                           the computation (in no concrete units --
                           complexity field should be larger for more
                           complex expressions and addressing modes).  */
-  int scratch;         /* Scratch used during cost computation.  */
+  int64_t scratch;     /* Scratch used during cost computation.  */
 };
 
 static const comp_cost no_cost;
-static const comp_cost infinite_cost (INFTY, INFTY, INFTY);
+static const comp_cost infinite_cost (INFTY, 0, INFTY);
 
 bool
 comp_cost::infinite_cost_p ()
@@ -239,6 +270,7 @@ operator+ (comp_cost cost1, comp_cost cost2)
   if (cost1.infinite_cost_p () || cost2.infinite_cost_p ())
     return infinite_cost;
 
+  gcc_assert (cost1.cost + cost2.cost < infinite_cost.cost);
   cost1.cost += cost2.cost;
   cost1.complexity += cost2.complexity;
 
@@ -252,6 +284,7 @@ operator- (comp_cost cost1, comp_cost cost2)
     return infinite_cost;
 
   gcc_assert (!cost2.infinite_cost_p ());
+  gcc_assert (cost1.cost - cost2.cost < infinite_cost.cost);
 
   cost1.cost -= cost2.cost;
   cost1.complexity -= cost2.complexity;
@@ -269,9 +302,13 @@ comp_cost::operator+= (comp_cost cost)
 comp_cost
 comp_cost::operator+= (HOST_WIDE_INT c)
 {
+  if (c >= INFTY)
+    this->cost = INFTY;
+
   if (infinite_cost_p ())
     return *this;
 
+  gcc_assert (this->cost + c < infinite_cost.cost);
   this->cost += c;
 
   return *this;
@@ -283,6 +320,7 @@ comp_cost::operator-= (HOST_WIDE_INT c)
   if (infinite_cost_p ())
     return *this;
 
+  gcc_assert (this->cost - c < infinite_cost.cost);
   this->cost -= c;
 
   return *this;
@@ -291,6 +329,7 @@ comp_cost::operator-= (HOST_WIDE_INT c)
 comp_cost
 comp_cost::operator/= (HOST_WIDE_INT c)
 {
+  gcc_assert (c != 0);
   if (infinite_cost_p ())
     return *this;
 
@@ -305,6 +344,7 @@ comp_cost::operator*= (HOST_WIDE_INT c)
   if (infinite_cost_p ())
     return *this;
 
+  gcc_assert (this->cost * c < infinite_cost.cost);
   this->cost *= c;
 
   return *this;
@@ -342,8 +382,9 @@ operator<= (comp_cost cost1, comp_cost cost2)
 struct iv_inv_expr_ent;
 
 /* The candidate - cost pair.  */
-struct cost_pair
+class cost_pair
 {
+public:
   struct iv_cand *cand;        /* The candidate.  */
   comp_cost cost;      /* The cost.  */
   enum tree_code comp; /* For iv elimination, the comparison.  */
@@ -362,12 +403,15 @@ struct iv_use
   unsigned id;         /* The id of the use.  */
   unsigned group_id;   /* The group id the use belongs to.  */
   enum use_type type;  /* Type of the use.  */
+  tree mem_type;       /* The memory type to use when testing whether an
+                          address is legitimate, and what the address's
+                          cost is.  */
   struct iv *iv;       /* The induction variable it is based on.  */
   gimple *stmt;                /* Statement in that it occurs.  */
   tree *op_p;          /* The place where it occurs.  */
 
   tree addr_base;      /* Base address with const offset stripped.  */
-  unsigned HOST_WIDE_INT addr_offset;
+  poly_uint64_pod addr_offset;
                        /* Const offset stripped from base address.  */
 };
 
@@ -383,9 +427,11 @@ struct iv_group
   /* Number of IV candidates in the cost_map.  */
   unsigned n_map_members;
   /* The costs wrto the iv candidates.  */
-  struct cost_pair *cost_map;
+  class cost_pair *cost_map;
   /* The selected candidate for the group.  */
   struct iv_cand *selected;
+  /* To indicate this is a doloop use group.  */
+  bool doloop_p;
   /* Uses in the group.  */
   vec<struct iv_use *> vuses;
 };
@@ -426,11 +472,13 @@ struct iv_cand
                           be hoisted out of loop.  */
   struct iv *orig_iv;  /* The original iv if this cand is added from biv with
                           smaller type.  */
+  bool doloop_p;       /* Whether this is a doloop candidate.  */
 };
 
 /* Hashtable entry for common candidate derived from iv uses.  */
-struct iv_common_cand
+class iv_common_cand
 {
+public:
   tree base;
   tree step;
   /* IV uses from which this common candidate is derived.  */
@@ -506,6 +554,14 @@ struct iv_inv_expr_hasher : free_ptr_hash <iv_inv_expr_ent>
   static inline bool equal (const iv_inv_expr_ent *, const iv_inv_expr_ent *);
 };
 
+/* Return true if uses of type TYPE represent some form of address.  */
+
+inline bool
+address_p (use_type type)
+{
+  return type == USE_REF_ADDRESS || type == USE_PTR_ADDRESS;
+}
+
 /* Hash function for loop invariant expressions.  */
 
 inline hashval_t
@@ -527,8 +583,8 @@ iv_inv_expr_hasher::equal (const iv_inv_expr_ent *expr1,
 struct ivopts_data
 {
   /* The currently optimized loop.  */
-  struct loop *current_loop;
-  source_location loop_loc;
+  class loop *current_loop;
+  location_t loop_loc;
 
   /* Numbers of iterations for all exits of the current loop.  */
   hash_map<edge, tree_niter_desc *> *niters;
@@ -567,6 +623,9 @@ struct ivopts_data
   /* The common candidates.  */
   vec<iv_common_cand *> iv_common_cands;
 
+  /* Hash map recording base object information of tree exp.  */
+  hash_map<tree, tree> *base_object_map;
+
   /* The maximum invariant variable id.  */
   unsigned max_inv_var_id;
 
@@ -591,12 +650,16 @@ struct ivopts_data
 
   /* Whether the loop body can only be exited via single exit.  */
   bool loop_single_exit_p;
+
+  /* Whether the loop has doloop comparison use.  */
+  bool doloop_use_p;
 };
 
 /* An assignment of iv candidates to uses.  */
 
-struct iv_ca
+class iv_ca
 {
+public:
   /* The number of uses covered by the assignment.  */
   unsigned upto;
 
@@ -604,7 +667,7 @@ struct iv_ca
   unsigned bad_groups;
 
   /* Candidate assigned to a use, together with the related costs.  */
-  struct cost_pair **cand_for_group;
+  class cost_pair **cand_for_group;
 
   /* Number of times each candidate is used.  */
   unsigned *n_cand_uses;
@@ -623,7 +686,7 @@ struct iv_ca
   comp_cost cand_use_cost;
 
   /* Total cost of candidates.  */
-  unsigned cand_cost;
+  int64_t cand_cost;
 
   /* Number of times each invariant variable is used.  */
   unsigned *n_inv_var_uses;
@@ -643,10 +706,10 @@ struct iv_ca_delta
   struct iv_group *group;
 
   /* An old assignment (for rollback purposes).  */
-  struct cost_pair *old_cp;
+  class cost_pair *old_cp;
 
   /* A new assignment.  */
-  struct cost_pair *new_cp;
+  class cost_pair *new_cp;
 
   /* Next change in the list.  */
   struct iv_ca_delta *next;
@@ -655,19 +718,19 @@ struct iv_ca_delta
 /* Bound on number of candidates below that all candidates are considered.  */
 
 #define CONSIDER_ALL_CANDIDATES_BOUND \
-  ((unsigned) PARAM_VALUE (PARAM_IV_CONSIDER_ALL_CANDIDATES_BOUND))
+  ((unsigned) param_iv_consider_all_candidates_bound)
 
 /* If there are more iv occurrences, we just give up (it is quite unlikely that
    optimizing such a loop would help, and it would take ages).  */
 
 #define MAX_CONSIDERED_GROUPS \
-  ((unsigned) PARAM_VALUE (PARAM_IV_MAX_CONSIDERED_USES))
+  ((unsigned) param_iv_max_considered_uses)
 
 /* If there are at most this number of ivs in the set, try removing unnecessary
    ivs from the set always.  */
 
 #define ALWAYS_PRUNE_CAND_SET_BOUND \
-  ((unsigned) PARAM_VALUE (PARAM_IV_ALWAYS_PRUNE_CAND_SET_BOUND))
+  ((unsigned) param_iv_always_prune_cand_set_bound)
 
 /* The list of trees for that the decl_rtl field must be reset is stored
    here.  */
@@ -679,7 +742,7 @@ static comp_cost force_expr_to_var_cost (tree, bool);
 /* The single loop exit if it dominates the latch, NULL otherwise.  */
 
 edge
-single_dom_exit (struct loop *loop)
+single_dom_exit (class loop *loop)
 {
   edge exit = single_exit (loop);
 
@@ -768,8 +831,10 @@ dump_groups (FILE *file, struct ivopts_data *data)
       fprintf (file, "Group %d:\n", group->id);
       if (group->type == USE_NONLINEAR_EXPR)
        fprintf (file, "  Type:\tGENERIC\n");
-      else if (group->type == USE_ADDRESS)
-       fprintf (file, "  Type:\tADDRESS\n");
+      else if (group->type == USE_REF_ADDRESS)
+       fprintf (file, "  Type:\tREFERENCE ADDRESS\n");
+      else if (group->type == USE_PTR_ADDRESS)
+       fprintf (file, "  Type:\tPOINTER ARGUMENT ADDRESS\n");
       else
        {
          gcc_assert (group->type == USE_COMPARE);
@@ -858,7 +923,7 @@ name_info (struct ivopts_data *data, tree name)
    emitted in LOOP.  */
 
 static bool
-stmt_after_ip_normal_pos (struct loop *loop, gimple *stmt)
+stmt_after_ip_normal_pos (class loop *loop, gimple *stmt)
 {
   basic_block bb = ip_normal_pos (loop), sbb = gimple_bb (stmt);
 
@@ -899,7 +964,7 @@ stmt_after_inc_pos (struct iv_cand *cand, gimple *stmt, bool true_if_equal)
    CAND is incremented in LOOP.  */
 
 static bool
-stmt_after_increment (struct loop *loop, struct iv_cand *cand, gimple *stmt)
+stmt_after_increment (class loop *loop, struct iv_cand *cand, gimple *stmt)
 {
   switch (cand->pos)
     {
@@ -921,36 +986,19 @@ stmt_after_increment (struct loop *loop, struct iv_cand *cand, gimple *stmt)
     }
 }
 
-/* Returns true if EXP is a ssa name that occurs in an abnormal phi node.  */
+/* walk_tree callback for contains_abnormal_ssa_name_p.  */
 
-static bool
-abnormal_ssa_name_p (tree exp)
+static tree
+contains_abnormal_ssa_name_p_1 (tree *tp, int *walk_subtrees, void *)
 {
-  if (!exp)
-    return false;
+  if (TREE_CODE (*tp) == SSA_NAME
+      && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (*tp))
+    return *tp;
 
-  if (TREE_CODE (exp) != SSA_NAME)
-    return false;
-
-  return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp) != 0;
-}
-
-/* Returns false if BASE or INDEX contains a ssa name that occurs in an
-   abnormal phi node.  Callback for for_each_index.  */
-
-static bool
-idx_contains_abnormal_ssa_name_p (tree base, tree *index,
-                                 void *data ATTRIBUTE_UNUSED)
-{
-  if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
-    {
-      if (abnormal_ssa_name_p (TREE_OPERAND (base, 2)))
-       return false;
-      if (abnormal_ssa_name_p (TREE_OPERAND (base, 3)))
-       return false;
-    }
+  if (!EXPR_P (*tp))
+    *walk_subtrees = 0;
 
-  return !abnormal_ssa_name_p (*index);
+  return NULL_TREE;
 }
 
 /* Returns true if EXPR contains a ssa name that occurs in an
@@ -959,60 +1007,17 @@ idx_contains_abnormal_ssa_name_p (tree base, tree *index,
 bool
 contains_abnormal_ssa_name_p (tree expr)
 {
-  enum tree_code code;
-  enum tree_code_class codeclass;
-
-  if (!expr)
-    return false;
-
-  code = TREE_CODE (expr);
-  codeclass = TREE_CODE_CLASS (code);
-
-  if (code == SSA_NAME)
-    return SSA_NAME_OCCURS_IN_ABNORMAL_PHI (expr) != 0;
-
-  if (code == INTEGER_CST
-      || is_gimple_min_invariant (expr))
-    return false;
-
-  if (code == ADDR_EXPR)
-    return !for_each_index (&TREE_OPERAND (expr, 0),
-                           idx_contains_abnormal_ssa_name_p,
-                           NULL);
-
-  if (code == COND_EXPR)
-    return contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0))
-      || contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1))
-      || contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 2));
-
-  switch (codeclass)
-    {
-    case tcc_binary:
-    case tcc_comparison:
-      if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 1)))
-       return true;
-
-      /* Fallthru.  */
-    case tcc_unary:
-      if (contains_abnormal_ssa_name_p (TREE_OPERAND (expr, 0)))
-       return true;
-
-      break;
-
-    default:
-      gcc_unreachable ();
-    }
-
-  return false;
+  return walk_tree_without_duplicates
+          (&expr, contains_abnormal_ssa_name_p_1, NULL) != NULL_TREE;
 }
 
 /*  Returns the structure describing number of iterations determined from
     EXIT of DATA->current_loop, or NULL if something goes wrong.  */
 
-static struct tree_niter_desc *
+static class tree_niter_desc *
 niter_for_exit (struct ivopts_data *data, edge exit)
 {
-  struct tree_niter_desc *desc;
+  class tree_niter_desc *desc;
   tree_niter_desc **slot;
 
   if (!data->niters)
@@ -1028,7 +1033,7 @@ niter_for_exit (struct ivopts_data *data, edge exit)
       /* Try to determine number of iterations.  We cannot safely work with ssa
         names that appear in phi nodes on abnormal edges, so that we do not
         create overlapping life ranges for them (PR 27283).  */
-      desc = XNEW (struct tree_niter_desc);
+      desc = XNEW (class tree_niter_desc);
       if (!number_of_iterations_exit (data->current_loop,
                                      exit, desc, true)
          || contains_abnormal_ssa_name_p (desc->niter))
@@ -1048,7 +1053,7 @@ niter_for_exit (struct ivopts_data *data, edge exit)
    single dominating exit of DATA->current_loop, or NULL if something
    goes wrong.  */
 
-static struct tree_niter_desc *
+static class tree_niter_desc *
 niter_for_single_dom_exit (struct ivopts_data *data)
 {
   edge exit = single_dom_exit (data->current_loop);
@@ -1076,59 +1081,68 @@ tree_ssa_iv_optimize_init (struct ivopts_data *data)
   data->vcands.create (20);
   data->inv_expr_tab = new hash_table<iv_inv_expr_hasher> (10);
   data->name_expansion_cache = NULL;
+  data->base_object_map = NULL;
   data->iv_common_cand_tab = new hash_table<iv_common_cand_hasher> (10);
   data->iv_common_cands.create (20);
   decl_rtl_to_reset.create (20);
   gcc_obstack_init (&data->iv_obstack);
 }
 
-/* Returns a memory object to that EXPR points.  In case we are able to
-   determine that it does not point to any such object, NULL is returned.  */
+/* walk_tree callback for determine_base_object.  */
 
 static tree
-determine_base_object (tree expr)
+determine_base_object_1 (tree *tp, int *walk_subtrees, void *wdata)
 {
-  enum tree_code code = TREE_CODE (expr);
-  tree base, obj;
-
-  /* If this is a pointer casted to any type, we need to determine
-     the base object for the pointer; so handle conversions before
-     throwing away non-pointer expressions.  */
-  if (CONVERT_EXPR_P (expr))
-    return determine_base_object (TREE_OPERAND (expr, 0));
-
-  if (!POINTER_TYPE_P (TREE_TYPE (expr)))
-    return NULL_TREE;
-
-  switch (code)
+  tree_code code = TREE_CODE (*tp);
+  tree obj = NULL_TREE;
+  if (code == ADDR_EXPR)
     {
-    case INTEGER_CST:
-      return NULL_TREE;
-
-    case ADDR_EXPR:
-      obj = TREE_OPERAND (expr, 0);
-      base = get_base_address (obj);
-
+      tree base = get_base_address (TREE_OPERAND (*tp, 0));
       if (!base)
-       return expr;
-
-      if (TREE_CODE (base) == MEM_REF)
-       return determine_base_object (TREE_OPERAND (base, 0));
+       obj = *tp;
+      else if (TREE_CODE (base) != MEM_REF)
+       obj = fold_convert (ptr_type_node, build_fold_addr_expr (base));
+    }
+  else if (code == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (*tp)))
+       obj = fold_convert (ptr_type_node, *tp);
 
-      return fold_convert (ptr_type_node,
-                          build_fold_addr_expr (base));
+  if (!obj)
+    {
+      if (!EXPR_P (*tp))
+       *walk_subtrees = 0;
 
-    case POINTER_PLUS_EXPR:
-      return determine_base_object (TREE_OPERAND (expr, 0));
+      return NULL_TREE;
+    }
+  /* Record special node for multiple base objects and stop.  */
+  if (*static_cast<tree *> (wdata))
+    {
+      *static_cast<tree *> (wdata) = integer_zero_node;
+      return integer_zero_node;
+    }
+  /* Record the base object and continue looking.  */
+  *static_cast<tree *> (wdata) = obj;
+  return NULL_TREE;
+}
 
-    case PLUS_EXPR:
-    case MINUS_EXPR:
-      /* Pointer addition is done solely using POINTER_PLUS_EXPR.  */
-      gcc_unreachable ();
+/* Returns a memory object to that EXPR points with caching.  Return NULL if we
+   are able to determine that it does not point to any such object; specially
+   return integer_zero_node if EXPR contains multiple base objects.  */
 
-    default:
-      return fold_convert (ptr_type_node, expr);
+static tree
+determine_base_object (struct ivopts_data *data, tree expr)
+{
+  tree *slot, obj = NULL_TREE;
+  if (data->base_object_map)
+    {
+      if ((slot = data->base_object_map->get(expr)) != NULL)
+       return *slot;
     }
+  else
+    data->base_object_map = new hash_map<tree, tree>;
+
+  (void) walk_tree_without_duplicates (&expr, determine_base_object_1, &obj);
+  data->base_object_map->put (expr, obj);
+  return obj;
 }
 
 /* Return true if address expression with non-DECL_P operand appears
@@ -1186,7 +1200,7 @@ alloc_iv (struct ivopts_data *data, tree base, tree step,
     }
 
   iv->base = base;
-  iv->base_object = determine_base_object (base);
+  iv->base_object = determine_base_object (data, base);
   iv->step = step;
   iv->biv_p = false;
   iv->nonlin_use = NULL;
@@ -1235,7 +1249,11 @@ get_iv (struct ivopts_data *data, tree var)
 
       if (!bb
          || !flow_bb_inside_loop_p (data->current_loop, bb))
-       set_iv (data, var, var, build_int_cst (type, 0), true);
+       {
+         if (POINTER_TYPE_P (type))
+           type = sizetype;
+         set_iv (data, var, var, build_int_cst (type, 0), true);
+       }
     }
 
   return name_info (data, var)->iv;
@@ -1277,7 +1295,7 @@ find_bivs (struct ivopts_data *data)
   affine_iv iv;
   tree step, type, base, stop;
   bool found = false;
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   gphi_iterator psi;
 
   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
@@ -1335,7 +1353,7 @@ mark_bivs (struct ivopts_data *data)
   gimple *def;
   tree var;
   struct iv *iv, *incr_iv;
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   basic_block incr_bb;
   gphi_iterator psi;
 
@@ -1382,7 +1400,7 @@ static bool
 find_givs_in_stmt_scev (struct ivopts_data *data, gimple *stmt, affine_iv *iv)
 {
   tree lhs, stop;
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
 
   iv->base = NULL_TREE;
   iv->step = NULL_TREE;
@@ -1409,9 +1427,9 @@ find_givs_in_stmt_scev (struct ivopts_data *data, gimple *stmt, affine_iv *iv)
     return false;
 
   /* If STMT could throw, then do not consider STMT as defining a GIV.
-     While this will suppress optimizations, we can not safely delete this
+     While this will suppress optimizations, we cannot safely delete this
      GIV and associated statements, even if it appears it is not used.  */
-  if (stmt_could_throw_p (stmt))
+  if (stmt_could_throw_p (cfun, stmt))
     return false;
 
   return true;
@@ -1446,7 +1464,7 @@ find_givs_in_bb (struct ivopts_data *data, basic_block bb)
 static void
 find_givs (struct ivopts_data *data)
 {
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   basic_block *body = get_loop_body_in_dom_order (loop);
   unsigned i;
 
@@ -1472,7 +1490,7 @@ find_induction_variables (struct ivopts_data *data)
 
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
-      struct tree_niter_desc *niter = niter_for_single_dom_exit (data);
+      class tree_niter_desc *niter = niter_for_single_dom_exit (data);
 
       if (niter)
        {
@@ -1500,19 +1518,21 @@ find_induction_variables (struct ivopts_data *data)
 
 /* Records a use of TYPE at *USE_P in STMT whose value is IV in GROUP.
    For address type use, ADDR_BASE is the stripped IV base, ADDR_OFFSET
-   is the const offset stripped from IV base; for other types use, both
-   are zero by default.  */
+   is the const offset stripped from IV base and MEM_TYPE is the type
+   of the memory being addressed.  For uses of other types, ADDR_BASE
+   and ADDR_OFFSET are zero by default and MEM_TYPE is NULL_TREE.  */
 
 static struct iv_use *
 record_use (struct iv_group *group, tree *use_p, struct iv *iv,
-           gimple *stmt, enum use_type type, tree addr_base,
-           unsigned HOST_WIDE_INT addr_offset)
+           gimple *stmt, enum use_type type, tree mem_type,
+           tree addr_base, poly_uint64 addr_offset)
 {
   struct iv_use *use = XCNEW (struct iv_use);
 
   use->id = group->vuses.length ();
   use->group_id = group->id;
   use->type = type;
+  use->mem_type = mem_type;
   use->iv = iv;
   use->stmt = stmt;
   use->op_p = use_p;
@@ -1550,9 +1570,6 @@ record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
 }
 
-static tree
-strip_offset (tree expr, unsigned HOST_WIDE_INT *offset);
-
 /* Record a group of TYPE.  */
 
 static struct iv_group *
@@ -1564,24 +1581,28 @@ record_group (struct ivopts_data *data, enum use_type type)
   group->type = type;
   group->related_cands = BITMAP_ALLOC (NULL);
   group->vuses.create (1);
+  group->doloop_p = false;
 
   data->vgroups.safe_push (group);
   return group;
 }
 
 /* Record a use of TYPE at *USE_P in STMT whose value is IV in a group.
-   New group will be created if there is no existing group for the use.  */
+   New group will be created if there is no existing group for the use.
+   MEM_TYPE is the type of memory being addressed, or NULL if this
+   isn't an address reference.  */
 
 static struct iv_use *
 record_group_use (struct ivopts_data *data, tree *use_p,
-                 struct iv *iv, gimple *stmt, enum use_type type)
+                 struct iv *iv, gimple *stmt, enum use_type type,
+                 tree mem_type)
 {
   tree addr_base = NULL;
   struct iv_group *group = NULL;
-  unsigned HOST_WIDE_INT addr_offset = 0;
+  poly_uint64 addr_offset = 0;
 
   /* Record non address type use in a new group.  */
-  if (type == USE_ADDRESS && iv->base_object)
+  if (address_p (type))
     {
       unsigned int i;
 
@@ -1592,7 +1613,7 @@ record_group_use (struct ivopts_data *data, tree *use_p,
 
          group = data->vgroups[i];
          use = group->vuses[0];
-         if (use->type != USE_ADDRESS || !use->iv->base_object)
+         if (!address_p (use->type))
            continue;
 
          /* Check if it has the same stripped base and step.  */
@@ -1608,7 +1629,8 @@ record_group_use (struct ivopts_data *data, tree *use_p,
   if (!group)
     group = record_group (data, type);
 
-  return record_use (group, use_p, iv, stmt, type, addr_base, addr_offset);
+  return record_use (group, use_p, iv, stmt, type, mem_type,
+                    addr_base, addr_offset);
 }
 
 /* Checks whether the use OP is interesting and if so, records it.  */
@@ -1642,7 +1664,7 @@ find_interesting_uses_op (struct ivopts_data *data, tree op)
   stmt = SSA_NAME_DEF_STMT (op);
   gcc_assert (gimple_code (stmt) == GIMPLE_PHI || is_gimple_assign (stmt));
 
-  use = record_group_use (data, NULL, iv, stmt, USE_NONLINEAR_EXPR);
+  use = record_group_use (data, NULL, iv, stmt, USE_NONLINEAR_EXPR, NULL_TREE);
   iv->nonlin_use = use;
   return use;
 }
@@ -1758,10 +1780,10 @@ find_interesting_uses_cond (struct ivopts_data *data, gimple *stmt)
       return;
     }
 
-  record_group_use (data, var_p, var_iv, stmt, USE_COMPARE);
+  record_group_use (data, var_p, var_iv, stmt, USE_COMPARE, NULL_TREE);
   /* Record compare type iv_use for iv on the other side of comparison.  */
   if (ret == COMP_IV_EXPR_2)
-    record_group_use (data, bound_p, bound_iv, stmt, USE_COMPARE);
+    record_group_use (data, bound_p, bound_iv, stmt, USE_COMPARE, NULL_TREE);
 }
 
 /* Returns the outermost loop EXPR is obviously invariant in
@@ -1769,8 +1791,8 @@ find_interesting_uses_cond (struct ivopts_data *data, gimple *stmt)
    outside of the returned loop.  Returns NULL if EXPR is not
    even obviously invariant in LOOP.  */
 
-struct loop *
-outermost_invariant_loop_for_expr (struct loop *loop, tree expr)
+class loop *
+outermost_invariant_loop_for_expr (class loop *loop, tree expr)
 {
   basic_block def_bb;
   unsigned i, len;
@@ -1799,7 +1821,7 @@ outermost_invariant_loop_for_expr (struct loop *loop, tree expr)
   len = TREE_OPERAND_LENGTH (expr);
   for (i = 0; i < len; i++)
     {
-      struct loop *ivloop;
+      class loop *ivloop;
       if (!TREE_OPERAND (expr, i))
        continue;
 
@@ -1817,7 +1839,7 @@ outermost_invariant_loop_for_expr (struct loop *loop, tree expr)
    should not be the function body.  */
 
 bool
-expr_invariant_in_loop_p (struct loop *loop, tree expr)
+expr_invariant_in_loop_p (class loop *loop, tree expr)
 {
   basic_block def_bb;
   unsigned i, len;
@@ -2010,7 +2032,7 @@ idx_find_step (tree base, tree *idx, void *data)
   struct iv *iv;
   bool use_overflow_semantics = false;
   tree step, iv_base, iv_step, lbound, off;
-  struct loop *loop = dta->ivopts_data->current_loop;
+  class loop *loop = dta->ivopts_data->current_loop;
 
   /* If base is a component ref, require that the offset of the reference
      be invariant.  */
@@ -2160,14 +2182,20 @@ constant_multiple_of (tree top, tree bot, widest_int *mul)
       if (TREE_CODE (bot) != INTEGER_CST)
        return false;
 
-      p0 = widest_int::from (top, SIGNED);
-      p1 = widest_int::from (bot, SIGNED);
+      p0 = widest_int::from (wi::to_wide (top), SIGNED);
+      p1 = widest_int::from (wi::to_wide (bot), SIGNED);
       if (p1 == 0)
        return false;
       *mul = wi::sext (wi::divmod_trunc (p0, p1, SIGNED, &res), precision);
       return res == 0;
 
     default:
+      if (POLY_INT_CST_P (top)
+         && POLY_INT_CST_P (bot)
+         && constant_multiple_p (wi::to_poly_widest (top),
+                                 wi::to_poly_widest (bot), mul))
+       return true;
+
       return false;
     }
 }
@@ -2209,6 +2237,10 @@ may_be_nonaddressable_p (tree expr)
 {
   switch (TREE_CODE (expr))
     {
+    case VAR_DECL:
+      /* Check if it's a register variable.  */
+      return DECL_HARD_REGISTER (expr);
+
     case TARGET_MEM_REF:
       /* TARGET_MEM_REFs are translated directly to valid MEMs on the
         target, thus they are always addressable.  */
@@ -2370,7 +2402,7 @@ find_interesting_uses_address (struct ivopts_data *data, gimple *stmt,
   if (civ->base_object == NULL_TREE)
     goto fail;
 
-  record_group_use (data, op_p, civ, stmt, USE_ADDRESS);
+  record_group_use (data, op_p, civ, stmt, USE_REF_ADDRESS, TREE_TYPE (*op_p));
   return;
 
 fail:
@@ -2393,6 +2425,59 @@ find_invariants_stmt (struct ivopts_data *data, gimple *stmt)
     }
 }
 
+/* CALL calls an internal function.  If operand *OP_P will become an
+   address when the call is expanded, return the type of the memory
+   being addressed, otherwise return null.  */
+
+static tree
+get_mem_type_for_internal_fn (gcall *call, tree *op_p)
+{
+  switch (gimple_call_internal_fn (call))
+    {
+    case IFN_MASK_LOAD:
+    case IFN_MASK_LOAD_LANES:
+    case IFN_LEN_LOAD:
+      if (op_p == gimple_call_arg_ptr (call, 0))
+       return TREE_TYPE (gimple_call_lhs (call));
+      return NULL_TREE;
+
+    case IFN_MASK_STORE:
+    case IFN_MASK_STORE_LANES:
+    case IFN_LEN_STORE:
+      if (op_p == gimple_call_arg_ptr (call, 0))
+       return TREE_TYPE (gimple_call_arg (call, 3));
+      return NULL_TREE;
+
+    default:
+      return NULL_TREE;
+    }
+}
+
+/* IV is a (non-address) iv that describes operand *OP_P of STMT.
+   Return true if the operand will become an address when STMT
+   is expanded and record the associated address use if so.  */
+
+static bool
+find_address_like_use (struct ivopts_data *data, gimple *stmt, tree *op_p,
+                      struct iv *iv)
+{
+  /* Fail if base object of this memory reference is unknown.  */
+  if (iv->base_object == NULL_TREE)
+    return false;
+
+  tree mem_type = NULL_TREE;
+  if (gcall *call = dyn_cast <gcall *> (stmt))
+    if (gimple_call_internal_p (call))
+      mem_type = get_mem_type_for_internal_fn (call, op_p);
+  if (mem_type)
+    {
+      iv = alloc_iv (data, iv->base, iv->step);
+      record_group_use (data, op_p, iv, stmt, USE_PTR_ADDRESS, mem_type);
+      return true;
+    }
+  return false;
+}
+
 /* Finds interesting uses of induction variables in the statement STMT.  */
 
 static void
@@ -2477,7 +2562,8 @@ find_interesting_uses_stmt (struct ivopts_data *data, gimple *stmt)
       if (!iv)
        continue;
 
-      find_interesting_uses_op (data, op);
+      if (!find_address_like_use (data, stmt, use_p->use, iv))
+       find_interesting_uses_op (data, op);
     }
 }
 
@@ -2506,16 +2592,16 @@ find_interesting_uses_outside (struct ivopts_data *data, edge exit)
 static GTY (()) vec<rtx, va_gc> *addr_list;
 
 static bool
-addr_offset_valid_p (struct iv_use *use, HOST_WIDE_INT offset)
+addr_offset_valid_p (struct iv_use *use, poly_int64 offset)
 {
   rtx reg, addr;
   unsigned list_index;
   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
-  machine_mode addr_mode, mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
+  machine_mode addr_mode, mem_mode = TYPE_MODE (use->mem_type);
 
   list_index = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
   if (list_index >= vec_safe_length (addr_list))
-    vec_safe_grow_cleared (addr_list, list_index + MAX_MACHINE_MODE);
+    vec_safe_grow_cleared (addr_list, list_index + MAX_MACHINE_MODE, true);
 
   addr = (*addr_list)[list_index];
   if (!addr)
@@ -2540,10 +2626,7 @@ group_compare_offset (const void *a, const void *b)
   const struct iv_use *const *u1 = (const struct iv_use *const *) a;
   const struct iv_use *const *u2 = (const struct iv_use *const *) b;
 
-  if ((*u1)->addr_offset != (*u2)->addr_offset)
-    return (*u1)->addr_offset < (*u2)->addr_offset ? -1 : 1;
-  else
-    return 0;
+  return compare_sizes_for_sort ((*u1)->addr_offset, (*u2)->addr_offset);
 }
 
 /* Check if small groups should be split.  Return true if no group
@@ -2571,10 +2654,11 @@ split_small_address_groups_p (struct ivopts_data *data)
       if (group->vuses.length () == 1)
        continue;
 
-      gcc_assert (group->type == USE_ADDRESS);
+      gcc_assert (address_p (group->type));
       if (group->vuses.length () == 2)
        {
-         if (group->vuses[0]->addr_offset > group->vuses[1]->addr_offset)
+         if (compare_sizes_for_sort (group->vuses[0]->addr_offset,
+                                     group->vuses[1]->addr_offset) > 0)
            std::swap (group->vuses[0], group->vuses[1]);
        }
       else
@@ -2586,7 +2670,7 @@ split_small_address_groups_p (struct ivopts_data *data)
       distinct = 1;
       for (pre = group->vuses[0], j = 1; j < group->vuses.length (); j++)
        {
-         if (group->vuses[j]->addr_offset != pre->addr_offset)
+         if (maybe_ne (group->vuses[j]->addr_offset, pre->addr_offset))
            {
              pre = group->vuses[j];
              distinct++;
@@ -2622,18 +2706,18 @@ split_address_groups (struct ivopts_data *data)
       if (group->vuses.length () == 1)
        continue;
 
-      gcc_assert (group->type == USE_ADDRESS);
+      gcc_assert (address_p (use->type));
 
       for (j = 1; j < group->vuses.length ();)
        {
          struct iv_use *next = group->vuses[j];
-         HOST_WIDE_INT offset = next->addr_offset - use->addr_offset;
+         poly_int64 offset = next->addr_offset - use->addr_offset;
 
          /* Split group if aksed to, or the offset against the first
             use can't fit in offset part of addressing mode.  IV uses
             having the same offset are still kept in one group.  */
-         if (offset != 0 &&
-             (split_p || !addr_offset_valid_p (use, offset)))
+         if (maybe_ne (offset, 0)
+             && (split_p || !addr_offset_valid_p (use, offset)))
            {
              if (!new_group)
                new_group = record_group (data, group->type);
@@ -2694,12 +2778,13 @@ find_interesting_uses (struct ivopts_data *data)
 
 static tree
 strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
-               HOST_WIDE_INT *offset)
+               poly_int64 *offset)
 {
   tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
   enum tree_code code;
   tree type, orig_type = TREE_TYPE (expr);
-  HOST_WIDE_INT off0, off1, st;
+  poly_int64 off0, off1;
+  HOST_WIDE_INT st;
   tree orig_expr = expr;
 
   STRIP_NOPS (expr);
@@ -2710,14 +2795,6 @@ strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
 
   switch (code)
     {
-    case INTEGER_CST:
-      if (!cst_and_fits_in_hwi (expr)
-         || integer_zerop (expr))
-       return orig_expr;
-
-      *offset = int_cst_value (expr);
-      return build_int_cst (orig_type, 0);
-
     case POINTER_PLUS_EXPR:
     case PLUS_EXPR:
     case MINUS_EXPR:
@@ -2835,6 +2912,8 @@ strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
       break;
 
     default:
+      if (ptrdiff_tree_p (expr, offset) && maybe_ne (*offset, 0))
+       return build_int_cst (orig_type, 0);
       return orig_expr;
     }
 
@@ -2863,10 +2942,10 @@ strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
 
 /* Strips constant offsets from EXPR and stores them to OFFSET.  */
 
-static tree
-strip_offset (tree expr, unsigned HOST_WIDE_INT *offset)
+tree
+strip_offset (tree expr, poly_uint64_pod *offset)
 {
-  HOST_WIDE_INT off;
+  poly_int64 off;
   tree core = strip_offset_1 (expr, false, false, &off);
   *offset = off;
   return core;
@@ -2920,7 +2999,10 @@ find_inv_vars_cb (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
 
       if (!bb || !flow_bb_inside_loop_p (idata->current_loop, bb))
        {
-         set_iv (idata, op, op, build_int_cst (TREE_TYPE (op), 0), true);
+         tree steptype = TREE_TYPE (op);
+         if (POINTER_TYPE_P (steptype))
+           steptype = sizetype;
+         set_iv (idata, op, op, build_int_cst (steptype, 0), true);
          record_invariant (idata, op, false);
        }
     }
@@ -2956,7 +3038,7 @@ find_inv_vars (struct ivopts_data *data, tree *expr_p, bitmap *inv_vars)
    It's hard to make decision whether constant part should be stripped
    or not.  We choose to not strip based on below facts:
      1) We need to count ADD cost for constant part if it's stripped,
-       which is't always trivial where this functions is called.
+       which isn't always trivial where this functions is called.
      2) Stripping constant away may be conflict with following loop
        invariant hoisting pass.
      3) Not stripping constant away results in more invariant exprs,
@@ -2967,7 +3049,8 @@ get_loop_invariant_expr (struct ivopts_data *data, tree inv_expr)
 {
   STRIP_NOPS (inv_expr);
 
-  if (TREE_CODE (inv_expr) == INTEGER_CST || TREE_CODE (inv_expr) == SSA_NAME)
+  if (poly_int_tree_p (inv_expr)
+      || TREE_CODE (inv_expr) == SSA_NAME)
     return NULL;
 
   /* Don't strip constant part away as we used to.  */
@@ -2995,10 +3078,10 @@ get_loop_invariant_expr (struct ivopts_data *data, tree inv_expr)
    replacement of the final value of the iv by a direct computation.  */
 
 static struct iv_cand *
-add_candidate_1 (struct ivopts_data *data,
-                tree base, tree step, bool important, enum iv_position pos,
-                struct iv_use *use, gimple *incremented_at,
-                struct iv *orig_iv = NULL)
+add_candidate_1 (struct ivopts_data *data, tree base, tree step, bool important,
+                enum iv_position pos, struct iv_use *use,
+                gimple *incremented_at, struct iv *orig_iv = NULL,
+                bool doloop = false)
 {
   unsigned i;
   struct iv_cand *cand = NULL;
@@ -3057,14 +3140,18 @@ add_candidate_1 (struct ivopts_data *data,
       cand->pos = pos;
       if (pos != IP_ORIGINAL)
        {
-         cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
+         if (doloop)
+           cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "doloop");
+         else
+           cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
          cand->var_after = cand->var_before;
        }
       cand->important = important;
       cand->incremented_at = incremented_at;
+      cand->doloop_p = doloop;
       data->vcands.safe_push (cand);
 
-      if (TREE_CODE (step) != INTEGER_CST)
+      if (!poly_int_tree_p (step))
        {
          find_inv_vars (data, &step, &cand->inv_vars);
 
@@ -3094,6 +3181,7 @@ add_candidate_1 (struct ivopts_data *data,
     }
 
   cand->important |= important;
+  cand->doloop_p |= doloop;
 
   /* Relate candidate to the group for which it is added.  */
   if (use)
@@ -3112,7 +3200,7 @@ add_candidate_1 (struct ivopts_data *data,
    is already nonempty.  */
 
 static bool
-allow_ip_end_pos_p (struct loop *loop)
+allow_ip_end_pos_p (class loop *loop)
 {
   if (!ip_normal_pos (loop))
     return true;
@@ -3140,19 +3228,19 @@ add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
      statement.  */
   if (use_bb->loop_father != data->current_loop
       || !dominated_by_p (CDI_DOMINATORS, data->current_loop->latch, use_bb)
-      || stmt_could_throw_p (use->stmt)
+      || stmt_can_throw_internal (cfun, use->stmt)
       || !cst_and_fits_in_hwi (step))
     return;
 
   cstepi = int_cst_value (step);
 
-  mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
+  mem_mode = TYPE_MODE (use->mem_type);
   if (((USE_LOAD_PRE_INCREMENT (mem_mode)
        || USE_STORE_PRE_INCREMENT (mem_mode))
-       && GET_MODE_SIZE (mem_mode) == cstepi)
+       && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
       || ((USE_LOAD_PRE_DECREMENT (mem_mode)
           || USE_STORE_PRE_DECREMENT (mem_mode))
-         && GET_MODE_SIZE (mem_mode) == -cstepi))
+         && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
     {
       enum tree_code code = MINUS_EXPR;
       tree new_base;
@@ -3171,10 +3259,10 @@ add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
     }
   if (((USE_LOAD_POST_INCREMENT (mem_mode)
        || USE_STORE_POST_INCREMENT (mem_mode))
-       && GET_MODE_SIZE (mem_mode) == cstepi)
+       && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
       || ((USE_LOAD_POST_DECREMENT (mem_mode)
           || USE_STORE_POST_DECREMENT (mem_mode))
-         && GET_MODE_SIZE (mem_mode) == -cstepi))
+         && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
     {
       add_candidate_1 (data, base, step, important, IP_AFTER_USE, use,
                       use->stmt);
@@ -3187,14 +3275,16 @@ add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
    the end of loop.  */
 
 static void
-add_candidate (struct ivopts_data *data,
-              tree base, tree step, bool important, struct iv_use *use,
-              struct iv *orig_iv = NULL)
+add_candidate (struct ivopts_data *data, tree base, tree step, bool important,
+              struct iv_use *use, struct iv *orig_iv = NULL,
+              bool doloop = false)
 {
   if (ip_normal_pos (data->current_loop))
-    add_candidate_1 (data, base, step, important,
-                    IP_NORMAL, use, NULL, orig_iv);
-  if (ip_end_pos (data->current_loop)
+    add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL, orig_iv,
+                    doloop);
+  /* Exclude doloop candidate here since it requires decrement then comparison
+     and jump, the IP_END position doesn't match.  */
+  if (!doloop && ip_end_pos (data->current_loop)
       && allow_ip_end_pos_p (data->current_loop))
     add_candidate_1 (data, base, step, important, IP_END, use, NULL, orig_iv);
 }
@@ -3303,8 +3393,8 @@ static void
 record_common_cand (struct ivopts_data *data, tree base,
                    tree step, struct iv_use *use)
 {
-  struct iv_common_cand ent;
-  struct iv_common_cand **slot;
+  class iv_common_cand ent;
+  class iv_common_cand **slot;
 
   ent.base = base;
   ent.step = step;
@@ -3333,10 +3423,10 @@ static int
 common_cand_cmp (const void *p1, const void *p2)
 {
   unsigned n1, n2;
-  const struct iv_common_cand *const *const ccand1
-    = (const struct iv_common_cand *const *)p1;
-  const struct iv_common_cand *const *const ccand2
-    = (const struct iv_common_cand *const *)p2;
+  const class iv_common_cand *const *const ccand1
+    = (const class iv_common_cand *const *)p1;
+  const class iv_common_cand *const *const ccand2
+    = (const class iv_common_cand *const *)p2;
 
   n1 = (*ccand1)->uses.length ();
   n2 = (*ccand2)->uses.length ();
@@ -3354,7 +3444,7 @@ add_iv_candidate_derived_from_uses (struct ivopts_data *data)
   data->iv_common_cands.qsort (common_cand_cmp);
   for (i = 0; i < data->iv_common_cands.length (); i++)
     {
-      struct iv_common_cand *ptr = data->iv_common_cands[i];
+      class iv_common_cand *ptr = data->iv_common_cands[i];
 
       /* Only add IV candidate if it's derived from multiple uses.  */
       if (ptr->uses.length () <= 1)
@@ -3392,10 +3482,23 @@ add_iv_candidate_derived_from_uses (struct ivopts_data *data)
 static void
 add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
 {
-  unsigned HOST_WIDE_INT offset;
+  poly_uint64 offset;
   tree base;
-  tree basetype;
   struct iv *iv = use->iv;
+  tree basetype = TREE_TYPE (iv->base);
+
+  /* Don't add candidate for iv_use with non integer, pointer or non-mode
+     precision types, instead, add candidate for the corresponding scev in
+     unsigned type with the same precision.  See PR93674 for more info.  */
+  if ((TREE_CODE (basetype) != INTEGER_TYPE && !POINTER_TYPE_P (basetype))
+      || !type_has_mode_precision_p (basetype))
+    {
+      basetype = lang_hooks.types.type_for_mode (TYPE_MODE (basetype),
+                                                TYPE_UNSIGNED (basetype));
+      add_candidate (data, fold_convert (basetype, iv->base),
+                    fold_convert (basetype, iv->step), false, NULL);
+      return;
+    }
 
   add_candidate (data, iv->base, iv->step, false, use);
 
@@ -3408,10 +3511,30 @@ add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
     basetype = sizetype;
   record_common_cand (data, build_int_cst (basetype, 0), iv->step, use);
 
+  /* Compare the cost of an address with an unscaled index with the cost of
+    an address with a scaled index and add candidate if useful.  */
+  poly_int64 step;
+  if (use != NULL
+      && poly_int_tree_p (iv->step, &step)
+      && address_p (use->type))
+    {
+      poly_int64 new_step;
+      unsigned int fact = preferred_mem_scale_factor
+       (use->iv->base,
+        TYPE_MODE (use->mem_type),
+        optimize_loop_for_speed_p (data->current_loop));
+
+      if (fact != 1
+         && multiple_p (step, fact, &new_step))
+       add_candidate (data, size_int (0),
+                      wide_int_to_tree (sizetype, new_step),
+                      true, NULL);
+    }
+
   /* Record common candidate with constant offset stripped in base.
      Like the use itself, we also add candidate directly for it.  */
   base = strip_offset (iv->base, &offset);
-  if (offset || base != iv->base)
+  if (maybe_ne (offset, 0U) || base != iv->base)
     {
       record_common_cand (data, base, iv->step, use);
       add_candidate (data, base, iv->step, false, use);
@@ -3430,14 +3553,14 @@ add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
       record_common_cand (data, base, step, use);
       /* Also record common candidate with offset stripped.  */
       base = strip_offset (base, &offset);
-      if (offset)
+      if (maybe_ne (offset, 0U))
        record_common_cand (data, base, step, use);
     }
 
   /* At last, add auto-incremental candidates.  Make such variables
      important since other iv uses with same base object may be based
      on it.  */
-  if (use != NULL && use->type == USE_ADDRESS)
+  if (use != NULL && address_p (use->type))
     add_autoinc_candidates (data, iv->base, iv->step, true, use);
 }
 
@@ -3510,7 +3633,7 @@ alloc_use_cost_map (struct ivopts_data *data)
        }
 
       group->n_map_members = size;
-      group->cost_map = XCNEWVEC (struct cost_pair, size);
+      group->cost_map = XCNEWVEC (class cost_pair, size);
     }
 }
 
@@ -3566,12 +3689,12 @@ found:
 
 /* Gets cost of (GROUP, CAND) pair.  */
 
-static struct cost_pair *
+static class cost_pair *
 get_group_iv_cost (struct ivopts_data *data, struct iv_group *group,
                   struct iv_cand *cand)
 {
   unsigned i, s;
-  struct cost_pair *ret;
+  class cost_pair *ret;
 
   if (!cand)
     return NULL;
@@ -3690,6 +3813,63 @@ prepare_decl_rtl (tree *expr_p, int *ws, void *data)
   return NULL_TREE;
 }
 
+/* Predict whether the given loop will be transformed in the RTL
+   doloop_optimize pass.  Attempt to duplicate some doloop_optimize checks.
+   This is only for target independent checks, see targetm.predict_doloop_p
+   for the target dependent ones.
+
+   Note that according to some initial investigation, some checks like costly
+   niter check and invalid stmt scanning don't have much gains among general
+   cases, so keep this as simple as possible first.
+
+   Some RTL specific checks seems unable to be checked in gimple, if any new
+   checks or easy checks _are_ missing here, please add them.  */
+
+static bool
+generic_predict_doloop_p (struct ivopts_data *data)
+{
+  class loop *loop = data->current_loop;
+
+  /* Call target hook for target dependent checks.  */
+  if (!targetm.predict_doloop_p (loop))
+    {
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       fprintf (dump_file, "Predict doloop failure due to"
+                           " target specific checks.\n");
+      return false;
+    }
+
+  /* Similar to doloop_optimize, check iteration description to know it's
+     suitable or not.  Keep it as simple as possible, feel free to extend it
+     if you find any multiple exits cases matter.  */
+  edge exit = single_dom_exit (loop);
+  class tree_niter_desc *niter_desc;
+  if (!exit || !(niter_desc = niter_for_exit (data, exit)))
+    {
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       fprintf (dump_file, "Predict doloop failure due to"
+                           " unexpected niters.\n");
+      return false;
+    }
+
+  /* Similar to doloop_optimize, check whether iteration count too small
+     and not profitable.  */
+  HOST_WIDE_INT est_niter = get_estimated_loop_iterations_int (loop);
+  if (est_niter == -1)
+    est_niter = get_likely_max_loop_iterations_int (loop);
+  if (est_niter >= 0 && est_niter < 3)
+    {
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       fprintf (dump_file,
+                "Predict doloop failure due to"
+                " too few iterations (%u).\n",
+                (unsigned int) est_niter);
+      return false;
+    }
+
+  return true;
+}
+
 /* Determines cost of the computation of EXPR.  */
 
 static unsigned
@@ -3727,7 +3907,7 @@ computation_cost (tree expr, bool speed)
 /* Returns variable containing the value of candidate CAND at statement AT.  */
 
 static tree
-var_at_stmt (struct loop *loop, struct iv_cand *cand, gimple *stmt)
+var_at_stmt (class loop *loop, struct iv_cand *cand, gimple *stmt)
 {
   if (stmt_after_increment (loop, cand, stmt))
     return cand->var_after;
@@ -3778,9 +3958,9 @@ determine_common_wider_type (tree *a, tree *b)
    non-null.  Returns false if USE cannot be expressed using CAND.  */
 
 static bool
-get_computation_aff_1 (struct loop *loop, gimple *at, struct iv_use *use,
-                      struct iv_cand *cand, struct aff_tree *aff_inv,
-                      struct aff_tree *aff_var, widest_int *prat = NULL)
+get_computation_aff_1 (class loop *loop, gimple *at, struct iv_use *use,
+                      struct iv_cand *cand, class aff_tree *aff_inv,
+                      class aff_tree *aff_var, widest_int *prat = NULL)
 {
   tree ubase = use->iv->base, ustep = use->iv->step;
   tree cbase = cand->iv->base, cstep = cand->iv->step;
@@ -3800,7 +3980,7 @@ get_computation_aff_1 (struct loop *loop, gimple *at, struct iv_use *use,
   if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
     {
       if (cand->orig_iv != NULL && CONVERT_EXPR_P (cbase)
-         && (CONVERT_EXPR_P (cstep) || TREE_CODE (cstep) == INTEGER_CST))
+         && (CONVERT_EXPR_P (cstep) || poly_int_tree_p (cstep)))
        {
          tree inner_base, inner_step, inner_type;
          inner_base = TREE_OPERAND (cbase, 0);
@@ -3884,8 +4064,8 @@ get_computation_aff_1 (struct loop *loop, gimple *at, struct iv_use *use,
    form into AFF.  Returns false if USE cannot be expressed using CAND.  */
 
 static bool
-get_computation_aff (struct loop *loop, gimple *at, struct iv_use *use,
-                    struct iv_cand *cand, struct aff_tree *aff)
+get_computation_aff (class loop *loop, gimple *at, struct iv_use *use,
+                    struct iv_cand *cand, class aff_tree *aff)
 {
   aff_tree aff_var;
 
@@ -3904,7 +4084,7 @@ get_use_type (struct iv_use *use)
   tree base_type = TREE_TYPE (use->iv->base);
   tree type;
 
-  if (use->type == USE_ADDRESS)
+  if (use->type == USE_REF_ADDRESS)
     {
       /* The base_type may be a void pointer.  Create a pointer type based on
         the mem_ref instead.  */
@@ -3922,7 +4102,7 @@ get_use_type (struct iv_use *use)
    CAND at statement AT in LOOP.  The computation is unshared.  */
 
 static tree
-get_computation_at (struct loop *loop, gimple *at,
+get_computation_at (class loop *loop, gimple *at,
                    struct iv_use *use, struct iv_cand *cand)
 {
   aff_tree aff;
@@ -3934,21 +4114,107 @@ get_computation_at (struct loop *loop, gimple *at,
   return fold_convert (type, aff_combination_to_tree (&aff));
 }
 
+/* Like get_computation_at, but try harder, even if the computation
+   is more expensive.  Intended for debug stmts.  */
+
+static tree
+get_debug_computation_at (class loop *loop, gimple *at,
+                         struct iv_use *use, struct iv_cand *cand)
+{
+  if (tree ret = get_computation_at (loop, at, use, cand))
+    return ret;
+
+  tree ubase = use->iv->base, ustep = use->iv->step;
+  tree cbase = cand->iv->base, cstep = cand->iv->step;
+  tree var;
+  tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
+  widest_int rat;
+
+  /* We must have a precision to express the values of use.  */
+  if (TYPE_PRECISION (utype) >= TYPE_PRECISION (ctype))
+    return NULL_TREE;
+
+  /* Try to handle the case that get_computation_at doesn't,
+     try to express
+     use = ubase + (var - cbase) / ratio.  */
+  if (!constant_multiple_of (cstep, fold_convert (TREE_TYPE (cstep), ustep),
+                            &rat))
+    return NULL_TREE;
+
+  bool neg_p = false;
+  if (wi::neg_p (rat))
+    {
+      if (TYPE_UNSIGNED (ctype))
+       return NULL_TREE;
+      neg_p = true;
+      rat = wi::neg (rat);
+    }
+
+  /* If both IVs can wrap around and CAND doesn't have a power of two step,
+     it is unsafe.  Consider uint16_t CAND with step 9, when wrapping around,
+     the values will be ... 0xfff0, 0xfff9, 2, 11 ... and when use is say
+     uint8_t with step 3, those values divided by 3 cast to uint8_t will be
+     ... 0x50, 0x53, 0, 3 ... rather than expected 0x50, 0x53, 0x56, 0x59.  */
+  if (!use->iv->no_overflow
+      && !cand->iv->no_overflow
+      && !integer_pow2p (cstep))
+    return NULL_TREE;
+
+  int bits = wi::exact_log2 (rat);
+  if (bits == -1)
+    bits = wi::floor_log2 (rat) + 1;
+  if (!cand->iv->no_overflow
+      && TYPE_PRECISION (utype) + bits > TYPE_PRECISION (ctype))
+    return NULL_TREE;
+
+  var = var_at_stmt (loop, cand, at);
+
+  if (POINTER_TYPE_P (ctype))
+    {
+      ctype = unsigned_type_for (ctype);
+      cbase = fold_convert (ctype, cbase);
+      cstep = fold_convert (ctype, cstep);
+      var = fold_convert (ctype, var);
+    }
+
+  if (stmt_after_increment (loop, cand, at))
+    var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var,
+                      unshare_expr (cstep));
+
+  var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var, cbase);
+  var = fold_build2 (EXACT_DIV_EXPR, TREE_TYPE (var), var,
+                    wide_int_to_tree (TREE_TYPE (var), rat));
+  if (POINTER_TYPE_P (utype))
+    {
+      var = fold_convert (sizetype, var);
+      if (neg_p)
+       var = fold_build1 (NEGATE_EXPR, sizetype, var);
+      var = fold_build2 (POINTER_PLUS_EXPR, utype, ubase, var);
+    }
+  else
+    {
+      var = fold_convert (utype, var);
+      var = fold_build2 (neg_p ? MINUS_EXPR : PLUS_EXPR, utype,
+                        ubase, var);
+    }
+  return var;
+}
+
 /* Adjust the cost COST for being in loop setup rather than loop body.
    If we're optimizing for space, the loop setup overhead is constant;
    if we're optimizing for speed, amortize it over the per-iteration cost.
    If ROUND_UP_P is true, the result is round up rather than to zero when
    optimizing for speed.  */
-static unsigned
-adjust_setup_cost (struct ivopts_data *data, unsigned cost,
+static int64_t
+adjust_setup_cost (struct ivopts_data *data, int64_t cost,
                   bool round_up_p = false)
 {
   if (cost == INFTY)
     return cost;
   else if (optimize_loop_for_speed_p (data->current_loop))
     {
-      HOST_WIDE_INT niters = avg_loop_niter (data->current_loop);
-      return ((HOST_WIDE_INT) cost + (round_up_p ? niters - 1 : 0)) / niters;
+      int64_t niters = (int64_t) avg_loop_niter (data->current_loop);
+      return (cost + (round_up_p ? niters - 1 : 0)) / niters;
     }
   else
     return cost;
@@ -3960,7 +4226,7 @@ adjust_setup_cost (struct ivopts_data *data, unsigned cost,
    the cost in COST.  */
 
 static bool
-get_shiftadd_cost (tree expr, machine_mode mode, comp_cost cost0,
+get_shiftadd_cost (tree expr, scalar_int_mode mode, comp_cost cost0,
                   comp_cost cost1, tree mult, bool speed, comp_cost *cost)
 {
   comp_cost res;
@@ -4058,7 +4324,7 @@ force_expr_to_var_cost (tree expr, bool speed)
 
   if (is_gimple_min_invariant (expr))
     {
-      if (TREE_CODE (expr) == INTEGER_CST)
+      if (poly_int_tree_p (expr))
        return comp_cost (integer_cost [speed], 0);
 
       if (TREE_CODE (expr) == ADDR_EXPR)
@@ -4098,6 +4364,36 @@ force_expr_to_var_cost (tree expr, bool speed)
       STRIP_NOPS (op0);
       op1 = NULL_TREE;
       break;
+    /* See add_iv_candidate_for_doloop, for doloop may_be_zero case, we
+       introduce COND_EXPR for IV base, need to support better cost estimation
+       for this COND_EXPR and tcc_comparison.  */
+    case COND_EXPR:
+      op0 = TREE_OPERAND (expr, 1);
+      STRIP_NOPS (op0);
+      op1 = TREE_OPERAND (expr, 2);
+      STRIP_NOPS (op1);
+      break;
+    case LT_EXPR:
+    case LE_EXPR:
+    case GT_EXPR:
+    case GE_EXPR:
+    case EQ_EXPR:
+    case NE_EXPR:
+    case UNORDERED_EXPR:
+    case ORDERED_EXPR:
+    case UNLT_EXPR:
+    case UNLE_EXPR:
+    case UNGT_EXPR:
+    case UNGE_EXPR:
+    case UNEQ_EXPR:
+    case LTGT_EXPR:
+    case MAX_EXPR:
+    case MIN_EXPR:
+      op0 = TREE_OPERAND (expr, 0);
+      STRIP_NOPS (op0);
+      op1 = TREE_OPERAND (expr, 1);
+      STRIP_NOPS (op1);
+      break;
 
     default:
       /* Just an arbitrary value, FIXME.  */
@@ -4179,6 +4475,35 @@ force_expr_to_var_cost (tree expr, bool speed)
     case RSHIFT_EXPR:
       cost = comp_cost (add_cost (speed, mode), 0);
       break;
+    case COND_EXPR:
+      op0 = TREE_OPERAND (expr, 0);
+      STRIP_NOPS (op0);
+      if (op0 == NULL_TREE || TREE_CODE (op0) == SSA_NAME
+         || CONSTANT_CLASS_P (op0))
+       cost = no_cost;
+      else
+       cost = force_expr_to_var_cost (op0, speed);
+      break;
+    case LT_EXPR:
+    case LE_EXPR:
+    case GT_EXPR:
+    case GE_EXPR:
+    case EQ_EXPR:
+    case NE_EXPR:
+    case UNORDERED_EXPR:
+    case ORDERED_EXPR:
+    case UNLT_EXPR:
+    case UNLE_EXPR:
+    case UNGT_EXPR:
+    case UNGE_EXPR:
+    case UNEQ_EXPR:
+    case LTGT_EXPR:
+    case MAX_EXPR:
+    case MIN_EXPR:
+      /* Simply use add cost for now, FIXME if there is some more accurate cost
+        evaluation way.  */
+      cost = comp_cost (add_cost (speed, mode), 0);
+      break;
 
     default:
       gcc_unreachable ();
@@ -4219,11 +4544,11 @@ enum ainc_type
 
 struct ainc_cost_data
 {
-  unsigned costs[AINC_NONE];
+  int64_t costs[AINC_NONE];
 };
 
 static comp_cost
-get_address_cost_ainc (HOST_WIDE_INT ainc_step, HOST_WIDE_INT ainc_offset,
+get_address_cost_ainc (poly_int64 ainc_step, poly_int64 ainc_offset,
                       machine_mode addr_mode, machine_mode mem_mode,
                       addr_space_t as, bool speed)
 {
@@ -4244,7 +4569,7 @@ get_address_cost_ainc (HOST_WIDE_INT ainc_step, HOST_WIDE_INT ainc_offset,
       unsigned nsize = ((unsigned) as + 1) *MAX_MACHINE_MODE;
 
       gcc_assert (nsize > idx);
-      ainc_cost_data_list.safe_grow_cleared (nsize);
+      ainc_cost_data_list.safe_grow_cleared (nsize, true);
     }
 
   ainc_cost_data *data = ainc_cost_data_list[idx];
@@ -4296,14 +4621,14 @@ get_address_cost_ainc (HOST_WIDE_INT ainc_step, HOST_WIDE_INT ainc_offset,
       ainc_cost_data_list[idx] = data;
     }
 
-  HOST_WIDE_INT msize = GET_MODE_SIZE (mem_mode);
-  if (ainc_offset == 0 && msize == ainc_step)
+  poly_int64 msize = GET_MODE_SIZE (mem_mode);
+  if (known_eq (ainc_offset, 0) && known_eq (msize, ainc_step))
     return comp_cost (data->costs[AINC_POST_INC], 0);
-  if (ainc_offset == 0 && msize == -ainc_step)
+  if (known_eq (ainc_offset, 0) && known_eq (msize, -ainc_step))
     return comp_cost (data->costs[AINC_POST_DEC], 0);
-  if (ainc_offset == msize && msize == ainc_step)
+  if (known_eq (ainc_offset, msize) && known_eq (msize, ainc_step))
     return comp_cost (data->costs[AINC_PRE_INC], 0);
-  if (ainc_offset == -msize && msize == -ainc_step)
+  if (known_eq (ainc_offset, -msize) && known_eq (msize, -ainc_step))
     return comp_cost (data->costs[AINC_PRE_DEC], 0);
 
   return infinite_cost;
@@ -4332,21 +4657,28 @@ get_address_cost (struct ivopts_data *data, struct iv_use *use,
   struct mem_address parts = {NULL_TREE, integer_one_node,
                              NULL_TREE, NULL_TREE, NULL_TREE};
   machine_mode addr_mode = TYPE_MODE (type);
-  machine_mode mem_mode = TYPE_MODE (TREE_TYPE (*use->op_p));
+  machine_mode mem_mode = TYPE_MODE (use->mem_type);
   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
+  /* Only true if ratio != 1.  */
+  bool ok_with_ratio_p = false;
+  bool ok_without_ratio_p = false;
 
   if (!aff_combination_const_p (aff_inv))
     {
       parts.index = integer_one_node;
       /* Addressing mode "base + index".  */
-      if (valid_mem_ref_p (mem_mode, as, &parts))
+      ok_without_ratio_p = valid_mem_ref_p (mem_mode, as, &parts);
+      if (ratio != 1)
        {
          parts.step = wide_int_to_tree (type, ratio);
          /* Addressing mode "base + index << scale".  */
-         if (ratio != 1 && !valid_mem_ref_p (mem_mode, as, &parts))
+         ok_with_ratio_p = valid_mem_ref_p (mem_mode, as, &parts);
+         if (!ok_with_ratio_p)
            parts.step = NULL_TREE;
-
-         if (aff_inv->offset != 0)
+       }
+      if (ok_with_ratio_p || ok_without_ratio_p)
+       {
+         if (maybe_ne (aff_inv->offset, 0))
            {
              parts.offset = wide_int_to_tree (sizetype, aff_inv->offset);
              /* Addressing mode "base + index [<< scale] + offset".  */
@@ -4379,10 +4711,12 @@ get_address_cost (struct ivopts_data *data, struct iv_use *use,
     }
   else
     {
-      if (can_autoinc && ratio == 1 && cst_and_fits_in_hwi (cand->iv->step))
+      poly_int64 ainc_step;
+      if (can_autoinc
+         && ratio == 1
+         && ptrdiff_tree_p (cand->iv->step, &ainc_step))
        {
-         HOST_WIDE_INT ainc_step = int_cst_value (cand->iv->step);
-         HOST_WIDE_INT ainc_offset = (aff_inv->offset).to_shwi ();
+         poly_int64 ainc_offset = (aff_inv->offset).force_shwi ();
 
          if (stmt_after_increment (data->current_loop, cand, use->stmt))
            ainc_offset += ainc_step;
@@ -4443,7 +4777,9 @@ get_address_cost (struct ivopts_data *data, struct iv_use *use,
 
   if (parts.symbol != NULL_TREE)
     cost.complexity += 1;
-  if (parts.step != NULL_TREE && !integer_onep (parts.step))
+  /* Don't increase the complexity of adding a scaled index if it's
+     the only kind of index that the target allows.  */
+  if (parts.step != NULL_TREE && ok_without_ratio_p)
     cost.complexity += 1;
   if (parts.base != NULL_TREE && parts.index != NULL_TREE)
     cost.complexity += 1;
@@ -4460,22 +4796,25 @@ get_address_cost (struct ivopts_data *data, struct iv_use *use,
 static comp_cost
 get_scaled_computation_cost_at (ivopts_data *data, gimple *at, comp_cost cost)
 {
-   int loop_freq = data->current_loop->header->frequency;
-   int bb_freq = gimple_bb (at)->frequency;
-   if (loop_freq != 0)
-     {
-       gcc_assert (cost.scratch <= cost.cost);
-       int scaled_cost
-        = cost.scratch + (cost.cost - cost.scratch) * bb_freq / loop_freq;
+  if (data->speed
+      && data->current_loop->header->count.to_frequency (cfun) > 0)
+    {
+      basic_block bb = gimple_bb (at);
+      gcc_assert (cost.scratch <= cost.cost);
+      int scale_factor = (int)(intptr_t) bb->aux;
+      if (scale_factor == 1)
+       return cost;
 
-       if (dump_file && (dump_flags & TDF_DETAILS))
-        fprintf (dump_file, "Scaling cost based on bb prob "
-                 "by %2.2f: %d (scratch: %d) -> %d (%d/%d)\n",
-                 1.0f * bb_freq / loop_freq, cost.cost,
-                 cost.scratch, scaled_cost, bb_freq, loop_freq);
+      int64_t scaled_cost
+       = cost.scratch + (cost.cost - cost.scratch) * scale_factor;
 
-       cost.cost = scaled_cost;
-     }
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       fprintf (dump_file, "Scaling cost based on bb prob by %2.2f: "
+                "%" PRId64 " (scratch: %" PRId64 ") -> %" PRId64 "\n",
+                1.0f * scale_factor, cost.cost, cost.scratch, scaled_cost);
+
+      cost.cost = scaled_cost;
+    }
 
   return cost;
 }
@@ -4541,7 +4880,10 @@ get_computation_cost (struct ivopts_data *data, struct iv_use *use,
     {
       cost = get_address_cost (data, use, cand, &aff_inv, &aff_var, ratio,
                               inv_vars, inv_expr, can_autoinc, speed);
-      return get_scaled_computation_cost_at (data, at, cost);
+      cost = get_scaled_computation_cost_at (data, at, cost);
+      /* For doloop IV cand, add on the extra cost.  */
+      cost += cand->doloop_p ? targetm.doloop_cost_for_address : 0;
+      return cost;
     }
 
   bool simple_inv = (aff_combination_const_p (&aff_inv)
@@ -4591,7 +4933,13 @@ get_computation_cost (struct ivopts_data *data, struct iv_use *use,
   if (comp_inv && !integer_zerop (comp_inv))
     cost += add_cost (speed, TYPE_MODE (utype));
 
-  return get_scaled_computation_cost_at (data, at, cost);
+  cost = get_scaled_computation_cost_at (data, at, cost);
+
+  /* For doloop IV cand, add on the extra cost.  */
+  if (cand->doloop_p && use->type == USE_NONLINEAR_EXPR)
+    cost += targetm.doloop_cost_for_generic;
+
+  return cost;
 }
 
 /* Determines cost of computing the use in GROUP with CAND in a generic
@@ -4690,7 +5038,7 @@ determine_group_iv_cost_address (struct ivopts_data *data,
    stores it to VAL.  */
 
 static void
-cand_value_at (struct loop *loop, struct iv_cand *cand, gimple *at, tree niter,
+cand_value_at (class loop *loop, struct iv_cand *cand, gimple *at, tree niter,
               aff_tree *val)
 {
   aff_tree step, delta, nit;
@@ -4749,7 +5097,7 @@ iv_period (struct iv *iv)
 static enum tree_code
 iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
 {
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   basic_block ex_bb;
   edge exit;
 
@@ -4873,10 +5221,10 @@ difference_cannot_overflow_p (struct ivopts_data *data, tree base, tree offset)
 static bool
 iv_elimination_compare_lt (struct ivopts_data *data,
                           struct iv_cand *cand, enum tree_code *comp_p,
-                          struct tree_niter_desc *niter)
+                          class tree_niter_desc *niter)
 {
   tree cand_type, a, b, mbz, nit_type = TREE_TYPE (niter->niter), offset;
-  struct aff_tree nit, tmpa, tmpb;
+  class aff_tree nit, tmpa, tmpb;
   enum tree_code comp;
   HOST_WIDE_INT step;
 
@@ -4940,7 +5288,7 @@ iv_elimination_compare_lt (struct ivopts_data *data,
   aff_combination_scale (&tmpa, -1);
   aff_combination_add (&tmpb, &tmpa);
   aff_combination_add (&tmpb, &nit);
-  if (tmpb.n != 0 || tmpb.offset != 1)
+  if (tmpb.n != 0 || maybe_ne (tmpb.offset, 1))
     return false;
 
   /* Finally, check that CAND->IV->BASE - CAND->IV->STEP * A does not
@@ -4975,9 +5323,9 @@ may_eliminate_iv (struct ivopts_data *data,
   basic_block ex_bb;
   edge exit;
   tree period;
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   aff_tree bnd;
-  struct tree_niter_desc *desc = NULL;
+  class tree_niter_desc *desc = NULL;
 
   if (TREE_CODE (cand->iv->step) != INTEGER_CST)
     return false;
@@ -5049,6 +5397,15 @@ may_eliminate_iv (struct ivopts_data *data,
        }
     }
 
+  /* For doloop IV cand, the bound would be zero.  It's safe whether
+     may_be_zero set or not.  */
+  if (cand->doloop_p)
+    {
+      *bound = build_int_cst (TREE_TYPE (cand->iv->base), 0);
+      *comp = iv_elimination_compare (data, use);
+      return true;
+    }
+
   cand_value_at (loop, cand, use->stmt, desc->niter, &bnd);
 
   *bound = fold_convert (TREE_TYPE (cand->iv->base),
@@ -5171,6 +5528,9 @@ determine_group_iv_cost_cond (struct ivopts_data *data,
       inv_vars = inv_vars_elim;
       inv_vars_elim = NULL;
       inv_expr = inv_expr_elim;
+      /* For doloop candidate/use pair, adjust to zero cost.  */
+      if (group->doloop_p && cand->doloop_p && elim_cost.cost > no_cost.cost)
+       cost = no_cost;
     }
   else
     {
@@ -5210,7 +5570,8 @@ determine_group_iv_cost (struct ivopts_data *data,
     case USE_NONLINEAR_EXPR:
       return determine_group_iv_cost_generic (data, group, cand);
 
-    case USE_ADDRESS:
+    case USE_REF_ADDRESS:
+    case USE_PTR_ADDRESS:
       return determine_group_iv_cost_address (data, group, cand);
 
     case USE_COMPARE:
@@ -5228,7 +5589,7 @@ static bool
 autoinc_possible_for_pair (struct ivopts_data *data, struct iv_use *use,
                           struct iv_cand *cand)
 {
-  if (use->type != USE_ADDRESS)
+  if (!address_p (use->type))
     return false;
 
   bool can_autoinc = false;
@@ -5296,6 +5657,107 @@ relate_compare_use_with_all_cands (struct ivopts_data *data)
     }
 }
 
+/* If PREFERRED_MODE is suitable and profitable, use the preferred
+   PREFERRED_MODE to compute doloop iv base from niter: base = niter + 1.  */
+
+static tree
+compute_doloop_base_on_mode (machine_mode preferred_mode, tree niter,
+                            const widest_int &iterations_max)
+{
+  tree ntype = TREE_TYPE (niter);
+  tree pref_type = lang_hooks.types.type_for_mode (preferred_mode, 1);
+  if (!pref_type)
+    return fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
+                       build_int_cst (ntype, 1));
+
+  gcc_assert (TREE_CODE (pref_type) == INTEGER_TYPE);
+
+  int prec = TYPE_PRECISION (ntype);
+  int pref_prec = TYPE_PRECISION (pref_type);
+
+  tree base;
+
+  /* Check if the PREFERRED_MODED is able to present niter.  */
+  if (pref_prec > prec
+      || wi::ltu_p (iterations_max,
+                   widest_int::from (wi::max_value (pref_prec, UNSIGNED),
+                                     UNSIGNED)))
+    {
+      /* No wrap, it is safe to use preferred type after niter + 1.  */
+      if (wi::ltu_p (iterations_max,
+                    widest_int::from (wi::max_value (prec, UNSIGNED),
+                                      UNSIGNED)))
+       {
+         /* This could help to optimize "-1 +1" pair when niter looks
+            like "n-1": n is in original mode.  "base = (n - 1) + 1"
+            in PREFERRED_MODED: it could be base = (PREFERRED_TYPE)n.  */
+         base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
+                             build_int_cst (ntype, 1));
+         base = fold_convert (pref_type, base);
+       }
+
+      /* To avoid wrap, convert niter to preferred type before plus 1.  */
+      else
+       {
+         niter = fold_convert (pref_type, niter);
+         base = fold_build2 (PLUS_EXPR, pref_type, unshare_expr (niter),
+                             build_int_cst (pref_type, 1));
+       }
+    }
+  else
+    base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
+                       build_int_cst (ntype, 1));
+  return base;
+}
+
+/* Add one doloop dedicated IV candidate:
+     - Base is (may_be_zero ? 1 : (niter + 1)).
+     - Step is -1.  */
+
+static void
+add_iv_candidate_for_doloop (struct ivopts_data *data)
+{
+  tree_niter_desc *niter_desc = niter_for_single_dom_exit (data);
+  gcc_assert (niter_desc && niter_desc->assumptions);
+
+  tree niter = niter_desc->niter;
+  tree ntype = TREE_TYPE (niter);
+  gcc_assert (TREE_CODE (ntype) == INTEGER_TYPE);
+
+  tree may_be_zero = niter_desc->may_be_zero;
+  if (may_be_zero && integer_zerop (may_be_zero))
+    may_be_zero = NULL_TREE;
+  if (may_be_zero)
+    {
+      if (COMPARISON_CLASS_P (may_be_zero))
+       {
+         niter = fold_build3 (COND_EXPR, ntype, may_be_zero,
+                              build_int_cst (ntype, 0),
+                              rewrite_to_non_trapping_overflow (niter));
+       }
+      /* Don't try to obtain the iteration count expression when may_be_zero is
+        integer_nonzerop (actually iteration count is one) or else.  */
+      else
+       return;
+    }
+
+  machine_mode mode = TYPE_MODE (ntype);
+  machine_mode pref_mode = targetm.preferred_doloop_mode (mode);
+
+  tree base;
+  if (mode != pref_mode)
+    {
+      base = compute_doloop_base_on_mode (pref_mode, niter, niter_desc->max);
+      ntype = TREE_TYPE (base);
+    }
+  else
+    base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
+                       build_int_cst (ntype, 1));
+
+
+  add_candidate (data, base, build_int_cst (ntype, -1), true, NULL, NULL, true);
+}
+
 /* Finds the candidates for the induction variables.  */
 
 static void
@@ -5304,6 +5766,10 @@ find_iv_candidates (struct ivopts_data *data)
   /* Add commonly used ivs.  */
   add_standard_iv_candidates (data);
 
+  /* Add doloop dedicated ivs.  */
+  if (data->doloop_use_p)
+    add_iv_candidate_for_doloop (data);
+
   /* Add old induction variables.  */
   add_iv_candidate_for_bivs (data);
 
@@ -5438,7 +5904,7 @@ determine_group_iv_costs (struct ivopts_data *data)
                  || group->cost_map[j].cost.infinite_cost_p ())
                continue;
 
-             fprintf (dump_file, "  %d\t%d\t%d\t",
+             fprintf (dump_file, "  %d\t%" PRId64 "\t%d\t",
                       group->cost_map[j].cand->id,
                       group->cost_map[j].cost.cost,
                       group->cost_map[j].cost.complexity);
@@ -5468,7 +5934,7 @@ static void
 determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
 {
   comp_cost cost_base;
-  unsigned cost, cost_step;
+  int64_t cost, cost_step;
   tree base;
 
   gcc_assert (cand->iv != NULL);
@@ -5484,16 +5950,21 @@ determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
      or a const set.  */
   if (cost_base.cost == 0)
     cost_base.cost = COSTS_N_INSNS (1);
-  cost_step = add_cost (data->speed, TYPE_MODE (TREE_TYPE (base)));
-
+  /* Doloop decrement should be considered as zero cost.  */
+  if (cand->doloop_p)
+    cost_step = 0;
+  else
+    cost_step = add_cost (data->speed, TYPE_MODE (TREE_TYPE (base)));
   cost = cost_step + adjust_setup_cost (data, cost_base.cost);
 
   /* Prefer the original ivs unless we may gain something by replacing it.
      The reason is to make debugging simpler; so this is not relevant for
      artificial ivs created by other optimization passes.  */
-  if (cand->pos != IP_ORIGINAL
-      || !SSA_NAME_VAR (cand->var_before)
-      || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
+  if ((cand->pos != IP_ORIGINAL
+       || !SSA_NAME_VAR (cand->var_before)
+       || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
+      /* Prefer doloop as well.  */
+      && !cand->doloop_p)
     cost++;
 
   /* Prefer not to insert statements into latch unless there are some
@@ -5584,7 +6055,7 @@ determine_set_costs (struct ivopts_data *data)
   gphi *phi;
   gphi_iterator psi;
   tree op;
-  struct loop *loop = data->current_loop;
+  class loop *loop = data->current_loop;
   bitmap_iterator bi;
 
   if (dump_file && (dump_flags & TDF_DETAILS))
@@ -5641,7 +6112,7 @@ determine_set_costs (struct ivopts_data *data)
 /* Returns true if A is a cheaper cost pair than B.  */
 
 static bool
-cheaper_cost_pair (struct cost_pair *a, struct cost_pair *b)
+cheaper_cost_pair (class cost_pair *a, class cost_pair *b)
 {
   if (!a)
     return false;
@@ -5666,7 +6137,7 @@ cheaper_cost_pair (struct cost_pair *a, struct cost_pair *b)
    for more expensive, equal and cheaper respectively.  */
 
 static int
-compare_cost_pair (struct cost_pair *a, struct cost_pair *b)
+compare_cost_pair (class cost_pair *a, class cost_pair *b)
 {
   if (cheaper_cost_pair (a, b))
     return -1;
@@ -5678,8 +6149,8 @@ compare_cost_pair (struct cost_pair *a, struct cost_pair *b)
 
 /* Returns candidate by that USE is expressed in IVS.  */
 
-static struct cost_pair *
-iv_ca_cand_for_group (struct iv_ca *ivs, struct iv_group *group)
+static class cost_pair *
+iv_ca_cand_for_group (class iv_ca *ivs, struct iv_group *group)
 {
   return ivs->cand_for_group[group->id];
 }
@@ -5687,7 +6158,7 @@ iv_ca_cand_for_group (struct iv_ca *ivs, struct iv_group *group)
 /* Computes the cost field of IVS structure.  */
 
 static void
-iv_ca_recount_cost (struct ivopts_data *data, struct iv_ca *ivs)
+iv_ca_recount_cost (struct ivopts_data *data, class iv_ca *ivs)
 {
   comp_cost cost = ivs->cand_use_cost;
 
@@ -5700,7 +6171,7 @@ iv_ca_recount_cost (struct ivopts_data *data, struct iv_ca *ivs)
    and IVS.  */
 
 static void
-iv_ca_set_remove_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
+iv_ca_set_remove_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
 {
   bitmap_iterator bi;
   unsigned iid;
@@ -5720,11 +6191,11 @@ iv_ca_set_remove_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
 /* Set USE not to be expressed by any candidate in IVS.  */
 
 static void
-iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_set_no_cp (struct ivopts_data *data, class iv_ca *ivs,
                 struct iv_group *group)
 {
   unsigned gid = group->id, cid;
-  struct cost_pair *cp;
+  class cost_pair *cp;
 
   cp = ivs->cand_for_group[gid];
   if (!cp)
@@ -5738,7 +6209,8 @@ iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
   if (ivs->n_cand_uses[cid] == 0)
     {
       bitmap_clear_bit (ivs->cands, cid);
-      ivs->n_cands--;
+      if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
+       ivs->n_cands--;
       ivs->cand_cost -= cp->cand->cost;
       iv_ca_set_remove_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
       iv_ca_set_remove_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses);
@@ -5754,7 +6226,7 @@ iv_ca_set_no_cp (struct ivopts_data *data, struct iv_ca *ivs,
    IVS.  */
 
 static void
-iv_ca_set_add_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
+iv_ca_set_add_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
 {
   bitmap_iterator bi;
   unsigned iid;
@@ -5774,8 +6246,8 @@ iv_ca_set_add_invs (struct iv_ca *ivs, bitmap invs, unsigned *n_inv_uses)
 /* Set cost pair for GROUP in set IVS to CP.  */
 
 static void
-iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
-             struct iv_group *group, struct cost_pair *cp)
+iv_ca_set_cp (struct ivopts_data *data, class iv_ca *ivs,
+             struct iv_group *group, class cost_pair *cp)
 {
   unsigned gid = group->id, cid;
 
@@ -5795,7 +6267,8 @@ iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
       if (ivs->n_cand_uses[cid] == 1)
        {
          bitmap_set_bit (ivs->cands, cid);
-         ivs->n_cands++;
+         if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
+           ivs->n_cands++;
          ivs->cand_cost += cp->cand->cost;
          iv_ca_set_add_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses);
          iv_ca_set_add_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses);
@@ -5813,10 +6286,10 @@ iv_ca_set_cp (struct ivopts_data *data, struct iv_ca *ivs,
    set IVS don't give any result.  */
 
 static void
-iv_ca_add_group (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_add_group (struct ivopts_data *data, class iv_ca *ivs,
               struct iv_group *group)
 {
-  struct cost_pair *best_cp = NULL, *cp;
+  class cost_pair *best_cp = NULL, *cp;
   bitmap_iterator bi;
   unsigned i;
   struct iv_cand *cand;
@@ -5850,7 +6323,7 @@ iv_ca_add_group (struct ivopts_data *data, struct iv_ca *ivs,
 /* Get cost for assignment IVS.  */
 
 static comp_cost
-iv_ca_cost (struct iv_ca *ivs)
+iv_ca_cost (class iv_ca *ivs)
 {
   /* This was a conditional expression but it triggered a bug in
      Sun C 5.5.  */
@@ -5865,9 +6338,9 @@ iv_ca_cost (struct iv_ca *ivs)
    respectively.  */
 
 static int
-iv_ca_compare_deps (struct ivopts_data *data, struct iv_ca *ivs,
-                   struct iv_group *group, struct cost_pair *old_cp,
-                   struct cost_pair *new_cp)
+iv_ca_compare_deps (struct ivopts_data *data, class iv_ca *ivs,
+                   struct iv_group *group, class cost_pair *old_cp,
+                   class cost_pair *new_cp)
 {
   gcc_assert (old_cp && new_cp && old_cp != new_cp);
   unsigned old_n_invs = ivs->n_invs;
@@ -5882,8 +6355,8 @@ iv_ca_compare_deps (struct ivopts_data *data, struct iv_ca *ivs,
    it before NEXT.  */
 
 static struct iv_ca_delta *
-iv_ca_delta_add (struct iv_group *group, struct cost_pair *old_cp,
-                struct cost_pair *new_cp, struct iv_ca_delta *next)
+iv_ca_delta_add (struct iv_group *group, class cost_pair *old_cp,
+                class cost_pair *new_cp, struct iv_ca_delta *next)
 {
   struct iv_ca_delta *change = XNEW (struct iv_ca_delta);
 
@@ -5939,10 +6412,10 @@ iv_ca_delta_reverse (struct iv_ca_delta *delta)
    reverted instead.  */
 
 static void
-iv_ca_delta_commit (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_delta_commit (struct ivopts_data *data, class iv_ca *ivs,
                    struct iv_ca_delta *delta, bool forward)
 {
-  struct cost_pair *from, *to;
+  class cost_pair *from, *to;
   struct iv_ca_delta *act;
 
   if (!forward)
@@ -5963,7 +6436,7 @@ iv_ca_delta_commit (struct ivopts_data *data, struct iv_ca *ivs,
 /* Returns true if CAND is used in IVS.  */
 
 static bool
-iv_ca_cand_used_p (struct iv_ca *ivs, struct iv_cand *cand)
+iv_ca_cand_used_p (class iv_ca *ivs, struct iv_cand *cand)
 {
   return ivs->n_cand_uses[cand->id] > 0;
 }
@@ -5971,7 +6444,7 @@ iv_ca_cand_used_p (struct iv_ca *ivs, struct iv_cand *cand)
 /* Returns number of induction variable candidates in the set IVS.  */
 
 static unsigned
-iv_ca_n_cands (struct iv_ca *ivs)
+iv_ca_n_cands (class iv_ca *ivs)
 {
   return ivs->n_cands;
 }
@@ -5994,14 +6467,14 @@ iv_ca_delta_free (struct iv_ca_delta **delta)
 
 /* Allocates new iv candidates assignment.  */
 
-static struct iv_ca *
+static class iv_ca *
 iv_ca_new (struct ivopts_data *data)
 {
-  struct iv_ca *nw = XNEW (struct iv_ca);
+  class iv_ca *nw = XNEW (class iv_ca);
 
   nw->upto = 0;
   nw->bad_groups = 0;
-  nw->cand_for_group = XCNEWVEC (struct cost_pair *,
+  nw->cand_for_group = XCNEWVEC (class cost_pair *,
                                 data->vgroups.length ());
   nw->n_cand_uses = XCNEWVEC (unsigned, data->vcands.length ());
   nw->cands = BITMAP_ALLOC (NULL);
@@ -6019,7 +6492,7 @@ iv_ca_new (struct ivopts_data *data)
 /* Free memory occupied by the set IVS.  */
 
 static void
-iv_ca_free (struct iv_ca **ivs)
+iv_ca_free (class iv_ca **ivs)
 {
   free ((*ivs)->cand_for_group);
   free ((*ivs)->n_cand_uses);
@@ -6033,26 +6506,28 @@ iv_ca_free (struct iv_ca **ivs)
 /* Dumps IVS to FILE.  */
 
 static void
-iv_ca_dump (struct ivopts_data *data, FILE *file, struct iv_ca *ivs)
+iv_ca_dump (struct ivopts_data *data, FILE *file, class iv_ca *ivs)
 {
   unsigned i;
   comp_cost cost = iv_ca_cost (ivs);
 
-  fprintf (file, "  cost: %d (complexity %d)\n", cost.cost,
+  fprintf (file, "  cost: %" PRId64 " (complexity %d)\n", cost.cost,
           cost.complexity);
-  fprintf (file, "  cand_cost: %d\n  cand_group_cost: %d (complexity %d)\n",
-          ivs->cand_cost, ivs->cand_use_cost.cost,
-          ivs->cand_use_cost.complexity);
+  fprintf (file, "  reg_cost: %d\n",
+          ivopts_estimate_reg_pressure (data, ivs->n_invs, ivs->n_cands));
+  fprintf (file, "  cand_cost: %" PRId64 "\n  cand_group_cost: "
+          "%" PRId64 " (complexity %d)\n", ivs->cand_cost,
+          ivs->cand_use_cost.cost, ivs->cand_use_cost.complexity);
   bitmap_print (file, ivs->cands, "  candidates: ","\n");
 
   for (i = 0; i < ivs->upto; i++)
     {
       struct iv_group *group = data->vgroups[i];
-      struct cost_pair *cp = iv_ca_cand_for_group (ivs, group);
+      class cost_pair *cp = iv_ca_cand_for_group (ivs, group);
       if (cp)
-        fprintf (file, "   group:%d --> iv_cand:%d, cost=(%d,%d)\n",
-                group->id, cp->cand->id, cp->cost.cost,
-                cp->cost.complexity);
+        fprintf (file, "   group:%d --> iv_cand:%d, cost=("
+                "%" PRId64 ",%d)\n", group->id, cp->cand->id,
+                cp->cost.cost, cp->cost.complexity);
       else
        fprintf (file, "   group:%d --> ??\n", group->id);
     }
@@ -6084,14 +6559,14 @@ iv_ca_dump (struct ivopts_data *data, FILE *file, struct iv_ca *ivs)
    the function will try to find a solution with mimimal iv candidates.  */
 
 static comp_cost
-iv_ca_extend (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_extend (struct ivopts_data *data, class iv_ca *ivs,
              struct iv_cand *cand, struct iv_ca_delta **delta,
              unsigned *n_ivs, bool min_ncand)
 {
   unsigned i;
   comp_cost cost;
   struct iv_group *group;
-  struct cost_pair *old_cp, *new_cp;
+  class cost_pair *old_cp, *new_cp;
 
   *delta = NULL;
   for (i = 0; i < ivs->upto; i++)
@@ -6137,13 +6612,13 @@ iv_ca_extend (struct ivopts_data *data, struct iv_ca *ivs,
    the candidate with which we start narrowing.  */
 
 static comp_cost
-iv_ca_narrow (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_narrow (struct ivopts_data *data, class iv_ca *ivs,
              struct iv_cand *cand, struct iv_cand *start,
              struct iv_ca_delta **delta)
 {
   unsigned i, ci;
   struct iv_group *group;
-  struct cost_pair *old_cp, *new_cp, *cp;
+  class cost_pair *old_cp, *new_cp, *cp;
   bitmap_iterator bi;
   struct iv_cand *cnd;
   comp_cost cost, best_cost, acost;
@@ -6231,7 +6706,7 @@ iv_ca_narrow (struct ivopts_data *data, struct iv_ca *ivs,
    differences in DELTA.  */
 
 static comp_cost
-iv_ca_prune (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_prune (struct ivopts_data *data, class iv_ca *ivs,
             struct iv_cand *except_cand, struct iv_ca_delta **delta)
 {
   bitmap_iterator bi;
@@ -6280,13 +6755,13 @@ iv_ca_prune (struct ivopts_data *data, struct iv_ca *ivs,
    cheaper local cost for GROUP than BEST_CP.  Return pointer to
    the corresponding cost_pair, otherwise just return BEST_CP.  */
 
-static struct cost_pair*
+static class cost_pair*
 cheaper_cost_with_cand (struct ivopts_data *data, struct iv_group *group,
                        unsigned int cand_idx, struct iv_cand *old_cand,
-                       struct cost_pair *best_cp)
+                       class cost_pair *best_cp)
 {
   struct iv_cand *cand;
-  struct cost_pair *cp;
+  class cost_pair *cp;
 
   gcc_assert (old_cand != NULL && best_cp != NULL);
   if (cand_idx == old_cand->id)
@@ -6308,7 +6783,7 @@ cheaper_cost_with_cand (struct ivopts_data *data, struct iv_group *group,
    candidate replacement in list DELTA.  */
 
 static comp_cost
-iv_ca_replace (struct ivopts_data *data, struct iv_ca *ivs,
+iv_ca_replace (struct ivopts_data *data, class iv_ca *ivs,
               struct iv_ca_delta **delta)
 {
   bitmap_iterator bi, bj;
@@ -6316,7 +6791,7 @@ iv_ca_replace (struct ivopts_data *data, struct iv_ca *ivs,
   struct iv_cand *cand;
   comp_cost orig_cost, acost;
   struct iv_ca_delta *act_delta, *tmp_delta;
-  struct cost_pair *old_cp, *best_cp = NULL;
+  class cost_pair *old_cp, *best_cp = NULL;
 
   *delta = NULL;
   orig_cost = iv_ca_cost (ivs);
@@ -6383,7 +6858,7 @@ iv_ca_replace (struct ivopts_data *data, struct iv_ca *ivs,
    based on any memory object.  */
 
 static bool
-try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
+try_add_cand_for (struct ivopts_data *data, class iv_ca *ivs,
                  struct iv_group *group, bool originalp)
 {
   comp_cost best_cost, act_cost;
@@ -6391,7 +6866,7 @@ try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
   bitmap_iterator bi;
   struct iv_cand *cand;
   struct iv_ca_delta *best_delta = NULL, *act_delta;
-  struct cost_pair *cp;
+  class cost_pair *cp;
 
   iv_ca_add_group (data, ivs, group);
   best_cost = iv_ca_cost (ivs);
@@ -6495,11 +6970,11 @@ try_add_cand_for (struct ivopts_data *data, struct iv_ca *ivs,
 
 /* Finds an initial assignment of candidates to uses.  */
 
-static struct iv_ca *
+static class iv_ca *
 get_initial_solution (struct ivopts_data *data, bool originalp)
 {
   unsigned i;
-  struct iv_ca *ivs = iv_ca_new (data);
+  class iv_ca *ivs = iv_ca_new (data);
 
   for (i = 0; i < data->vgroups.length (); i++)
     if (!try_add_cand_for (data, ivs, data->vgroups[i], originalp))
@@ -6517,7 +6992,7 @@ get_initial_solution (struct ivopts_data *data, bool originalp)
 
 static bool
 try_improve_iv_set (struct ivopts_data *data,
-                   struct iv_ca *ivs, bool *try_replace_p)
+                   class iv_ca *ivs, bool *try_replace_p)
 {
   unsigned i, n_ivs;
   comp_cost acost, best_cost = iv_ca_cost (ivs);
@@ -6580,19 +7055,18 @@ try_improve_iv_set (struct ivopts_data *data,
     }
 
   iv_ca_delta_commit (data, ivs, best_delta, true);
-  gcc_assert (best_cost == iv_ca_cost (ivs));
   iv_ca_delta_free (&best_delta);
-  return true;
+  return best_cost == iv_ca_cost (ivs);
 }
 
 /* Attempts to find the optimal set of induction variables.  We do simple
    greedy heuristic -- we try to replace at most one candidate in the selected
    solution and remove the unused ivs while this improves the cost.  */
 
-static struct iv_ca *
+static class iv_ca *
 find_optimal_iv_set_1 (struct ivopts_data *data, bool originalp)
 {
-  struct iv_ca *set;
+  class iv_ca *set;
   bool try_replace_p = true;
 
   /* Get the initial solution.  */
@@ -6619,15 +7093,23 @@ find_optimal_iv_set_1 (struct ivopts_data *data, bool originalp)
        }
     }
 
+  /* If the set has infinite_cost, it can't be optimal.  */
+  if (iv_ca_cost (set).infinite_cost_p ())
+    {
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       fprintf (dump_file,
+                "Overflow to infinite cost in try_improve_iv_set.\n");
+      iv_ca_free (&set);
+    }
   return set;
 }
 
-static struct iv_ca *
+static class iv_ca *
 find_optimal_iv_set (struct ivopts_data *data)
 {
   unsigned i;
   comp_cost cost, origcost;
-  struct iv_ca *set, *origset;
+  class iv_ca *set, *origset;
 
   /* Determine the cost based on a strategy that starts with original IVs,
      and try again using a strategy that prefers candidates not based
@@ -6643,9 +7125,9 @@ find_optimal_iv_set (struct ivopts_data *data)
 
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
-      fprintf (dump_file, "Original cost %d (complexity %d)\n\n",
+      fprintf (dump_file, "Original cost %" PRId64 " (complexity %d)\n\n",
               origcost.cost, origcost.complexity);
-      fprintf (dump_file, "Final cost %d (complexity %d)\n\n",
+      fprintf (dump_file, "Final cost %" PRId64 " (complexity %d)\n\n",
               cost.cost, cost.complexity);
     }
 
@@ -6723,7 +7205,7 @@ create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
 /* Creates new induction variables described in SET.  */
 
 static void
-create_new_ivs (struct ivopts_data *data, struct iv_ca *set)
+create_new_ivs (struct ivopts_data *data, class iv_ca *set)
 {
   unsigned i;
   struct iv_cand *cand;
@@ -6837,7 +7319,7 @@ rewrite_use_nonlinear_expr (struct ivopts_data *data,
   unshare_aff_combination (&aff_var);
   /* Prefer CSE opportunity than loop invariant by adding offset at last
      so that iv_uses have different offsets can be CSEed.  */
-  widest_int offset = aff_inv.offset;
+  poly_widest_int offset = aff_inv.offset;
   aff_inv.offset = 0;
 
   gimple_seq stmt_list = NULL, seq = NULL;
@@ -6869,12 +7351,13 @@ rewrite_use_nonlinear_expr (struct ivopts_data *data,
     }
 
   comp = fold_convert (type, comp);
-  if (!valid_gimple_rhs_p (comp)
-      || (gimple_code (use->stmt) != GIMPLE_PHI
-         /* We can't allow re-allocating the stmt as it might be pointed
-            to still.  */
-         && (get_gimple_rhs_num_ops (TREE_CODE (comp))
-             >= gimple_num_ops (gsi_stmt (bsi)))))
+  comp = force_gimple_operand (comp, &seq, false, NULL);
+  gimple_seq_add_seq (&stmt_list, seq);
+  if (gimple_code (use->stmt) != GIMPLE_PHI
+      /* We can't allow re-allocating the stmt as it might be pointed
+        to still.  */
+      && (get_gimple_rhs_num_ops (TREE_CODE (comp))
+         >= gimple_num_ops (gsi_stmt (bsi))))
     {
       comp = force_gimple_operand (comp, &seq, true, NULL);
       gimple_seq_add_seq (&stmt_list, seq);
@@ -6987,6 +7470,31 @@ adjust_iv_update_pos (struct iv_cand *cand, struct iv_use *use)
   cand->incremented_at = use->stmt;
 }
 
+/* Return the alias pointer type that should be used for a MEM_REF
+   associated with USE, which has type USE_PTR_ADDRESS.  */
+
+static tree
+get_alias_ptr_type_for_ptr_address (iv_use *use)
+{
+  gcall *call = as_a <gcall *> (use->stmt);
+  switch (gimple_call_internal_fn (call))
+    {
+    case IFN_MASK_LOAD:
+    case IFN_MASK_STORE:
+    case IFN_MASK_LOAD_LANES:
+    case IFN_MASK_STORE_LANES:
+    case IFN_LEN_LOAD:
+    case IFN_LEN_STORE:
+      /* The second argument contains the correct alias type.  */
+      gcc_assert (use->op_p = gimple_call_arg_ptr (call, 0));
+      return TREE_TYPE (gimple_call_arg (call, 1));
+
+    default:
+      gcc_unreachable ();
+    }
+}
+
+
 /* Rewrites USE (address that is an iv) using candidate CAND.  */
 
 static void
@@ -7015,16 +7523,31 @@ rewrite_use_address (struct ivopts_data *data,
   tree iv = var_at_stmt (data->current_loop, cand, use->stmt);
   tree base_hint = (cand->iv->base_object) ? iv : NULL_TREE;
   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
-  tree type = TREE_TYPE (*use->op_p);
-  unsigned int align = get_object_alignment (*use->op_p);
-  if (align != TYPE_ALIGN (type))
-    type = build_aligned_type (type, align);
-
-  tree ref = create_mem_ref (&bsi, type, &aff,
-                            reference_alias_ptr_type (*use->op_p),
+  tree type = use->mem_type;
+  tree alias_ptr_type;
+  if (use->type == USE_PTR_ADDRESS)
+    alias_ptr_type = get_alias_ptr_type_for_ptr_address (use);
+  else
+    {
+      gcc_assert (type == TREE_TYPE (*use->op_p));
+      unsigned int align = get_object_alignment (*use->op_p);
+      if (align != TYPE_ALIGN (type))
+       type = build_aligned_type (type, align);
+      alias_ptr_type = reference_alias_ptr_type (*use->op_p);
+    }
+  tree ref = create_mem_ref (&bsi, type, &aff, alias_ptr_type,
                             iv, base_hint, data->speed);
 
-  copy_ref_info (ref, *use->op_p);
+  if (use->type == USE_PTR_ADDRESS)
+    {
+      ref = fold_build1 (ADDR_EXPR, build_pointer_type (use->mem_type), ref);
+      ref = fold_convert (get_use_type (use), ref);
+      ref = force_gimple_operand_gsi (&bsi, ref, true, NULL_TREE,
+                                     true, GSI_SAME_STMT);
+    }
+  else
+    copy_ref_info (ref, *use->op_p);
+
   *use->op_p = ref;
 }
 
@@ -7039,7 +7562,7 @@ rewrite_use_compare (struct ivopts_data *data,
   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
   enum tree_code compare;
   struct iv_group *group = data->vgroups[use->group_id];
-  struct cost_pair *cp = get_group_iv_cost (data, group, cand);
+  class cost_pair *cp = get_group_iv_cost (data, group, cand);
 
   bound = cp->value;
   if (bound)
@@ -7100,7 +7623,7 @@ rewrite_groups (struct ivopts_data *data)
              update_stmt (group->vuses[j]->stmt);
            }
        }
-      else if (group->type == USE_ADDRESS)
+      else if (address_p (group->type))
        {
          for (j = 0; j < group->vuses.length (); j++)
            {
@@ -7124,11 +7647,10 @@ rewrite_groups (struct ivopts_data *data)
 /* Removes the ivs that are not used after rewriting.  */
 
 static void
-remove_unused_ivs (struct ivopts_data *data)
+remove_unused_ivs (struct ivopts_data *data, bitmap toremove)
 {
   unsigned j;
   bitmap_iterator bi;
-  bitmap toremove = BITMAP_ALLOC (NULL);
 
   /* Figure out an order in which to release SSA DEFs so that we don't
      release something that we'd have to propagate into a debug stmt
@@ -7148,7 +7670,7 @@ remove_unused_ivs (struct ivopts_data *data)
 
          tree def = info->iv->ssa_name;
 
-         if (MAY_HAVE_DEBUG_STMTS && SSA_NAME_DEF_STMT (def))
+         if (MAY_HAVE_DEBUG_BIND_STMTS && SSA_NAME_DEF_STMT (def))
            {
              imm_use_iterator imm_iter;
              use_operand_p use_p;
@@ -7171,7 +7693,7 @@ remove_unused_ivs (struct ivopts_data *data)
                    count++;
 
                  if (count > 1)
-                   BREAK_FROM_IMM_USE_STMT (imm_iter);
+                   break;
                }
 
              if (!count)
@@ -7180,6 +7702,7 @@ remove_unused_ivs (struct ivopts_data *data)
              struct iv_use dummy_use;
              struct iv_cand *best_cand = NULL, *cand;
              unsigned i, best_pref = 0, cand_pref;
+             tree comp = NULL_TREE;
 
              memset (&dummy_use, 0, sizeof (dummy_use));
              dummy_use.iv = info->iv;
@@ -7200,20 +7723,23 @@ remove_unused_ivs (struct ivopts_data *data)
                    ? 1 : 0;
                  if (best_cand == NULL || best_pref < cand_pref)
                    {
-                     best_cand = cand;
-                     best_pref = cand_pref;
+                     tree this_comp
+                       = get_debug_computation_at (data->current_loop,
+                                                   SSA_NAME_DEF_STMT (def),
+                                                   &dummy_use, cand);
+                     if (this_comp)
+                       {
+                         best_cand = cand;
+                         best_pref = cand_pref;
+                         comp = this_comp;
+                       }
                    }
                }
 
              if (!best_cand)
                continue;
 
-             tree comp = get_computation_at (data->current_loop,
-                                             SSA_NAME_DEF_STMT (def),
-                                             &dummy_use, best_cand);
-             if (!comp)
-               continue;
-
+             comp = unshare_expr (comp);
              if (count > 1)
                {
                  tree vexpr = make_node (DEBUG_EXPR_DECL);
@@ -7250,13 +7776,9 @@ remove_unused_ivs (struct ivopts_data *data)
            }
        }
     }
-
-  release_defs_bitset (toremove);
-
-  BITMAP_FREE (toremove);
 }
 
-/* Frees memory occupied by struct tree_niter_desc in *VALUE. Callback
+/* Frees memory occupied by class tree_niter_desc in *VALUE. Callback
    for hash_map::traverse.  */
 
 bool
@@ -7367,6 +7889,8 @@ tree_ssa_iv_optimize_finalize (struct ivopts_data *data)
   delete data->inv_expr_tab;
   data->inv_expr_tab = NULL;
   free_affine_expand_cache (&data->name_expansion_cache);
+  if (data->base_object_map)
+    delete data->base_object_map;
   delete data->iv_common_cand_tab;
   data->iv_common_cand_tab = NULL;
   data->iv_common_cands.release ();
@@ -7393,19 +7917,137 @@ loop_body_includes_call (basic_block *body, unsigned num_nodes)
   return false;
 }
 
+/* Determine cost scaling factor for basic blocks in loop.  */
+#define COST_SCALING_FACTOR_BOUND (20)
+
+static void
+determine_scaling_factor (struct ivopts_data *data, basic_block *body)
+{
+  int lfreq = data->current_loop->header->count.to_frequency (cfun);
+  if (!data->speed || lfreq <= 0)
+    return;
+
+  int max_freq = lfreq;
+  for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
+    {
+      body[i]->aux = (void *)(intptr_t) 1;
+      if (max_freq < body[i]->count.to_frequency (cfun))
+       max_freq = body[i]->count.to_frequency (cfun);
+    }
+  if (max_freq > lfreq)
+    {
+      int divisor, factor;
+      /* Check if scaling factor itself needs to be scaled by the bound.  This
+        is to avoid overflow when scaling cost according to profile info.  */
+      if (max_freq / lfreq > COST_SCALING_FACTOR_BOUND)
+       {
+         divisor = max_freq;
+         factor = COST_SCALING_FACTOR_BOUND;
+       }
+      else
+       {
+         divisor = lfreq;
+         factor = 1;
+       }
+      for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
+       {
+         int bfreq = body[i]->count.to_frequency (cfun);
+         if (bfreq <= lfreq)
+           continue;
+
+         body[i]->aux = (void*)(intptr_t) (factor * bfreq / divisor);
+       }
+    }
+}
+
+/* Find doloop comparison use and set its doloop_p on if found.  */
+
+static bool
+find_doloop_use (struct ivopts_data *data)
+{
+  struct loop *loop = data->current_loop;
+
+  for (unsigned i = 0; i < data->vgroups.length (); i++)
+    {
+      struct iv_group *group = data->vgroups[i];
+      if (group->type == USE_COMPARE)
+       {
+         gcc_assert (group->vuses.length () == 1);
+         struct iv_use *use = group->vuses[0];
+         gimple *stmt = use->stmt;
+         if (gimple_code (stmt) == GIMPLE_COND)
+           {
+             basic_block bb = gimple_bb (stmt);
+             edge true_edge, false_edge;
+             extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
+             /* This comparison is used for loop latch.  Require latch is empty
+                for now.  */
+             if ((loop->latch == true_edge->dest
+                  || loop->latch == false_edge->dest)
+                 && empty_block_p (loop->latch))
+               {
+                 group->doloop_p = true;
+                 if (dump_file && (dump_flags & TDF_DETAILS))
+                   {
+                     fprintf (dump_file, "Doloop cmp iv use: ");
+                     print_gimple_stmt (dump_file, stmt, TDF_DETAILS);
+                   }
+                 return true;
+               }
+           }
+       }
+    }
+
+  return false;
+}
+
+/* For the targets which support doloop, to predict whether later RTL doloop
+   transformation will perform on this loop, further detect the doloop use and
+   mark the flag doloop_use_p if predicted.  */
+
+void
+analyze_and_mark_doloop_use (struct ivopts_data *data)
+{
+  data->doloop_use_p = false;
+
+  if (!flag_branch_on_count_reg)
+    return;
+
+  if (data->current_loop->unroll == USHRT_MAX)
+    return;
+
+  if (!generic_predict_doloop_p (data))
+    return;
+
+  if (find_doloop_use (data))
+    {
+      data->doloop_use_p = true;
+      if (dump_file && (dump_flags & TDF_DETAILS))
+       {
+         struct loop *loop = data->current_loop;
+         fprintf (dump_file,
+                  "Predict loop %d can perform"
+                  " doloop optimization later.\n",
+                  loop->num);
+         flow_loop_dump (loop, dump_file, NULL, 1);
+       }
+    }
+}
+
 /* Optimizes the LOOP.  Returns true if anything changed.  */
 
 static bool
-tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
+tree_ssa_iv_optimize_loop (struct ivopts_data *data, class loop *loop,
+                          bitmap toremove)
 {
   bool changed = false;
-  struct iv_ca *iv_ca;
+  class iv_ca *iv_ca;
   edge exit = single_dom_exit (loop);
   basic_block *body;
 
   gcc_assert (!data->niters);
   data->current_loop = loop;
-  data->loop_loc = find_loop_location (loop);
+  data->loop_loc = find_loop_location (loop).get_location_t ();
   data->speed = optimize_loop_for_speed_p (loop);
 
   if (dump_file && (dump_flags & TDF_DETAILS))
@@ -7430,9 +8072,9 @@ tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
   body = get_loop_body (loop);
   data->body_includes_call = loop_body_includes_call (body, loop->num_nodes);
   renumber_gimple_stmt_uids_in_blocks (body, loop->num_nodes);
-  free (body);
 
-  data->loop_single_exit_p = exit != NULL && loop_only_exit_p (loop, exit);
+  data->loop_single_exit_p
+    = exit != NULL && loop_only_exit_p (loop, body, exit);
 
   /* For each ssa name determines whether it behaves as an induction variable
      in some loop.  */
@@ -7444,6 +8086,12 @@ tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
   if (data->vgroups.length () > MAX_CONSIDERED_GROUPS)
     goto finish;
 
+  /* Determine cost scaling factor for basic blocks in loop.  */
+  determine_scaling_factor (data, body);
+
+  /* Analyze doloop possibility and mark the doloop use if predicted.  */
+  analyze_and_mark_doloop_use (data);
+
   /* Finds candidates for the induction variables (item 2).  */
   find_iv_candidates (data);
 
@@ -7454,6 +8102,9 @@ tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
 
   /* Find the optimal set of induction variables (item 3, part 2).  */
   iv_ca = find_optimal_iv_set (data);
+  /* Cleanup basic block aux field.  */
+  for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
+    body[i]->aux = NULL;
   if (!iv_ca)
     goto finish;
   changed = true;
@@ -7466,14 +8117,10 @@ tree_ssa_iv_optimize_loop (struct ivopts_data *data, struct loop *loop)
   rewrite_groups (data);
 
   /* Remove the ivs that are unused after rewriting.  */
-  remove_unused_ivs (data);
-
-  /* We have changed the structure of induction variables; it might happen
-     that definitions in the scev database refer to some of them that were
-     eliminated.  */
-  scev_reset ();
+  remove_unused_ivs (data, toremove);
 
 finish:
+  free (body);
   free_loop_data (data);
 
   return changed;
@@ -7484,20 +8131,33 @@ finish:
 void
 tree_ssa_iv_optimize (void)
 {
-  struct loop *loop;
   struct ivopts_data data;
+  auto_bitmap toremove;
 
   tree_ssa_iv_optimize_init (&data);
 
   /* Optimize the loops starting with the innermost ones.  */
-  FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
+  for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
     {
+      if (!dbg_cnt (ivopts_loop))
+       continue;
+
       if (dump_file && (dump_flags & TDF_DETAILS))
        flow_loop_dump (loop, dump_file, NULL, 1);
 
-      tree_ssa_iv_optimize_loop (&data, loop);
+      tree_ssa_iv_optimize_loop (&data, loop, toremove);
     }
 
+  /* Remove eliminated IV defs.  */
+  release_defs_bitset (toremove);
+
+  /* We have changed the structure of induction variables; it might happen
+     that definitions in the scev database refer to some of them that were
+     eliminated.  */
+  scev_reset_htab ();
+  /* Likewise niter and control-IV information.  */
+  free_numbers_of_iterations_estimates (cfun);
+
   tree_ssa_iv_optimize_finalize (&data);
 }