LCOV - code coverage report
Current view: top level - gcc - tree-ssa-loop-unswitch.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 96.1 % 767 737
Test Date: 2026-12-05 16:10:02 Functions: 100.0 % 32 32
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Loop unswitching.
       2              :    Copyright (C) 2004-2026 Free Software Foundation, Inc.
       3              : 
       4              : This file is part of GCC.
       5              : 
       6              : GCC is free software; you can redistribute it and/or modify it
       7              : under the terms of the GNU General Public License as published by the
       8              : Free Software Foundation; either version 3, or (at your option) any
       9              : later version.
      10              : 
      11              : GCC is distributed in the hope that it will be useful, but WITHOUT
      12              : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14              : for more details.
      15              : 
      16              : You should have received a copy of the GNU General Public License
      17              : along with GCC; see the file COPYING3.  If not see
      18              : <http://www.gnu.org/licenses/>.  */
      19              : 
      20              : #include "config.h"
      21              : #include "system.h"
      22              : #include "coretypes.h"
      23              : #include "backend.h"
      24              : #include "tree.h"
      25              : #include "gimple.h"
      26              : #include "tree-pass.h"
      27              : #include "ssa.h"
      28              : #include "fold-const.h"
      29              : #include "tree-cfg.h"
      30              : #include "tree-ssa.h"
      31              : #include "tree-ssa-loop-niter.h"
      32              : #include "tree-ssa-loop.h"
      33              : #include "tree-into-ssa.h"
      34              : #include "cfgloop.h"
      35              : #include "tree-inline.h"
      36              : #include "gimple-iterator.h"
      37              : #include "cfghooks.h"
      38              : #include "tree-ssa-loop-manip.h"
      39              : #include "tree-vectorizer.h"
      40              : #include "gimple-range.h"
      41              : #include "dbgcnt.h"
      42              : #include "cfganal.h"
      43              : #include "tree-cfgcleanup.h"
      44              : 
      45              : /* This file implements the loop unswitching, i.e. transformation of loops like
      46              : 
      47              :    while (A)
      48              :      {
      49              :        if (inv)
      50              :          B;
      51              : 
      52              :        X;
      53              : 
      54              :        if (!inv)
      55              :          C;
      56              :      }
      57              : 
      58              :    where inv is the loop invariant, into
      59              : 
      60              :    if (inv)
      61              :      {
      62              :        while (A)
      63              :          {
      64              :            B;
      65              :            X;
      66              :          }
      67              :      }
      68              :    else
      69              :      {
      70              :        while (A)
      71              :          {
      72              :            X;
      73              :            C;
      74              :          }
      75              :      }
      76              : 
      77              :    Inv is considered invariant iff the values it compares are both invariant;
      78              :    tree-ssa-loop-im.cc ensures that all the suitable conditions are in this
      79              :    shape.  */
      80              : 
      81              : /* Loop unswitching algorithm for innermost loops works in the following steps:
      82              : 
      83              :    1) Number of instructions is estimated for each BB that belongs to a loop.
      84              :    2) Unswitching candidates are found for gcond and gswitch statements
      85              :       (note that an unswitching predicate for a gswitch actually corresponds
      86              :        to a non-default edge so it can contain multiple cases).
      87              :    3) The so called unswitch predicates are stored in a cache where the
      88              :       gimple_uid of the last stmt in a basic-block is an index to the cache.
      89              :    4) We consider one by one the unswitching candidates and calculate BBs that
      90              :       will be reachable in the unswitch version.
      91              :    5) A selected predicate is chosen and we simplify the CFG (dead edges) in
      92              :       both versions of the loop.  We utilize both Ranger for condition
      93              :       simplification and also symbol equivalence.  The folded if conditions
      94              :       are replaced with true/false values, while for gswitch we mark the
      95              :       corresponding edges with a pass-defined unreachable flag.
      96              :    6) Every time we unswitch a loop, we save unswitch_predicate to a vector
      97              :       together with information if true or false edge was taken.  Doing that
      98              :       we have a so called PREDICATE_PATH that is utilized for simplification
      99              :       of the cloned loop.
     100              :    7) The process is repeated until we reach a growth threshold or all
     101              :       unswitching opportunities are taken.  */
     102              : 
     103              : /* A tuple that holds a GENERIC condition and value range for an unswitching
     104              :    predicate.  */
     105              : 
     106              : struct unswitch_predicate
     107              : {
     108              :   /* CTOR for a switch edge predicate.  */
     109          118 :   unswitch_predicate (tree cond, tree lhs_, int edge_index_, edge e,
     110              :                       const int_range_max& edge_range)
     111          118 :     : condition (cond), lhs (lhs_),
     112          118 :       true_range (edge_range), edge_index (edge_index_), switch_p (true)
     113              :   {
     114          118 :     gcc_assert (!(e->flags & (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE))
     115              :                 && irange::supports_p (TREE_TYPE (lhs)));
     116          118 :     false_range = true_range;
     117          118 :     if (!false_range.varying_p ()
     118          118 :         && !false_range.undefined_p ())
     119              :       {
     120          118 :         if (!false_range.invert ())
     121              :           {
     122            1 :             true_range.set_varying (TREE_TYPE (lhs));
     123            1 :             false_range.set_varying (TREE_TYPE (lhs));
     124              :           }
     125              :       }
     126          118 :     count = e->count ();
     127          118 :     num = predicates->length ();
     128          118 :     predicates->safe_push (this);
     129          118 :   }
     130              : 
     131              :   /* CTOR for a GIMPLE condition statement.  */
     132         2670 :   unswitch_predicate (gcond *stmt)
     133         2670 :     : switch_p (false)
     134              :   {
     135         2670 :     basic_block bb = gimple_bb (stmt);
     136         2670 :     if (EDGE_SUCC (bb, 0)->flags & EDGE_TRUE_VALUE)
     137              :       edge_index = 0;
     138              :     else
     139           62 :       edge_index = 1;
     140         2670 :     lhs = gimple_cond_lhs (stmt);
     141         2670 :     tree rhs = gimple_cond_rhs (stmt);
     142         2670 :     enum tree_code code = gimple_cond_code (stmt);
     143         2670 :     condition = build2 (code, boolean_type_node, lhs, rhs);
     144         2670 :     count = profile_count::max_prefer_initialized (EDGE_SUCC (bb, 0)->count (),
     145         2670 :                                                    EDGE_SUCC (bb, 1)->count ());
     146         2670 :     if (irange::supports_p (TREE_TYPE (lhs)))
     147              :       {
     148         2476 :         auto range_op = range_op_handler (code);
     149         2476 :         int_range<2> rhs_range (TREE_TYPE (rhs));
     150         2476 :         if (CONSTANT_CLASS_P (rhs))
     151              :           {
     152         2332 :             wide_int w = wi::to_wide (rhs);
     153         2332 :             rhs_range.set (TREE_TYPE (rhs), w, w);
     154         2332 :           }
     155         2476 :         if (!range_op.op1_range (true_range, TREE_TYPE (lhs),
     156         4952 :                                  range_true (), rhs_range)
     157         7428 :             || !range_op.op1_range (false_range, TREE_TYPE (lhs),
     158         4952 :                                     range_false (), rhs_range))
     159              :           {
     160            0 :             true_range.set_varying (TREE_TYPE (lhs));
     161            0 :             false_range.set_varying (TREE_TYPE (lhs));
     162              :           }
     163         2476 :       }
     164         2670 :     num = predicates->length ();
     165         2670 :     predicates->safe_push (this);
     166         2670 :   }
     167              : 
     168              :   /* Copy ranges for purpose of usage in predicate path.  */
     169              : 
     170              :   inline void
     171         7034 :   copy_merged_ranges ()
     172              :   {
     173         7034 :     merged_true_range = true_range;
     174         7034 :     merged_false_range = false_range;
     175         7034 :   }
     176              : 
     177              :   /* GENERIC unswitching expression testing LHS against CONSTANT.  */
     178              :   tree condition;
     179              : 
     180              :   /* LHS of the expression.  */
     181              :   tree lhs;
     182              : 
     183              :   /* Initial ranges (when the expression is true/false) for the expression.  */
     184              :   int_range_max true_range = {}, false_range = {};
     185              : 
     186              :   /* Modified range that is part of a predicate path.  */
     187              :   int_range_max merged_true_range = {}, merged_false_range = {};
     188              : 
     189              :   /* Index of the edge the predicate belongs to in the successor vector.  */
     190              :   int edge_index;
     191              : 
     192              :   /* The profile count of this predicate.  */
     193              :   profile_count count;
     194              : 
     195              :   /* Whether the predicate was created from a switch statement.  */
     196              :   bool switch_p;
     197              : 
     198              :   /* The number of the predicate in the predicates vector below.  */
     199              :   unsigned num;
     200              : 
     201              :   /* Vector of all used predicates, used for assigning a unique id that
     202              :      can be used for bitmap operations.  */
     203              :   static vec<unswitch_predicate *> *predicates;
     204              : };
     205              : 
     206              : vec<unswitch_predicate *> *unswitch_predicate::predicates;
     207              : 
     208              : /* Ranger instance used in the pass.  */
     209              : static gimple_ranger *ranger = NULL;
     210              : 
     211              : /* Cache storage for unswitch_predicate belonging to a basic block.  */
     212              : static vec<vec<unswitch_predicate *>> *bb_predicates;
     213              : 
     214              : /* The type represents a predicate path leading to a basic block.  */
     215              : typedef vec<std::pair<unswitch_predicate *, bool>> predicate_vector;
     216              : 
     217              : static class loop *tree_unswitch_loop (class loop *, edge, tree);
     218              : static bool tree_unswitch_single_loop (class loop *, dump_user_location_t,
     219              :                                        predicate_vector &predicate_path,
     220              :                                        unsigned loop_size, unsigned &budget,
     221              :                                        int ignored_edge_flag, bitmap,
     222              :                                        unswitch_predicate * = NULL,
     223              :                                        basic_block = NULL);
     224              : static void
     225              : find_unswitching_predicates_for_bb (basic_block bb, class loop *loop,
     226              :                                     class loop *&outer_loop,
     227              :                                     vec<unswitch_predicate *> &candidates,
     228              :                                     unswitch_predicate *&hottest,
     229              :                                     basic_block &hottest_bb);
     230              : static bool tree_unswitch_outer_loop (class loop *);
     231              : static edge find_loop_guard (class loop *, vec<gimple *>&);
     232              : static bool empty_bb_without_guard_p (class loop *, basic_block,
     233              :                                       vec<gimple *>&);
     234              : static bool used_outside_loop_p (class loop *, tree, vec<gimple *>&);
     235              : static void hoist_guard (class loop *, edge);
     236              : static bool check_exit_phi (class loop *);
     237              : static tree get_vop_from_header (class loop *);
     238              : static void clean_up_after_unswitching (int);
     239              : 
     240              : /* Return vector of predicates that belong to a basic block.  */
     241              : 
     242              : static vec<unswitch_predicate *> &
     243       385898 : get_predicates_for_bb (basic_block bb)
     244              : {
     245       385898 :   gimple *last = last_nondebug_stmt (bb);
     246       385898 :   return (*bb_predicates)[last == NULL ? 0 : gimple_uid (last)];
     247              : }
     248              : 
     249              : /* Save predicates that belong to a basic block.  */
     250              : 
     251              : static void
     252         2712 : set_predicates_for_bb (basic_block bb, vec<unswitch_predicate *> predicates)
     253              : {
     254         5424 :   gimple_set_uid (last_nondebug_stmt (bb), bb_predicates->length ());
     255         2712 :   bb_predicates->safe_push (predicates);
     256         2712 : }
     257              : 
     258              : /* Estimate number of instructions in LOOP using eni_size_weights.  */
     259              : 
     260              : static unsigned
     261        78577 : estimate_loop_insns (class loop *loop)
     262              : {
     263        78577 :   unsigned insns = 0;
     264        78577 :   basic_block *body = get_loop_body (loop);
     265       541988 :   for (unsigned i = 0; i < loop->num_nodes; i++)
     266       769668 :     for (gimple_stmt_iterator gsi = gsi_start_bb (body[i]);
     267      1736798 :          !gsi_end_p (gsi); gsi_next (&gsi))
     268      1351964 :       insns += estimate_num_insns (gsi_stmt (gsi), &eni_size_weights);
     269        78577 :   free (body);
     270        78577 :   return insns;
     271              : }
     272              : 
     273              : /* Initialize LOOP information reused during the unswitching pass.
     274              :    Return total number of instructions in the loop.  Adjusts LOOP to
     275              :    the outermost loop all candidates are invariant in.  */
     276              : 
     277              : static unsigned
     278        66975 : init_loop_unswitch_info (class loop *&loop, unswitch_predicate *&hottest,
     279              :                          basic_block &hottest_bb)
     280              : {
     281        66975 :   unsigned total_insns = 0;
     282              : 
     283        66975 :   basic_block *bbs = get_loop_body (loop);
     284              : 
     285              :   /* Unswitch only nests with no sibling loops.  Since predicates come from
     286              :      the innermost loop, only the outer-loop bodies get duplicated by hoisting
     287              :      the unswitching out; the innermost loop is shared in the cost estimate.  */
     288        66975 :   class loop *outer_loop = loop;
     289        66975 :   unsigned max_depth = param_max_unswitch_depth;
     290        66975 :   unsigned innermost_size = estimate_loop_insns (loop);
     291        66975 :   while (loop_outer (outer_loop)->num != 0
     292        78035 :          && !loop_outer (outer_loop)->inner->next)
     293              :     {
     294        11607 :       if (--max_depth == 0)
     295              :         break;
     296              : 
     297        11602 :       class loop *candidate = loop_outer (outer_loop);
     298        11602 :       unsigned candidate_size = estimate_loop_insns (candidate);
     299              : 
     300        11602 :       if (candidate_size - innermost_size
     301        11602 :           > (unsigned) param_max_unswitch_insns)
     302              :         {
     303          542 :           if (dump_enabled_p ())
     304            3 :             dump_printf_loc (MSG_NOTE, find_loop_location (loop),
     305              :                              "Not unswitching outer loop, duplicated size %u "
     306              :                              "exceeds max-unswitch-insns %u\n",
     307              :                              candidate_size - innermost_size,
     308              :                              (unsigned) param_max_unswitch_insns);
     309              :           break;
     310              :         }
     311              : 
     312        11060 :       outer_loop = candidate;
     313              :     }
     314        66975 :   hottest = NULL;
     315        66975 :   hottest_bb = NULL;
     316              :   /* Find all unswitching candidates in the innermost loop.  */
     317       311450 :   for (unsigned i = 0; i != loop->num_nodes; i++)
     318              :     {
     319              :       /* Find a bb to unswitch on.  */
     320       244475 :       vec<unswitch_predicate *> candidates;
     321       244475 :       candidates.create (1);
     322       244475 :       find_unswitching_predicates_for_bb (bbs[i], loop, outer_loop, candidates,
     323              :                                           hottest, hottest_bb);
     324       244475 :       if (!candidates.is_empty ())
     325         2712 :         set_predicates_for_bb (bbs[i], candidates);
     326              :       else
     327              :         {
     328       241763 :           candidates.release ();
     329       241763 :           gimple *last = last_nondebug_stmt (bbs[i]);
     330       241763 :           if (last != NULL)
     331       151584 :             gimple_set_uid (last, 0);
     332              :         }
     333              :     }
     334              : 
     335        66975 :   if (outer_loop != loop)
     336              :     {
     337         8827 :       free (bbs);
     338         8827 :       bbs = get_loop_body (outer_loop);
     339              :     }
     340              : 
     341              :   /* Calculate instruction count.  */
     342       375332 :   for (unsigned i = 0; i < outer_loop->num_nodes; i++)
     343              :     {
     344       308357 :       unsigned insns = 0;
     345      1703051 :       for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);
     346      1086337 :            gsi_next (&gsi))
     347      1086337 :         insns += estimate_num_insns (gsi_stmt (gsi), &eni_size_weights);
     348              :       /* No predicates to unswitch on in the outer loops.  */
     349       308357 :       if (!flow_bb_inside_loop_p (loop, bbs[i]))
     350              :         {
     351        63882 :           gimple *last = last_nondebug_stmt (bbs[i]);
     352        63882 :           if (last != NULL)
     353        38084 :             gimple_set_uid (last, 0);
     354              :         }
     355              : 
     356       308357 :       bbs[i]->aux = (void *)(uintptr_t)insns;
     357       308357 :       total_insns += insns;
     358              :     }
     359              : 
     360        66975 :   free (bbs);
     361              : 
     362        66975 :   loop = outer_loop;
     363        66975 :   return total_insns;
     364              : }
     365              : 
     366              : /* Main entry point.  Perform loop unswitching on all suitable loops.  */
     367              : 
     368              : unsigned int
     369        30649 : tree_ssa_unswitch_loops (function *fun)
     370              : {
     371        30649 :   bool changed_unswitch = false;
     372        30649 :   bool changed_hoist = false;
     373        30649 :   auto_edge_flag ignored_edge_flag (fun);
     374        30649 :   mark_ssa_maybe_undefs ();
     375              : 
     376        30649 :   ranger = enable_ranger (fun);
     377              : 
     378              :   /* Go through all loops starting from innermost, hoisting guards.  */
     379       177787 :   for (auto loop : loops_list (fun, LI_FROM_INNERMOST))
     380              :     {
     381        85840 :       if (loop->inner)
     382        15373 :         changed_hoist |= tree_unswitch_outer_loop (loop);
     383        30649 :     }
     384              : 
     385              :   /* Go through innermost loops, unswitching on invariant predicates
     386              :      within those.  */
     387       162414 :   for (auto loop : loops_list (fun, LI_ONLY_INNERMOST))
     388              :     {
     389              :       /* Perform initial tests if unswitch is eligible.  */
     390        70467 :       dump_user_location_t loc = find_loop_location (loop);
     391              : 
     392              :       /* Do not unswitch in cold regions. */
     393        70467 :       if (optimize_loop_for_size_p (loop))
     394              :         {
     395         1276 :           if (dump_enabled_p ())
     396            0 :             dump_printf_loc (MSG_NOTE, loc,
     397              :                              "Not unswitching cold loops\n");
     398         3492 :           continue;
     399              :         }
     400              : 
     401              :       /* If the loop is not expected to iterate, there is no need
     402              :          for unswitching.  */
     403        69191 :       HOST_WIDE_INT iterations = estimated_loop_iterations_int (loop);
     404        69191 :       if (iterations < 0)
     405        41590 :         iterations = likely_max_loop_iterations_int (loop);
     406        69191 :       if (iterations >= 0 && iterations <= 1)
     407              :         {
     408         2216 :           if (dump_enabled_p ())
     409            2 :             dump_printf_loc (MSG_NOTE, loc,
     410              :                              "Not unswitching, loop is not expected"
     411              :                              " to iterate\n");
     412         2216 :           continue;
     413              :         }
     414              : 
     415        66975 :       bb_predicates = new vec<vec<unswitch_predicate *>> ();
     416        66975 :       bb_predicates->safe_push (vec<unswitch_predicate *> ());
     417        66975 :       unswitch_predicate::predicates = new vec<unswitch_predicate *> ();
     418              : 
     419              :       /* Unswitch loop.  */
     420        66975 :       unswitch_predicate *hottest;
     421        66975 :       basic_block hottest_bb;
     422        66975 :       unsigned int loop_size = init_loop_unswitch_info (loop, hottest,
     423              :                                                         hottest_bb);
     424        66975 :       unsigned int budget = loop_size + param_max_unswitch_insns;
     425              : 
     426        66975 :       predicate_vector predicate_path;
     427        66975 :       predicate_path.create (8);
     428        66975 :       auto_bitmap handled;
     429        66975 :       changed_unswitch |= tree_unswitch_single_loop (loop, loc, predicate_path,
     430              :                                                      loop_size, budget,
     431              :                                                      ignored_edge_flag, handled,
     432              :                                                      hottest, hottest_bb);
     433        66975 :       predicate_path.release ();
     434              : 
     435       270612 :       for (auto predlist : bb_predicates)
     436        69687 :         predlist.release ();
     437        66975 :       bb_predicates->release ();
     438        66975 :       delete bb_predicates;
     439        66975 :       bb_predicates = NULL;
     440              : 
     441       203713 :       for (auto pred : unswitch_predicate::predicates)
     442         2788 :         delete pred;
     443        66975 :       unswitch_predicate::predicates->release ();
     444        66975 :       delete unswitch_predicate::predicates;
     445        66975 :       unswitch_predicate::predicates = NULL;
     446        66975 :     }
     447              : 
     448        30649 :   disable_ranger (fun);
     449        30649 :   clear_aux_for_blocks ();
     450              : 
     451        30649 :   if (changed_unswitch)
     452         1416 :     clean_up_after_unswitching (ignored_edge_flag);
     453              : 
     454        30649 :   if (changed_unswitch || changed_hoist)
     455         1980 :     cleanup_tree_cfg ();
     456              : 
     457         1980 :   if (changed_unswitch)
     458         1416 :     return loop_invariant_motion_in_fun (cfun, false);
     459              : 
     460              :   return 0;
     461        30649 : }
     462              : 
     463              : /* Return TRUE if an SSA_NAME maybe undefined and is therefore
     464              :    unsuitable for unswitching.  STMT is the statement we are
     465              :    considering for unswitching and LOOP is the loop it appears in.  */
     466              : 
     467              : static bool
     468        19853 : is_maybe_undefined (const tree name, gimple *stmt, class loop *loop)
     469              : {
     470              :   /* The loop header is the only block we can trivially determine that
     471              :      will always be executed.  If the comparison is in the loop
     472              :      header, we know it's OK to unswitch on it.  */
     473            0 :   if (gimple_bb (stmt) == loop->header)
     474              :     return false;
     475              : 
     476         9487 :   return ssa_name_maybe_undef_p (name);
     477              : }
     478              : 
     479              : /* Checks whether we can unswitch LOOP on condition at end of BB -- one of its
     480              :    basic blocks (for what it means see comments below).
     481              :    All candidates all filled to the provided vector CANDIDATES.
     482              :    OUTER_LOOP is updated to the innermost loop all found candidates are
     483              :    invariant in.  */
     484              : 
     485              : static void
     486       244475 : find_unswitching_predicates_for_bb (basic_block bb, class loop *loop,
     487              :                                     class loop *&outer_loop,
     488              :                                     vec<unswitch_predicate *> &candidates,
     489              :                                     unswitch_predicate *&hottest,
     490              :                                     basic_block &hottest_bb)
     491              : {
     492       244475 :   gimple *last, *def;
     493       244475 :   tree use;
     494       244475 :   basic_block def_bb;
     495       244475 :   ssa_op_iter iter;
     496              : 
     497              :   /* BB must end in a simple conditional jump.  */
     498       244475 :   last = *gsi_last_bb (bb);
     499       244475 :   if (!last)
     500       217340 :     return;
     501              : 
     502       154673 :   if (gcond *stmt = safe_dyn_cast <gcond *> (last))
     503              :     {
     504              :       /* To keep the things simple, we do not directly remove the conditions,
     505              :          but just replace tests with 0 != 0 resp. 1 != 0.  Prevent the infinite
     506              :          loop where we would unswitch again on such a condition.  */
     507       130046 :       if (gimple_cond_true_p (stmt) || gimple_cond_false_p (stmt))
     508       127376 :         return;
     509              : 
     510              :       /* At least the LHS needs to be symbolic.  */
     511       130046 :       if (TREE_CODE (gimple_cond_lhs (stmt)) != SSA_NAME)
     512              :         return;
     513              : 
     514              :       /* Condition must be invariant.  */
     515       148985 :       FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
     516              :         {
     517       146306 :           def = SSA_NAME_DEF_STMT (use);
     518       146306 :           def_bb = gimple_bb (def);
     519       146306 :           if (def_bb
     520       146306 :               && flow_bb_inside_loop_p (loop, def_bb))
     521              :             return;
     522              :           /* Unswitching on undefined values would introduce undefined
     523              :              behavior that the original program might never exercise.  */
     524        28049 :           if (is_maybe_undefined (use, stmt, loop))
     525              :             return;
     526              :         }
     527              :       /* A condition that may trap must not be evaluated where the original
     528              :          program does not evaluate it.  Only the header of LOOP is known to
     529              :          execute once LOOP is entered, so require that, and do not hoist the
     530              :          condition out of any enclosing loop, which might not be entered.  */
     531         2679 :       if (gimple_could_trap_p (stmt))
     532              :         {
     533           14 :           if (bb != loop->header)
     534              :             return;
     535            5 :           outer_loop = loop;
     536              :         }
     537              :       /* Narrow OUTER_LOOP.  */
     538         2670 :       if (outer_loop != loop)
     539         1546 :         FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
     540              :           {
     541          782 :             def = SSA_NAME_DEF_STMT (use);
     542          782 :             def_bb = gimple_bb (def);
     543          782 :             while (outer_loop != loop
     544         1065 :                    && ((def_bb && flow_bb_inside_loop_p (outer_loop, def_bb))
     545         1417 :                        || is_maybe_undefined (use, stmt, outer_loop)))
     546          283 :               outer_loop = superloop_at_depth (loop,
     547          566 :                                                loop_depth (outer_loop) + 1);
     548              :           }
     549              : 
     550         2670 :       unswitch_predicate *predicate = new unswitch_predicate (stmt);
     551         2670 :       candidates.safe_push (predicate);
     552              :       /* If we unswitch on this predicate we isolate both paths, so
     553              :          pick the highest count for updating of the hottest predicate
     554              :          to unswitch on first.  */
     555         2670 :       if (!hottest || predicate->count > hottest->count)
     556              :         {
     557         1914 :           hottest = predicate;
     558         1914 :           hottest_bb = bb;
     559              :         }
     560              :     }
     561        27339 :   else if (gswitch *stmt = safe_dyn_cast <gswitch *> (last))
     562              :     {
     563          204 :       unsigned nlabels = gimple_switch_num_labels (stmt);
     564          204 :       tree idx = gimple_switch_index (stmt);
     565          204 :       tree idx_type = TREE_TYPE (idx);
     566          204 :       if (!gimple_range_ssa_p (idx) || nlabels < 1)
     567          162 :         return;
     568              :       /* Index must be invariant.  */
     569          204 :       def = SSA_NAME_DEF_STMT (idx);
     570          204 :       def_bb = gimple_bb (def);
     571          204 :       if (def_bb
     572          204 :           && flow_bb_inside_loop_p (loop, def_bb))
     573              :         return;
     574              :       /* Unswitching on undefined values would introduce undefined
     575              :          behavior that the original program might never exercise.  */
     576           63 :       if (is_maybe_undefined (idx, stmt, loop))
     577              :         return;
     578              :       /* Narrow OUTER_LOOP.  */
     579           42 :       while (outer_loop != loop
     580           42 :              && ((def_bb && flow_bb_inside_loop_p (outer_loop, def_bb))
     581            4 :                  || is_maybe_undefined (idx, stmt, outer_loop)))
     582            0 :         outer_loop = superloop_at_depth (loop,
     583            0 :                                          loop_depth (outer_loop) + 1);
     584              : 
     585              :       /* Build compound expression for all outgoing edges of the switch.  */
     586           42 :       auto_vec<tree, 16> preds;
     587           42 :       auto_vec<int_range_max> edge_range;
     588           84 :       preds.safe_grow_cleared (EDGE_COUNT (gimple_bb (stmt)->succs), true);
     589           84 :       edge_range.safe_grow_cleared (EDGE_COUNT (gimple_bb (stmt)->succs), true);
     590           42 :       edge e;
     591           42 :       edge_iterator ei;
     592           42 :       unsigned edge_index = 0;
     593          199 :       FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->succs)
     594          157 :         e->aux = (void *)(uintptr_t)edge_index++;
     595          430 :       for (unsigned i = 1; i < gimple_switch_num_labels (stmt); ++i)
     596              :         {
     597          388 :           tree lab = gimple_switch_label (stmt, i);
     598          388 :           tree cmp;
     599          388 :           int_range<2> lab_range;
     600          388 :           tree low = fold_convert (idx_type, CASE_LOW (lab));
     601          388 :           if (CASE_HIGH (lab) != NULL_TREE)
     602              :             {
     603            3 :               tree high = fold_convert (idx_type, CASE_HIGH (lab));
     604            3 :               tree cmp1 = fold_build2 (GE_EXPR, boolean_type_node, idx, low);
     605            3 :               tree cmp2 = fold_build2 (LE_EXPR, boolean_type_node, idx, high);
     606            3 :               cmp = fold_build2 (BIT_AND_EXPR, boolean_type_node, cmp1, cmp2);
     607            3 :               lab_range.set (idx_type, wi::to_wide (low), wi::to_wide (high));
     608              :             }
     609              :           else
     610              :             {
     611          385 :               cmp = fold_build2 (EQ_EXPR, boolean_type_node, idx, low);
     612          385 :               wide_int w = wi::to_wide (low);
     613          385 :               lab_range.set (idx_type, w, w);
     614          385 :             }
     615              : 
     616              :           /* Combine the expression with the existing one.  */
     617          388 :           basic_block dest = label_to_block (cfun, CASE_LABEL (lab));
     618          388 :           e = find_edge (gimple_bb (stmt), dest);
     619          388 :           tree &expr = preds[(uintptr_t)e->aux];
     620          388 :           if (expr == NULL_TREE)
     621              :             expr = cmp;
     622              :           else
     623          270 :             expr = fold_build2 (BIT_IOR_EXPR, boolean_type_node, expr, cmp);
     624          388 :           edge_range[(uintptr_t)e->aux].union_ (lab_range);
     625          388 :         }
     626              : 
     627              :       /* Now register the predicates.  */
     628          199 :       for (edge_index = 0; edge_index < preds.length (); ++edge_index)
     629              :         {
     630          157 :           edge e = EDGE_SUCC (gimple_bb (stmt), edge_index);
     631          157 :           e->aux = NULL;
     632          157 :           if (preds[edge_index] != NULL_TREE)
     633              :             {
     634          118 :               unswitch_predicate *predicate
     635          118 :                 = new unswitch_predicate (preds[edge_index], idx,
     636              :                                           edge_index, e,
     637          118 :                                           edge_range[edge_index]);
     638          118 :               candidates.safe_push (predicate);
     639          118 :               if (!hottest || predicate->count > hottest->count)
     640              :                 {
     641           38 :                   hottest = predicate;
     642           38 :                   hottest_bb = bb;
     643              :                 }
     644              :             }
     645              :         }
     646           42 :     }
     647              : }
     648              : 
     649              : /* Merge ranges for the last item of PREDICATE_PATH with a predicate
     650              :    that shared the same LHS.  */
     651              : 
     652              : static void
     653         7034 : merge_last (predicate_vector &predicate_path)
     654              : {
     655         7034 :   unswitch_predicate *last_predicate = predicate_path.last ().first;
     656              : 
     657        10034 :   for (int i = predicate_path.length () - 2; i >= 0; i--)
     658              :     {
     659         4038 :       unswitch_predicate *predicate = predicate_path[i].first;
     660         4038 :       bool true_edge = predicate_path[i].second;
     661              : 
     662         4038 :       if (operand_equal_p (predicate->lhs, last_predicate->lhs, 0))
     663              :         {
     664         1038 :           irange &other = (true_edge ? predicate->merged_true_range
     665              :                            : predicate->merged_false_range);
     666         1038 :           last_predicate->merged_true_range.intersect (other);
     667         1038 :           last_predicate->merged_false_range.intersect (other);
     668         1038 :           return;
     669              :         }
     670              :     }
     671              : }
     672              : 
     673              : /* Add PREDICATE to PREDICATE_PATH on TRUE_EDGE.  */
     674              : 
     675              : static void
     676         7034 : add_predicate_to_path (predicate_vector &predicate_path,
     677              :                        unswitch_predicate *predicate, bool true_edge)
     678              : {
     679         7034 :   predicate->copy_merged_ranges ();
     680         7034 :   predicate_path.safe_push (std::make_pair (predicate, true_edge));
     681         7034 :   merge_last (predicate_path);
     682         7034 : }
     683              : 
     684              : static bool
     685         1558 : find_range_for_lhs (predicate_vector &predicate_path, tree lhs,
     686              :                     int_range_max &range)
     687              : {
     688         3146 :   for (int i = predicate_path.length () - 1; i >= 0; i--)
     689              :     {
     690         1570 :       unswitch_predicate *predicate = predicate_path[i].first;
     691         1570 :       bool true_edge = predicate_path[i].second;
     692              : 
     693         1570 :       if (operand_equal_p (predicate->lhs, lhs, 0))
     694              :         {
     695         1540 :           range = (true_edge ? predicate->merged_true_range
     696         1540 :                    : predicate->merged_false_range);
     697         1540 :           return !range.undefined_p ();
     698              :         }
     699              :     }
     700              : 
     701              :   return false;
     702              : }
     703              : 
     704              : /* Simplifies STMT using the predicate we unswitched on which is the last
     705              :    in PREDICATE_PATH.  For switch statements add newly unreachable edges
     706              :    to IGNORED_EDGES (but do not set IGNORED_EDGE_FLAG on them).  */
     707              : 
     708              : static tree
     709        17186 : evaluate_control_stmt_using_entry_checks (gimple *stmt,
     710              :                                           predicate_vector &predicate_path,
     711              :                                           int ignored_edge_flag,
     712              :                                           hash_set<edge> *ignored_edges)
     713              : {
     714        17186 :   unswitch_predicate *last_predicate = predicate_path.last ().first;
     715        17186 :   bool true_edge = predicate_path.last ().second;
     716              : 
     717        17186 :   if (gcond *cond = dyn_cast<gcond *> (stmt))
     718              :     {
     719        16736 :       tree lhs = gimple_cond_lhs (cond);
     720        16736 :       if (!operand_equal_p (lhs, last_predicate->lhs))
     721              :         return NULL_TREE;
     722              :       /* Try a symbolic match which works for floating point and fully
     723              :          symbolic conditions.  */
     724         9936 :       if (gimple_cond_code (cond) == TREE_CODE (last_predicate->condition)
     725        19319 :           && operand_equal_p (gimple_cond_rhs (cond),
     726         9383 :                               TREE_OPERAND (last_predicate->condition, 1)))
     727         8748 :         return true_edge ? boolean_true_node : boolean_false_node;
     728              :       /* Else try ranger if it supports LHS.  */
     729         1188 :       else if (irange::supports_p (TREE_TYPE (lhs)))
     730              :         {
     731         1186 :           int_range<2> r;
     732         1186 :           int_range_max path_range;
     733              : 
     734         1186 :           if (find_range_for_lhs (predicate_path, lhs, path_range)
     735         1186 :               && fold_range (r, cond, path_range)
     736         2372 :               && r.singleton_p ())
     737          357 :             return r.zero_p () ? boolean_false_node : boolean_true_node;
     738         1186 :         }
     739              :     }
     740          450 :   else if (gswitch *swtch = dyn_cast<gswitch *> (stmt))
     741              :     {
     742          450 :       unsigned nlabels = gimple_switch_num_labels (swtch);
     743              : 
     744          450 :       tree idx = gimple_switch_index (swtch);
     745              : 
     746              :       /* Already folded switch.  */
     747          450 :       if (TREE_CONSTANT (idx))
     748          264 :         return NULL_TREE;
     749              : 
     750          372 :       int_range_max path_range;
     751          372 :       if (!find_range_for_lhs (predicate_path, idx, path_range))
     752              :         return NULL_TREE;
     753              : 
     754              :       tree result = NULL_TREE;
     755              :       edge single_edge = NULL;
     756         2680 :       for (unsigned i = 0; i < nlabels; ++i)
     757              :         {
     758         2326 :           tree lab = gimple_switch_label (swtch, i);
     759         2326 :           basic_block dest = label_to_block (cfun, CASE_LABEL (lab));
     760         2326 :           edge e = find_edge (gimple_bb (stmt), dest);
     761         2326 :           if (e->flags & ignored_edge_flag)
     762          410 :             continue;
     763              : 
     764         1916 :           int_range_max r;
     765         1916 :           if (!ranger->gori ().edge_range_p (r, e, idx,
     766              :                                              *get_global_range_query ()))
     767            0 :             continue;
     768         1916 :           r.intersect (path_range);
     769         1916 :           if (r.undefined_p ())
     770          691 :             ignored_edges->add (e);
     771              :           else
     772              :             {
     773         1225 :               if (!single_edge)
     774              :                 {
     775          354 :                   single_edge = e;
     776          354 :                   result = CASE_LOW (lab);
     777              :                 }
     778          871 :               else if (single_edge != e)
     779         1916 :                 result = NULL;
     780              :             }
     781         1916 :         }
     782              : 
     783              :       /* Only one edge from the switch is alive.  */
     784          354 :       if (single_edge && result)
     785              :         return result;
     786          372 :     }
     787              : 
     788              :   return NULL_TREE;
     789              : }
     790              : 
     791              : /* Simplify LOOP based on PREDICATE_PATH where dead edges are properly
     792              :    marked.  */
     793              : 
     794              : static bool
     795         4914 : simplify_loop_version (class loop *loop, predicate_vector &predicate_path,
     796              :                        int ignored_edge_flag, bitmap handled)
     797              : {
     798         4914 :   bool changed = false;
     799         4914 :   basic_block *bbs = get_loop_body (loop);
     800              : 
     801         4914 :   hash_set<edge> ignored_edges;
     802        51942 :   for (unsigned i = 0; i != loop->num_nodes; i++)
     803              :     {
     804        42114 :       vec<unswitch_predicate *> &predicates = get_predicates_for_bb (bbs[i]);
     805        42114 :       if (predicates.is_empty ())
     806        32496 :         continue;
     807              : 
     808         9618 :       gimple *stmt = *gsi_last_bb (bbs[i]);
     809         9618 :       tree folded = evaluate_control_stmt_using_entry_checks (stmt,
     810              :                                                               predicate_path,
     811              :                                                               ignored_edge_flag,
     812              :                                                               &ignored_edges);
     813              : 
     814         9618 :       if (gcond *cond = dyn_cast<gcond *> (stmt))
     815              :         {
     816         9396 :           if (folded)
     817              :             {
     818              :               /* Remove path.  */
     819         5503 :               if (integer_nonzerop (folded))
     820         2685 :                 gimple_cond_set_condition_from_tree (cond, boolean_true_node);
     821              :               else
     822         2818 :                 gimple_cond_set_condition_from_tree (cond, boolean_false_node);
     823              : 
     824         5503 :               gcc_assert (predicates.length () == 1);
     825         5503 :               bitmap_set_bit (handled, predicates[0]->num);
     826              : 
     827         5503 :               update_stmt (cond);
     828         5503 :               changed = true;
     829              :             }
     830              :         }
     831        42336 :       else if (gswitch *swtch = dyn_cast<gswitch *> (stmt))
     832              :         {
     833          222 :           edge e;
     834          222 :           edge_iterator ei;
     835         1094 :           FOR_EACH_EDGE (e, ei, bbs[i]->succs)
     836          872 :             if (ignored_edges.contains (e))
     837          299 :               e->flags |= ignored_edge_flag;
     838              : 
     839          878 :           for (unsigned j = 0; j < predicates.length (); j++)
     840              :             {
     841          656 :               edge e = EDGE_SUCC (bbs[i], predicates[j]->edge_index);
     842          656 :               if (ignored_edges.contains (e))
     843          218 :                 bitmap_set_bit (handled, predicates[j]->num);
     844              :             }
     845              : 
     846          222 :           if (folded)
     847              :             {
     848           81 :               gimple_switch_set_index (swtch, folded);
     849           81 :               update_stmt (swtch);
     850           81 :               changed = true;
     851              :             }
     852              :         }
     853              :     }
     854              : 
     855         4914 :   free (bbs);
     856         4914 :   return changed;
     857         4914 : }
     858              : 
     859              : /* Evaluate reachable blocks in LOOP and call VISIT on them, aborting the
     860              :    DFS walk if VISIT returns true.  When PREDICATE_PATH is specified then
     861              :    take into account that when computing reachability, otherwise just
     862              :    look at the simplified state and IGNORED_EDGE_FLAG.  */
     863              : 
     864              : template <typename VisitOp>
     865              : static void
     866        72198 : evaluate_bbs (class loop *loop, predicate_vector *predicate_path,
     867              :               int ignored_edge_flag, VisitOp visit)
     868              : {
     869        72198 :   auto_bb_flag reachable_flag (cfun);
     870        72198 :   auto_vec<basic_block, 10> worklist (loop->num_nodes);
     871        72198 :   auto_vec<basic_block, 10> reachable (loop->num_nodes);
     872        72198 :   hash_set<edge> ignored_edges;
     873              : 
     874        72198 :   loop->header->flags |= reachable_flag;
     875        72198 :   worklist.quick_push (loop->header);
     876        72198 :   reachable.safe_push (loop->header);
     877              : 
     878       508926 :   while (!worklist.is_empty ())
     879              :     {
     880              :       edge e;
     881              :       edge_iterator ei;
     882       367299 :       int flags = ignored_edge_flag;
     883       367299 :       basic_block bb = worklist.pop ();
     884              : 
     885       367299 :       if (visit (bb))
     886              :         break;
     887              : 
     888       366650 :       gimple *last = *gsi_last_bb (bb);
     889       179848 :       if (gcond *cond = safe_dyn_cast <gcond *> (last))
     890              :         {
     891       186802 :           if (gimple_cond_true_p (cond))
     892              :             flags = EDGE_FALSE_VALUE;
     893       181565 :           else if (gimple_cond_false_p (cond))
     894              :             flags = EDGE_TRUE_VALUE;
     895       175492 :           else if (predicate_path)
     896              :             {
     897              :               tree res;
     898       373990 :               if (!get_predicates_for_bb (bb).is_empty ()
     899         7340 :                   && (res = evaluate_control_stmt_using_entry_checks
     900         7340 :                               (cond, *predicate_path, ignored_edge_flag,
     901              :                                &ignored_edges)))
     902         5448 :                 flags = (integer_nonzerop (res)
     903         3602 :                          ? EDGE_FALSE_VALUE : EDGE_TRUE_VALUE);
     904              :             }
     905              :         }
     906       367217 :       else if (gswitch *swtch = safe_dyn_cast<gswitch *> (last))
     907              :         if (predicate_path
     908          567 :             && !get_predicates_for_bb (bb).is_empty ())
     909          228 :           evaluate_control_stmt_using_entry_checks (swtch, *predicate_path,
     910              :                                                     ignored_edge_flag,
     911              :                                                     &ignored_edges);
     912              : 
     913              :       /* Note that for the moment we do not account reachable conditions
     914              :          which are simplified to take a known edge as zero size nor
     915              :          are we accounting for the required addition of the versioning
     916              :          condition.  Those should cancel out conservatively.  */
     917              : 
     918       922723 :       FOR_EACH_EDGE (e, ei, bb->succs)
     919              :         {
     920       556073 :           basic_block dest = e->dest;
     921              : 
     922       556073 :           if (flow_bb_inside_loop_p (loop, dest)
     923       443564 :               && !(dest->flags & reachable_flag)
     924       308553 :               && !(e->flags & flags)
     925       851497 :               && !ignored_edges.contains (e))
     926              :             {
     927       295151 :               dest->flags |= reachable_flag;
     928       295151 :               worklist.safe_push (dest);
     929       295151 :               reachable.safe_push (dest);
     930              :             }
     931              :         }
     932              :     }
     933              : 
     934              :   /* Clear the flag from basic blocks.  */
     935       511745 :   while (!reachable.is_empty ())
     936       367349 :     reachable.pop ()->flags &= ~reachable_flag;
     937        72198 : }
     938              : 
     939              : /* Evaluate how many instruction will we have if we unswitch LOOP (with BBS)
     940              :    based on PREDICATE predicate (using PREDICATE_PATH).  Store the
     941              :    result in TRUE_SIZE and FALSE_SIZE.  */
     942              : 
     943              : static void
     944         1060 : evaluate_loop_insns_for_predicate (class loop *loop,
     945              :                                    predicate_vector &predicate_path,
     946              :                                    unswitch_predicate *predicate,
     947              :                                    int ignored_edge_flag,
     948              :                                    unsigned *true_size, unsigned *false_size)
     949              : {
     950         1060 :   unsigned size = 0;
     951        45691 :   auto sum_size = [&](basic_block bb) -> bool
     952        44631 :     { size += (uintptr_t)bb->aux; return false; };
     953              : 
     954         1060 :   add_predicate_to_path (predicate_path, predicate, true);
     955         1060 :   evaluate_bbs (loop, &predicate_path, ignored_edge_flag, sum_size);
     956         1060 :   predicate_path.pop ();
     957         1060 :   unsigned true_loop_cost = size;
     958              : 
     959         1060 :   size = 0;
     960         1060 :   add_predicate_to_path (predicate_path, predicate, false);
     961         1060 :   evaluate_bbs (loop, &predicate_path, ignored_edge_flag, sum_size);
     962         1060 :   predicate_path.pop ();
     963         1060 :   unsigned false_loop_cost = size;
     964              : 
     965         1060 :   *true_size = true_loop_cost;
     966         1060 :   *false_size = false_loop_cost;
     967         1060 : }
     968              : 
     969              : /* Unswitch single LOOP.  PREDICATE_PATH contains so far used predicates
     970              :    for unswitching.  BUDGET is number of instruction for which we can increase
     971              :    the loop and is updated when unswitching occurs.  If HOTTEST is not
     972              :    NULL then pick this candidate as the one to unswitch on.  */
     973              : 
     974              : static bool
     975        71889 : tree_unswitch_single_loop (class loop *loop, dump_user_location_t loc,
     976              :                            predicate_vector &predicate_path,
     977              :                            unsigned loop_size, unsigned &budget,
     978              :                            int ignored_edge_flag, bitmap handled,
     979              :                            unswitch_predicate *hottest, basic_block hottest_bb)
     980              : {
     981        71889 :   class loop *nloop;
     982        71889 :   bool changed = false;
     983        71889 :   unswitch_predicate *predicate = NULL;
     984        71889 :   basic_block predicate_bb = NULL;
     985        71889 :   unsigned true_size = 0, false_size = 0;
     986              : 
     987       394557 :   auto check_predicates = [&](basic_block bb) -> bool
     988              :     {
     989       345419 :       for (auto pred : get_predicates_for_bb (bb))
     990              :         {
     991         8038 :           if (bitmap_bit_p (handled, pred->num))
     992         6978 :             continue;
     993              : 
     994         1060 :           evaluate_loop_insns_for_predicate (loop, predicate_path,
     995              :                                              pred, ignored_edge_flag,
     996              :                                              &true_size, &false_size);
     997              : 
     998              :           /* We'll get LOOP replaced with a simplified version according
     999              :              to PRED estimated to TRUE_SIZE and a copy simplified
    1000              :              according to the inverted PRED estimated to FALSE_SIZE.  */
    1001         1060 :           if (true_size + false_size < budget + loop_size)
    1002              :             {
    1003          649 :               predicate = pred;
    1004          649 :               predicate_bb = bb;
    1005              : 
    1006              :               /* There are cases where true_size and false_size add up to
    1007              :                  less than the original loop_size.  We do not want to
    1008              :                  grow the remaining budget because of that.  */
    1009          649 :               if (true_size + false_size > loop_size)
    1010          649 :                 budget -= (true_size + false_size - loop_size);
    1011              : 
    1012              :               /* FIXME: right now we select first candidate, but we can
    1013              :                  choose the cheapest or hottest one.  */
    1014              :               return true;
    1015              :             }
    1016          411 :           else if (dump_enabled_p ())
    1017           13 :             dump_printf_loc (MSG_NOTE, loc,
    1018              :                              "not unswitching condition, cost too big "
    1019              :                              "(%u insns copied to %u and %u)\n", loop_size,
    1020              :                              true_size, false_size);
    1021              :         }
    1022              :       return false;
    1023        71889 :     };
    1024              : 
    1025        71889 :   if (hottest)
    1026              :     {
    1027         1811 :       predicate = hottest;
    1028         1811 :       predicate_bb = hottest_bb;
    1029              :     }
    1030              :   else
    1031              :     /* Check predicates of reachable blocks.  */
    1032        70078 :     evaluate_bbs (loop, NULL, ignored_edge_flag, check_predicates);
    1033              : 
    1034        71889 :   if (predicate != NULL)
    1035              :     {
    1036         2460 :       if (!dbg_cnt (loop_unswitch))
    1037            0 :         goto exit;
    1038              : 
    1039         2460 :       if (dump_enabled_p ())
    1040              :         {
    1041          104 :           dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
    1042              :                            "unswitching %sloop %d on %qs with condition: %T\n",
    1043          104 :                            loop->inner ? "outer " : "",
    1044          104 :                            loop->num, predicate->switch_p ? "switch" : "if",
    1045              :                            predicate->condition);
    1046          104 :           dump_printf_loc (MSG_NOTE, loc,
    1047              :                            "optimized sizes estimated to %u (true) "
    1048              :                            "and %u (false) from original size %u\n",
    1049              :                            true_size, false_size, loop_size);
    1050              :         }
    1051              : 
    1052         2460 :       bitmap_set_bit (handled, predicate->num);
    1053         2460 :       initialize_original_copy_tables ();
    1054              :       /* Unswitch the loop on this condition.  */
    1055         2460 :       nloop = tree_unswitch_loop (loop, EDGE_SUCC (predicate_bb,
    1056              :                                                    predicate->edge_index),
    1057              :                                   predicate->condition);
    1058         2460 :       if (!nloop)
    1059              :         {
    1060            3 :           free_original_copy_tables ();
    1061            3 :           goto exit;
    1062              :         }
    1063              : 
    1064              :       /* Copy BB costs.  */
    1065         2457 :       basic_block *bbs2 = get_loop_body (nloop);
    1066        25971 :       for (unsigned i = 0; i < nloop->num_nodes; i++)
    1067        21057 :         bbs2[i]->aux = get_bb_original (bbs2[i])->aux;
    1068         2457 :       free (bbs2);
    1069              : 
    1070         2457 :       free_original_copy_tables ();
    1071              : 
    1072              :       /* Update the SSA form after unswitching.  */
    1073         2457 :       update_ssa (TODO_update_ssa_no_phi);
    1074              : 
    1075              :       /* Invoke itself on modified loops.  */
    1076         2457 :       bitmap handled_copy = BITMAP_ALLOC (NULL);
    1077         2457 :       bitmap_copy (handled_copy, handled);
    1078         2457 :       add_predicate_to_path (predicate_path, predicate, false);
    1079         2457 :       changed |= simplify_loop_version (nloop, predicate_path,
    1080              :                                         ignored_edge_flag, handled_copy);
    1081         2457 :       tree_unswitch_single_loop (nloop, loc, predicate_path,
    1082              :                                  false_size, budget,
    1083              :                                  ignored_edge_flag, handled_copy);
    1084         2457 :       predicate_path.pop ();
    1085         2457 :       BITMAP_FREE (handled_copy);
    1086              : 
    1087              :       /* FIXME: After unwinding above we have to reset all ->handled
    1088              :          flags as otherwise we fail to realize unswitching opportunities
    1089              :          in the below recursion.  See gcc.dg/loop-unswitch-16.c  */
    1090         2457 :       add_predicate_to_path (predicate_path, predicate, true);
    1091         2457 :       changed |= simplify_loop_version (loop, predicate_path,
    1092              :                                         ignored_edge_flag, handled);
    1093         2457 :       tree_unswitch_single_loop (loop, loc, predicate_path,
    1094              :                                  true_size, budget,
    1095              :                                  ignored_edge_flag, handled);
    1096         2457 :       predicate_path.pop ();
    1097         2457 :       changed = true;
    1098              :     }
    1099              : 
    1100        69429 : exit:
    1101        71889 :   return changed;
    1102              : }
    1103              : 
    1104              : /* Unswitch a LOOP w.r. to given EDGE_TRUE.  We only support unswitching of
    1105              :    innermost loops.  COND is the condition determining which loop is entered;
    1106              :    the new loop is entered if COND is true.  Returns NULL if impossible, new
    1107              :    loop otherwise.  */
    1108              : 
    1109              : static class loop *
    1110         2460 : tree_unswitch_loop (class loop *loop, edge edge_true, tree cond)
    1111              : {
    1112              :   /* Some sanity checking.  */
    1113         2460 :   gcc_assert (flow_bb_inside_loop_p (loop, edge_true->src));
    1114         2460 :   gcc_assert (EDGE_COUNT (edge_true->src->succs) >= 2);
    1115              : 
    1116         2460 :   profile_probability prob_true = edge_true->probability;
    1117         2460 :   return loop_version (loop, unshare_expr (cond),
    1118              :                        NULL, prob_true,
    1119              :                        prob_true.invert (),
    1120              :                        prob_true, prob_true.invert (),
    1121         2460 :                        false);
    1122              : }
    1123              : 
    1124              : /* Unswitch outer loops by hoisting invariant guard on
    1125              :    inner loop without code duplication.  */
    1126              : static bool
    1127        15373 : tree_unswitch_outer_loop (class loop *loop)
    1128              : {
    1129        15373 :   edge exit, guard;
    1130        15373 :   HOST_WIDE_INT iterations;
    1131              : 
    1132        15373 :   gcc_assert (loop->inner);
    1133        15373 :   if (loop->inner->next)
    1134              :     return false;
    1135              :   /* Accept loops with single exit only which is not from inner loop.  */
    1136        13086 :   exit = single_exit (loop);
    1137        13086 :   if (!exit || exit->src->loop_father != loop)
    1138              :     return false;
    1139              :   /* Check that phi argument of exit edge is not defined inside loop.  */
    1140         9027 :   if (!check_exit_phi (loop))
    1141              :     return false;
    1142              :   /* If the loop is not expected to iterate, there is no need
    1143              :       for unswitching.  */
    1144         6523 :   iterations = estimated_loop_iterations_int (loop);
    1145         6523 :   if (iterations < 0)
    1146         4033 :     iterations = likely_max_loop_iterations_int (loop);
    1147         6523 :   if (iterations >= 0 && iterations <= 1)
    1148              :     {
    1149          292 :       if (dump_enabled_p ())
    1150            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, find_loop_location (loop),
    1151              :                          "Not unswitching, loop is not expected"
    1152              :                          " to iterate\n");
    1153              :       return false;
    1154              :     }
    1155              : 
    1156         6231 :   bool changed = false;
    1157         6231 :   auto_vec<gimple *> dbg_to_reset;
    1158         8034 :   while ((guard = find_loop_guard (loop, dbg_to_reset)))
    1159              :     {
    1160         1803 :       hoist_guard (loop, guard);
    1161         1803 :       for (gimple *debug_stmt : dbg_to_reset)
    1162              :         {
    1163            0 :           gimple_debug_bind_reset_value (debug_stmt);
    1164            0 :           update_stmt (debug_stmt);
    1165              :         }
    1166         1803 :       dbg_to_reset.truncate (0);
    1167         1803 :       changed = true;
    1168              :     }
    1169         6231 :   return changed;
    1170         6231 : }
    1171              : 
    1172              : /* Checks if the body of the LOOP is within an invariant guard.  If this
    1173              :    is the case, returns the edge that jumps over the real body of the loop,
    1174              :    otherwise returns NULL.  */
    1175              : 
    1176              : static edge
    1177         8034 : find_loop_guard (class loop *loop, vec<gimple *> &dbg_to_reset)
    1178              : {
    1179         8034 :   basic_block header = loop->header;
    1180         8034 :   edge guard_edge, te, fe;
    1181         8034 :   basic_block *body = NULL;
    1182        15517 :   unsigned i;
    1183        15517 :   tree use;
    1184        15517 :   ssa_op_iter iter;
    1185              : 
    1186              :   /* We check for the following situation:
    1187              : 
    1188              :      while (1)
    1189              :        {
    1190              :          [header]]
    1191              :          loop_phi_nodes;
    1192              :          something1;
    1193              :          if (cond1)
    1194              :            body;
    1195              :          nvar = phi(orig, bvar) ... for all variables changed in body;
    1196              :          [guard_end]
    1197              :          something2;
    1198              :          if (cond2)
    1199              :            break;
    1200              :          something3;
    1201              :        }
    1202              : 
    1203              :      where:
    1204              : 
    1205              :      1) cond1 is loop invariant
    1206              :      2) If cond1 is false, then the loop is essentially empty; i.e.,
    1207              :         a) nothing in something1, something2 and something3 has side
    1208              :            effects
    1209              :         b) anything defined in something1, something2 and something3
    1210              :            is not used outside of the loop.  */
    1211              : 
    1212        15517 :   gcond *cond;
    1213        15517 :   do
    1214              :     {
    1215        15517 :       basic_block next = NULL;
    1216        15517 :       if (single_succ_p (header))
    1217         4583 :         next = single_succ (header);
    1218              :       else
    1219              :         {
    1220        21868 :           cond = safe_dyn_cast <gcond *> (*gsi_last_bb (header));
    1221        10932 :           if (! cond)
    1222              :             return NULL;
    1223        10932 :           extract_true_false_edges_from_block (header, &te, &fe);
    1224              :           /* Make sure to skip earlier hoisted guards that are left
    1225              :              in place as if (true).  */
    1226        10932 :           if (gimple_cond_true_p (cond))
    1227          390 :             next = te->dest;
    1228        10542 :           else if (gimple_cond_false_p (cond))
    1229         2510 :             next = fe->dest;
    1230              :           else
    1231              :             break;
    1232              :         }
    1233              :       /* Never traverse a backedge.  */
    1234         7483 :       if (header->loop_father->header == next)
    1235              :         return NULL;
    1236              :       header = next;
    1237              :     }
    1238              :   while (1);
    1239         8032 :   if (!flow_bb_inside_loop_p (loop, te->dest)
    1240         8032 :       || !flow_bb_inside_loop_p (loop, fe->dest))
    1241              :     return NULL;
    1242              : 
    1243         7918 :   if (just_once_each_iteration_p (loop, te->dest)
    1244         7918 :       || (single_succ_p (te->dest)
    1245         4839 :           && just_once_each_iteration_p (loop, single_succ (te->dest))))
    1246              :     {
    1247         4059 :       if (just_once_each_iteration_p (loop, fe->dest))
    1248              :         return NULL;
    1249         4049 :       guard_edge = te;
    1250              :     }
    1251         3859 :   else if (just_once_each_iteration_p (loop, fe->dest)
    1252         3859 :            || (single_succ_p (fe->dest)
    1253         1919 :                && just_once_each_iteration_p (loop, single_succ (fe->dest))))
    1254         2347 :     guard_edge = fe;
    1255              :   else
    1256              :     return NULL;
    1257              : 
    1258         6396 :   dump_user_location_t loc = find_loop_location (loop);
    1259              : 
    1260              :   /* Guard edge must skip inner loop.  */
    1261         6396 :   if (!dominated_by_p (CDI_DOMINATORS, loop->inner->header,
    1262         6396 :       guard_edge == fe ? te->dest : fe->dest))
    1263              :     {
    1264         2493 :       if (dump_enabled_p ())
    1265            4 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, loc,
    1266              :                          "Guard edge %d --> %d is not around the loop!\n",
    1267            4 :                          guard_edge->src->index, guard_edge->dest->index);
    1268              :       return NULL;
    1269              :     }
    1270         3903 :   if (guard_edge->dest == loop->latch)
    1271              :     {
    1272            0 :       if (dump_enabled_p ())
    1273            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, loc,
    1274              :                          "Guard edge destination is loop latch.\n");
    1275              :       return NULL;
    1276              :     }
    1277              : 
    1278         3903 :   if (dump_enabled_p ())
    1279          104 :     dump_printf_loc (MSG_NOTE, loc,
    1280              :                      "Considering guard %d -> %d in loop %d\n",
    1281          104 :                      guard_edge->src->index, guard_edge->dest->index,
    1282              :                      loop->num);
    1283              :   /* Check if condition operands do not have definitions inside loop since
    1284              :      any bb copying is not performed.  */
    1285         6779 :   FOR_EACH_SSA_TREE_OPERAND (use, cond, iter, SSA_OP_USE)
    1286              :     {
    1287         4809 :       gimple *def = SSA_NAME_DEF_STMT (use);
    1288         4809 :       basic_block def_bb = gimple_bb (def);
    1289         4809 :       if (def_bb
    1290         4809 :           && flow_bb_inside_loop_p (loop, def_bb))
    1291              :         {
    1292         1933 :           if (dump_enabled_p ())
    1293           96 :             dump_printf_loc (MSG_NOTE, loc, "guard operands have definitions"
    1294              :                              " inside loop\n");
    1295              :           return NULL;
    1296              :         }
    1297              :     }
    1298              : 
    1299         1970 :   body = get_loop_body (loop);
    1300        24666 :   for (i = 0; i < loop->num_nodes; i++)
    1301              :     {
    1302        20893 :       basic_block bb = body[i];
    1303        20893 :       if (bb->loop_father != loop)
    1304        10489 :         continue;
    1305        10404 :       if (bb->flags & BB_IRREDUCIBLE_LOOP)
    1306              :         {
    1307            0 :           if (dump_enabled_p ())
    1308            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, loc,
    1309              :                              "Block %d is marked as irreducible in loop\n",
    1310              :                              bb->index);
    1311            0 :           guard_edge = NULL;
    1312            0 :           goto end;
    1313              :         }
    1314              :       /* If any of the not skipped blocks has side-effects or defs with
    1315              :          uses outside of the loop we cannot hoist the guard.  */
    1316        10404 :       if (!dominated_by_p (CDI_DOMINATORS,
    1317        10404 :                            bb, guard_edge == te ? fe->dest : te->dest)
    1318        10404 :           && !empty_bb_without_guard_p (loop, bb, dbg_to_reset))
    1319              :         {
    1320          167 :           if (dump_enabled_p ())
    1321            1 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, loc,
    1322              :                              "Block %d has side effects\n", bb->index);
    1323          167 :           guard_edge = NULL;
    1324          167 :           goto end;
    1325              :         }
    1326              :     }
    1327              : 
    1328         1803 :   if (dump_enabled_p ())
    1329            7 :     dump_printf_loc (MSG_NOTE, loc,
    1330              :                      "suitable to hoist\n");
    1331         1796 : end:
    1332         1970 :   if (body)
    1333         1970 :     free (body);
    1334              :   return guard_edge;
    1335              : }
    1336              : 
    1337              : /* Returns true if
    1338              :    1) no statement in BB has side effects
    1339              :    2) assuming that edge GUARD is always taken, all definitions in BB
    1340              :       are noy used outside of the loop.
    1341              :    KNOWN_INVARIANTS is a set of ssa names we know to be invariant, and
    1342              :    PROCESSED is a set of ssa names for that we already tested whether they
    1343              :    are invariant or not.  Uses in debug stmts outside of the loop are
    1344              :    pushed to DBG_TO_RESET.  */
    1345              : 
    1346              : static bool
    1347         7301 : empty_bb_without_guard_p (class loop *loop, basic_block bb,
    1348              :                           vec<gimple *> &dbg_to_reset)
    1349              : {
    1350         7301 :   basic_block exit_bb = single_exit (loop)->src;
    1351         7301 :   bool may_be_used_outside = (bb == exit_bb
    1352         7301 :                               || !dominated_by_p (CDI_DOMINATORS, bb, exit_bb));
    1353              :   tree name;
    1354              :   ssa_op_iter op_iter;
    1355              : 
    1356              :   /* Phi nodes do not have side effects, but their results might be used
    1357              :      outside of the loop.  */
    1358              :   if (may_be_used_outside)
    1359              :     {
    1360         5352 :       for (gphi_iterator gsi = gsi_start_phis (bb);
    1361        11447 :            !gsi_end_p (gsi); gsi_next (&gsi))
    1362              :         {
    1363         6095 :           gphi *phi = gsi.phi ();
    1364         6095 :           name = PHI_RESULT (phi);
    1365        12190 :           if (virtual_operand_p (name))
    1366         3854 :             continue;
    1367              : 
    1368         2241 :           if (used_outside_loop_p (loop, name, dbg_to_reset))
    1369            0 :             return false;
    1370              :         }
    1371              :     }
    1372              : 
    1373        14602 :   for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
    1374        17067 :        !gsi_end_p (gsi); gsi_next (&gsi))
    1375              :     {
    1376         9933 :       gimple *stmt = gsi_stmt (gsi);
    1377         9933 :       if (is_gimple_debug (stmt))
    1378         1316 :         continue;
    1379              : 
    1380         8617 :       if (gimple_has_side_effects (stmt))
    1381              :         return false;
    1382              : 
    1383        12672 :       if (gimple_vdef(stmt))
    1384              :         return false;
    1385              : 
    1386        12538 :       FOR_EACH_SSA_TREE_OPERAND (name, stmt, op_iter, SSA_OP_DEF)
    1387              :         {
    1388         4088 :           if (may_be_used_outside
    1389         4088 :               && used_outside_loop_p (loop, name, dbg_to_reset))
    1390              :             return false;
    1391              :         }
    1392              :     }
    1393              :   return true;
    1394              : }
    1395              : 
    1396              : /* Return true if NAME is used outside of LOOP.  Pushes debug stmts that
    1397              :    have such uses to DBG_TO_RESET but do not consider such uses.  */
    1398              : 
    1399              : static bool
    1400         6307 : used_outside_loop_p (class loop *loop, tree name, vec<gimple *> &dbg_to_reset)
    1401              : {
    1402         6307 :   imm_use_iterator it;
    1403         6307 :   use_operand_p use;
    1404              : 
    1405        18491 :   FOR_EACH_IMM_USE_FAST (use, it, name)
    1406              :     {
    1407        12184 :       gimple *stmt = USE_STMT (use);
    1408        12184 :       if (!flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
    1409              :         {
    1410            0 :           if (!is_gimple_debug (stmt))
    1411            0 :             return true;
    1412            0 :           dbg_to_reset.safe_push (stmt);
    1413              :         }
    1414            0 :     }
    1415              : 
    1416         6307 :   return false;
    1417              : }
    1418              : 
    1419              : /* Return argument for loop preheader edge in header virtual phi if any.  */
    1420              : 
    1421              : static tree
    1422         1793 : get_vop_from_header (class loop *loop)
    1423              : {
    1424         1793 :   for (gphi_iterator gsi = gsi_start_phis (loop->header);
    1425         3609 :        !gsi_end_p (gsi); gsi_next (&gsi))
    1426              :     {
    1427         3609 :       gphi *phi = gsi.phi ();
    1428         7218 :       if (!virtual_operand_p (gimple_phi_result (phi)))
    1429         1816 :         continue;
    1430         1793 :       return PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
    1431              :     }
    1432            0 :   return NULL_TREE;
    1433              : }
    1434              : 
    1435              : /* Move the check of GUARD outside of LOOP.  */
    1436              : 
    1437              : static void
    1438         1803 : hoist_guard (class loop *loop, edge guard)
    1439              : {
    1440         1803 :   edge exit = single_exit (loop);
    1441         1803 :   edge preh = loop_preheader_edge (loop);
    1442         1803 :   basic_block pre_header = preh->src;
    1443         1803 :   basic_block bb;
    1444         1803 :   edge te, fe, e, new_edge;
    1445         1803 :   gimple *stmt;
    1446         1803 :   basic_block guard_bb = guard->src;
    1447         1803 :   edge not_guard;
    1448         1803 :   gimple_stmt_iterator gsi;
    1449         1803 :   int flags = 0;
    1450         1803 :   bool fix_dom_of_exit;
    1451         1803 :   gcond *cond_stmt, *new_cond_stmt;
    1452              : 
    1453         1803 :   bb = get_immediate_dominator (CDI_DOMINATORS, exit->dest);
    1454         1803 :   fix_dom_of_exit = flow_bb_inside_loop_p (loop, bb);
    1455         1803 :   gsi = gsi_last_bb (guard_bb);
    1456         1803 :   stmt = gsi_stmt (gsi);
    1457         1803 :   gcc_assert (gimple_code (stmt) == GIMPLE_COND);
    1458         1803 :   cond_stmt = as_a <gcond *> (stmt);
    1459         1803 :   extract_true_false_edges_from_block (guard_bb, &te, &fe);
    1460              :   /* Insert guard to PRE_HEADER.  */
    1461         1803 :   gsi = gsi_last_bb (pre_header);
    1462              :   /* Create copy of COND_STMT.  */
    1463         1803 :   new_cond_stmt = gimple_build_cond (gimple_cond_code (cond_stmt),
    1464              :                                      gimple_cond_lhs (cond_stmt),
    1465              :                                      gimple_cond_rhs (cond_stmt),
    1466              :                                      NULL_TREE, NULL_TREE);
    1467         1803 :   gsi_insert_after (&gsi, new_cond_stmt, GSI_NEW_STMT);
    1468              :   /* Convert COND_STMT to true/false conditional.  */
    1469         1803 :   if (guard == te)
    1470         1562 :     gimple_cond_make_false (cond_stmt);
    1471              :   else
    1472          241 :     gimple_cond_make_true (cond_stmt);
    1473         1803 :   update_stmt (cond_stmt);
    1474              :   /* Create new loop pre-header.  */
    1475         1803 :   e = split_block (pre_header, last_nondebug_stmt (pre_header));
    1476              : 
    1477         1803 :   dump_user_location_t loc = find_loop_location (loop);
    1478              : 
    1479         1803 :   if (dump_enabled_p ())
    1480              :     {
    1481            7 :       char buffer[64];
    1482            7 :       guard->probability.dump (buffer);
    1483              : 
    1484            7 :       dump_printf_loc (MSG_NOTE, loc,
    1485              :                        "Moving guard %i->%i (prob %s) to bb %i, "
    1486              :                        "new preheader is %i\n",
    1487            7 :                        guard->src->index, guard->dest->index,
    1488            7 :                        buffer, e->src->index, e->dest->index);
    1489              :     }
    1490              : 
    1491         1803 :   gcc_assert (loop_preheader_edge (loop)->src == e->dest);
    1492              : 
    1493         1803 :   if (guard == fe)
    1494              :     {
    1495          241 :       e->flags = EDGE_TRUE_VALUE;
    1496          241 :       flags |= EDGE_FALSE_VALUE;
    1497          241 :       not_guard = te;
    1498              :     }
    1499              :   else
    1500              :     {
    1501         1562 :       e->flags = EDGE_FALSE_VALUE;
    1502         1562 :       flags |= EDGE_TRUE_VALUE;
    1503         1562 :       not_guard = fe;
    1504              :     }
    1505         1803 :   new_edge = make_edge (pre_header, exit->dest, flags);
    1506              : 
    1507              :   /* Determine the probability that we skip the loop.  Assume that loop has
    1508              :      same average number of iterations regardless outcome of guard.  */
    1509         1803 :   new_edge->probability = guard->probability;
    1510         3606 :   profile_count skip_count = guard->src->count.nonzero_p ()
    1511         3606 :                    ? guard->count ().apply_scale (pre_header->count,
    1512         1803 :                                                guard->src->count)
    1513            0 :                    : guard->count ().apply_probability (new_edge->probability);
    1514              : 
    1515         1803 :   if (skip_count > e->count ())
    1516              :     {
    1517            0 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1518            0 :         fprintf (dump_file, "  Capping count; expect profile inconsistency\n");
    1519            0 :       skip_count = e->count ();
    1520              :     }
    1521         1803 :   if (dump_enabled_p ())
    1522              :     {
    1523            7 :       char buffer[64];
    1524            7 :       new_edge->probability.dump (buffer);
    1525              : 
    1526            7 :       dump_printf_loc (MSG_NOTE, loc,
    1527              :                        "Estimated probability of skipping loop is %s\n",
    1528              :                        buffer);
    1529              :     }
    1530              : 
    1531              :   /* Update profile after the transform:
    1532              : 
    1533              :      First decrease count of path from newly hoisted loop guard
    1534              :      to loop header...  */
    1535         1803 :   e->probability = new_edge->probability.invert ();
    1536         1803 :   e->dest->count = e->count ();
    1537              : 
    1538              :   /* ... now update profile to represent that original guard will be optimized
    1539              :      away ...  */
    1540         1803 :   guard->probability = profile_probability::never ();
    1541         1803 :   not_guard->probability = profile_probability::always ();
    1542              : 
    1543              :   /* ... finally scale everything in the loop except for guarded basic blocks
    1544              :      where profile does not change.  */
    1545         1803 :   basic_block *body = get_loop_body (loop);
    1546              : 
    1547        24032 :   for (unsigned int i = 0; i < loop->num_nodes; i++)
    1548              :     {
    1549        20426 :       basic_block bb = body[i];
    1550        20426 :       if (!dominated_by_p (CDI_DOMINATORS, bb, not_guard->dest))
    1551              :         {
    1552         6834 :           if (dump_enabled_p ())
    1553           29 :             dump_printf_loc (MSG_NOTE, loc,
    1554              :                              "Scaling nonguarded BBs in loop: %i\n",
    1555              :                              bb->index);
    1556         6834 :           if (e->probability.initialized_p ())
    1557         6834 :             scale_bbs_frequencies (&bb, 1, e->probability);
    1558              :         }
    1559              :     }
    1560              : 
    1561         1803 :   if (fix_dom_of_exit)
    1562          700 :     set_immediate_dominator (CDI_DOMINATORS, exit->dest, pre_header);
    1563              :   /* Add NEW_ADGE argument for all phi in post-header block.  */
    1564         1803 :   bb = exit->dest;
    1565         1803 :   for (gphi_iterator gsi = gsi_start_phis (bb);
    1566         3792 :        !gsi_end_p (gsi); gsi_next (&gsi))
    1567              :     {
    1568         1989 :       gphi *phi = gsi.phi ();
    1569         1989 :       tree arg;
    1570         3978 :       if (virtual_operand_p (gimple_phi_result (phi)))
    1571              :         {
    1572         1793 :           arg = get_vop_from_header (loop);
    1573         1793 :           if (arg == NULL_TREE)
    1574              :             /* Use exit edge argument.  */
    1575            0 :             arg =  PHI_ARG_DEF_FROM_EDGE (phi, exit);
    1576         1793 :           add_phi_arg (phi, arg, new_edge, UNKNOWN_LOCATION);
    1577              :         }
    1578              :       else
    1579              :         {
    1580              :           /* Use exit edge argument.  */
    1581          196 :           arg = PHI_ARG_DEF_FROM_EDGE (phi, exit);
    1582          196 :           add_phi_arg (phi, arg, new_edge, UNKNOWN_LOCATION);
    1583              :         }
    1584              :     }
    1585              : 
    1586         1803 :   if (dump_enabled_p ())
    1587            7 :     dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
    1588              :                      "Guard hoisted\n");
    1589              : 
    1590         1803 :   free (body);
    1591         1803 : }
    1592              : 
    1593              : /* Return true if phi argument for exit edge can be used
    1594              :    for edge around loop.  */
    1595              : 
    1596              : static bool
    1597         9027 : check_exit_phi (class loop *loop)
    1598              : {
    1599         9027 :   edge exit = single_exit (loop);
    1600         9027 :   basic_block pre_header = loop_preheader_edge (loop)->src;
    1601              : 
    1602         9027 :   for (gphi_iterator gsi = gsi_start_phis (exit->dest);
    1603        15681 :        !gsi_end_p (gsi); gsi_next (&gsi))
    1604              :     {
    1605         9158 :       gphi *phi = gsi.phi ();
    1606         9158 :       tree arg;
    1607         9158 :       gimple *def;
    1608         9158 :       basic_block def_bb;
    1609        18316 :       if (virtual_operand_p (gimple_phi_result (phi)))
    1610         6495 :         continue;
    1611         2663 :       arg = PHI_ARG_DEF_FROM_EDGE (phi, exit);
    1612         2663 :       if (TREE_CODE (arg) != SSA_NAME)
    1613           17 :         continue;
    1614         2646 :       def = SSA_NAME_DEF_STMT (arg);
    1615         2646 :       if (!def)
    1616            0 :         continue;
    1617         2646 :       def_bb = gimple_bb (def);
    1618         2646 :       if (!def_bb)
    1619            0 :         continue;
    1620         2646 :       if (!dominated_by_p (CDI_DOMINATORS, pre_header, def_bb))
    1621              :         /* Definition inside loop!  */
    1622         2504 :         return false;
    1623              :       /* Check loop closed phi invariant.  */
    1624          142 :       if (!flow_bb_inside_loop_p (def_bb->loop_father, pre_header))
    1625              :         return false;
    1626              :     }
    1627         6523 :   return true;
    1628              : }
    1629              : 
    1630              : /* Remove all dead cases from switches that are unswitched.  */
    1631              : 
    1632              : static void
    1633         1416 : clean_up_after_unswitching (int ignored_edge_flag)
    1634              : {
    1635         1416 :   basic_block bb;
    1636         1416 :   edge e;
    1637         1416 :   edge_iterator ei;
    1638         1416 :   bool removed_edge = false;
    1639              : 
    1640        71598 :   FOR_EACH_BB_FN (bb, cfun)
    1641              :     {
    1642       140364 :       gswitch *stmt= safe_dyn_cast <gswitch *> (*gsi_last_bb (bb));
    1643          184 :       if (stmt && !CONSTANT_CLASS_P (gimple_switch_index (stmt)))
    1644              :         {
    1645           86 :           unsigned nlabels = gimple_switch_num_labels (stmt);
    1646           86 :           unsigned index = 1;
    1647           86 :           tree lab = gimple_switch_default_label (stmt);
    1648          172 :           edge default_e = find_edge (gimple_bb (stmt),
    1649           86 :                                       label_to_block (cfun, CASE_LABEL (lab)));
    1650          963 :           for (unsigned i = 1; i < nlabels; ++i)
    1651              :             {
    1652          791 :               tree lab = gimple_switch_label (stmt, i);
    1653          791 :               basic_block dest = label_to_block (cfun, CASE_LABEL (lab));
    1654          791 :               edge e = find_edge (gimple_bb (stmt), dest);
    1655          791 :               if (e == NULL)
    1656              :                 ; /* The edge is already removed.  */
    1657          775 :               else if (e->flags & ignored_edge_flag)
    1658              :                 {
    1659              :                   /* We may not remove the default label so we also have
    1660              :                      to preserve its edge.  But we can remove the
    1661              :                      non-default CASE sharing the edge.  */
    1662          100 :                   if (e != default_e)
    1663              :                     {
    1664          100 :                       remove_edge (e);
    1665          100 :                       removed_edge = true;
    1666              :                     }
    1667              :                 }
    1668              :               else
    1669              :                 {
    1670          675 :                   gimple_switch_set_label (stmt, index, lab);
    1671          675 :                   ++index;
    1672              :                 }
    1673              :             }
    1674              : 
    1675           86 :           if (index != nlabels)
    1676           44 :             gimple_switch_set_num_labels (stmt, index);
    1677              :         }
    1678              : 
    1679              :       /* Clean up the ignored_edge_flag from edges.  */
    1680       169561 :       FOR_EACH_EDGE (e, ei, bb->succs)
    1681        99379 :         e->flags &= ~ignored_edge_flag;
    1682              :     }
    1683              : 
    1684              :   /* If we removed an edge we possibly have to recompute dominators.  */
    1685         1416 :   if (removed_edge)
    1686           39 :     free_dominance_info (CDI_DOMINATORS);
    1687         1416 : }
    1688              : 
    1689              : /* Loop unswitching pass.  */
    1690              : 
    1691              : namespace {
    1692              : 
    1693              : const pass_data pass_data_tree_unswitch =
    1694              : {
    1695              :   GIMPLE_PASS, /* type */
    1696              :   "unswitch", /* name */
    1697              :   OPTGROUP_LOOP, /* optinfo_flags */
    1698              :   TV_TREE_LOOP_UNSWITCH, /* tv_id */
    1699              :   PROP_cfg, /* properties_required */
    1700              :   0, /* properties_provided */
    1701              :   0, /* properties_destroyed */
    1702              :   0, /* todo_flags_start */
    1703              :   0, /* todo_flags_finish */
    1704              : };
    1705              : 
    1706              : class pass_tree_unswitch : public gimple_opt_pass
    1707              : {
    1708              : public:
    1709       302985 :   pass_tree_unswitch (gcc::context *ctxt)
    1710       605970 :     : gimple_opt_pass (pass_data_tree_unswitch, ctxt)
    1711              :   {}
    1712              : 
    1713              :   /* opt_pass methods: */
    1714       251589 :   bool gate (function *) final override { return flag_unswitch_loops != 0; }
    1715              :   unsigned int execute (function *) final override;
    1716              : 
    1717              : }; // class pass_tree_unswitch
    1718              : 
    1719              : unsigned int
    1720        30649 : pass_tree_unswitch::execute (function *fun)
    1721              : {
    1722        61298 :   if (number_of_loops (fun) <= 1)
    1723              :     return 0;
    1724              : 
    1725        30649 :   return tree_ssa_unswitch_loops (fun);
    1726              : }
    1727              : 
    1728              : } // anon namespace
    1729              : 
    1730              : gimple_opt_pass *
    1731       302985 : make_pass_tree_unswitch (gcc::context *ctxt)
    1732              : {
    1733       302985 :   return new pass_tree_unswitch (ctxt);
    1734              : }
    1735              : 
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.