Avoid is_constant calls in vectorizable_bswap
[official-gcc.git] / gcc / tree-switch-conversion.c
blob9a594a01fc48cd78ef3fabe69a317f59cde4270f
1 /* Lower GIMPLE_SWITCH expressions to something more efficient than
2 a jump table.
3 Copyright (C) 2006-2018 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301, USA. */
22 /* This file handles the lowering of GIMPLE_SWITCH to an indexed
23 load, or a series of bit-test-and-branch expressions. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "backend.h"
29 #include "insn-codes.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "cfghooks.h"
34 #include "tree-pass.h"
35 #include "ssa.h"
36 #include "optabs-tree.h"
37 #include "cgraph.h"
38 #include "gimple-pretty-print.h"
39 #include "params.h"
40 #include "fold-const.h"
41 #include "varasm.h"
42 #include "stor-layout.h"
43 #include "cfganal.h"
44 #include "gimplify.h"
45 #include "gimple-iterator.h"
46 #include "gimplify-me.h"
47 #include "tree-cfg.h"
48 #include "cfgloop.h"
49 #include "alloc-pool.h"
50 #include "target.h"
51 #include "tree-into-ssa.h"
52 #include "omp-general.h"
54 /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
55 type in the GIMPLE type system that is language-independent? */
56 #include "langhooks.h"
58 #include "tree-switch-conversion.h"
60 using namespace tree_switch_conversion;
62 /* Constructor. */
64 switch_conversion::switch_conversion (): m_final_bb (NULL), m_other_count (),
65 m_constructors (NULL), m_default_values (NULL),
66 m_arr_ref_first (NULL), m_arr_ref_last (NULL),
67 m_reason (NULL), m_default_case_nonstandard (false), m_cfg_altered (false)
71 /* Collection information about SWTCH statement. */
73 void
74 switch_conversion::collect (gswitch *swtch)
76 unsigned int branch_num = gimple_switch_num_labels (swtch);
77 tree min_case, max_case;
78 unsigned int i;
79 edge e, e_default, e_first;
80 edge_iterator ei;
81 basic_block first;
83 m_switch = swtch;
85 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
86 is a default label which is the first in the vector.
87 Collect the bits we can deduce from the CFG. */
88 m_index_expr = gimple_switch_index (swtch);
89 m_switch_bb = gimple_bb (swtch);
90 m_default_bb
91 = label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
92 e_default = find_edge (m_switch_bb, m_default_bb);
93 m_default_prob = e_default->probability;
94 m_default_count = e_default->count ();
95 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
96 if (e != e_default)
97 m_other_count += e->count ();
99 /* Get upper and lower bounds of case values, and the covered range. */
100 min_case = gimple_switch_label (swtch, 1);
101 max_case = gimple_switch_label (swtch, branch_num - 1);
103 m_range_min = CASE_LOW (min_case);
104 if (CASE_HIGH (max_case) != NULL_TREE)
105 m_range_max = CASE_HIGH (max_case);
106 else
107 m_range_max = CASE_LOW (max_case);
109 m_contiguous_range = true;
110 tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : m_range_min;
111 for (i = 2; i < branch_num; i++)
113 tree elt = gimple_switch_label (swtch, i);
114 if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
116 m_contiguous_range = false;
117 break;
119 last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
122 if (m_contiguous_range)
124 first = label_to_block (CASE_LABEL (gimple_switch_label (swtch, 1)));
125 e_first = find_edge (m_switch_bb, first);
127 else
129 first = m_default_bb;
130 e_first = e_default;
133 /* See if there is one common successor block for all branch
134 targets. If it exists, record it in FINAL_BB.
135 Start with the destination of the first non-default case
136 if the range is contiguous and default case otherwise as
137 guess or its destination in case it is a forwarder block. */
138 if (! single_pred_p (e_first->dest))
139 m_final_bb = e_first->dest;
140 else if (single_succ_p (e_first->dest)
141 && ! single_pred_p (single_succ (e_first->dest)))
142 m_final_bb = single_succ (e_first->dest);
143 /* Require that all switch destinations are either that common
144 FINAL_BB or a forwarder to it, except for the default
145 case if contiguous range. */
146 if (m_final_bb)
147 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
149 if (e->dest == m_final_bb)
150 continue;
152 if (single_pred_p (e->dest)
153 && single_succ_p (e->dest)
154 && single_succ (e->dest) == m_final_bb)
155 continue;
157 if (e == e_default && m_contiguous_range)
159 m_default_case_nonstandard = true;
160 continue;
163 m_final_bb = NULL;
164 break;
167 m_range_size
168 = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
170 /* Get a count of the number of case labels. Single-valued case labels
171 simply count as one, but a case range counts double, since it may
172 require two compares if it gets lowered as a branching tree. */
173 m_count = 0;
174 for (i = 1; i < branch_num; i++)
176 tree elt = gimple_switch_label (swtch, i);
177 m_count++;
178 if (CASE_HIGH (elt)
179 && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
180 m_count++;
183 /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
184 block. Assume a CFG cleanup would have already removed degenerate
185 switch statements, this allows us to just use EDGE_COUNT. */
186 m_uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
189 /* Checks whether the range given by individual case statements of the switch
190 switch statement isn't too big and whether the number of branches actually
191 satisfies the size of the new array. */
193 bool
194 switch_conversion::check_range ()
196 gcc_assert (m_range_size);
197 if (!tree_fits_uhwi_p (m_range_size))
199 m_reason = "index range way too large or otherwise unusable";
200 return false;
203 if (tree_to_uhwi (m_range_size)
204 > ((unsigned) m_count * SWITCH_CONVERSION_BRANCH_RATIO))
206 m_reason = "the maximum range-branch ratio exceeded";
207 return false;
210 return true;
213 /* Checks whether all but the final BB basic blocks are empty. */
215 bool
216 switch_conversion::check_all_empty_except_final ()
218 edge e, e_default = find_edge (m_switch_bb, m_default_bb);
219 edge_iterator ei;
221 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
223 if (e->dest == m_final_bb)
224 continue;
226 if (!empty_block_p (e->dest))
228 if (m_contiguous_range && e == e_default)
230 m_default_case_nonstandard = true;
231 continue;
234 m_reason = "bad case - a non-final BB not empty";
235 return false;
239 return true;
242 /* This function checks whether all required values in phi nodes in final_bb
243 are constants. Required values are those that correspond to a basic block
244 which is a part of the examined switch statement. It returns true if the
245 phi nodes are OK, otherwise false. */
247 bool
248 switch_conversion::check_final_bb ()
250 gphi_iterator gsi;
252 m_phi_count = 0;
253 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
255 gphi *phi = gsi.phi ();
256 unsigned int i;
258 if (virtual_operand_p (gimple_phi_result (phi)))
259 continue;
261 m_phi_count++;
263 for (i = 0; i < gimple_phi_num_args (phi); i++)
265 basic_block bb = gimple_phi_arg_edge (phi, i)->src;
267 if (bb == m_switch_bb
268 || (single_pred_p (bb)
269 && single_pred (bb) == m_switch_bb
270 && (!m_default_case_nonstandard
271 || empty_block_p (bb))))
273 tree reloc, val;
274 const char *reason = NULL;
276 val = gimple_phi_arg_def (phi, i);
277 if (!is_gimple_ip_invariant (val))
278 reason = "non-invariant value from a case";
279 else
281 reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
282 if ((flag_pic && reloc != null_pointer_node)
283 || (!flag_pic && reloc == NULL_TREE))
285 if (reloc)
286 reason
287 = "value from a case would need runtime relocations";
288 else
289 reason
290 = "value from a case is not a valid initializer";
293 if (reason)
295 /* For contiguous range, we can allow non-constant
296 or one that needs relocation, as long as it is
297 only reachable from the default case. */
298 if (bb == m_switch_bb)
299 bb = m_final_bb;
300 if (!m_contiguous_range || bb != m_default_bb)
302 m_reason = reason;
303 return false;
306 unsigned int branch_num = gimple_switch_num_labels (m_switch);
307 for (unsigned int i = 1; i < branch_num; i++)
309 tree lab = CASE_LABEL (gimple_switch_label (m_switch, i));
310 if (label_to_block (lab) == bb)
312 m_reason = reason;
313 return false;
316 m_default_case_nonstandard = true;
322 return true;
325 /* The following function allocates default_values, target_{in,out}_names and
326 constructors arrays. The last one is also populated with pointers to
327 vectors that will become constructors of new arrays. */
329 void
330 switch_conversion::create_temp_arrays ()
332 int i;
334 m_default_values = XCNEWVEC (tree, m_phi_count * 3);
335 /* ??? Macros do not support multi argument templates in their
336 argument list. We create a typedef to work around that problem. */
337 typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
338 m_constructors = XCNEWVEC (vec_constructor_elt_gc, m_phi_count);
339 m_target_inbound_names = m_default_values + m_phi_count;
340 m_target_outbound_names = m_target_inbound_names + m_phi_count;
341 for (i = 0; i < m_phi_count; i++)
342 vec_alloc (m_constructors[i], tree_to_uhwi (m_range_size) + 1);
345 /* Populate the array of default values in the order of phi nodes.
346 DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
347 if the range is non-contiguous or the default case has standard
348 structure, otherwise it is the first non-default case instead. */
350 void
351 switch_conversion::gather_default_values (tree default_case)
353 gphi_iterator gsi;
354 basic_block bb = label_to_block (CASE_LABEL (default_case));
355 edge e;
356 int i = 0;
358 gcc_assert (CASE_LOW (default_case) == NULL_TREE
359 || m_default_case_nonstandard);
361 if (bb == m_final_bb)
362 e = find_edge (m_switch_bb, bb);
363 else
364 e = single_succ_edge (bb);
366 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
368 gphi *phi = gsi.phi ();
369 if (virtual_operand_p (gimple_phi_result (phi)))
370 continue;
371 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
372 gcc_assert (val);
373 m_default_values[i++] = val;
377 /* The following function populates the vectors in the constructors array with
378 future contents of the static arrays. The vectors are populated in the
379 order of phi nodes. */
381 void
382 switch_conversion::build_constructors ()
384 unsigned i, branch_num = gimple_switch_num_labels (m_switch);
385 tree pos = m_range_min;
386 tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
388 for (i = 1; i < branch_num; i++)
390 tree cs = gimple_switch_label (m_switch, i);
391 basic_block bb = label_to_block (CASE_LABEL (cs));
392 edge e;
393 tree high;
394 gphi_iterator gsi;
395 int j;
397 if (bb == m_final_bb)
398 e = find_edge (m_switch_bb, bb);
399 else
400 e = single_succ_edge (bb);
401 gcc_assert (e);
403 while (tree_int_cst_lt (pos, CASE_LOW (cs)))
405 int k;
406 for (k = 0; k < m_phi_count; k++)
408 constructor_elt elt;
410 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
411 elt.value
412 = unshare_expr_without_location (m_default_values[k]);
413 m_constructors[k]->quick_push (elt);
416 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
418 gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
420 j = 0;
421 if (CASE_HIGH (cs))
422 high = CASE_HIGH (cs);
423 else
424 high = CASE_LOW (cs);
425 for (gsi = gsi_start_phis (m_final_bb);
426 !gsi_end_p (gsi); gsi_next (&gsi))
428 gphi *phi = gsi.phi ();
429 if (virtual_operand_p (gimple_phi_result (phi)))
430 continue;
431 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
432 tree low = CASE_LOW (cs);
433 pos = CASE_LOW (cs);
437 constructor_elt elt;
439 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
440 elt.value = unshare_expr_without_location (val);
441 m_constructors[j]->quick_push (elt);
443 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
444 } while (!tree_int_cst_lt (high, pos)
445 && tree_int_cst_lt (low, pos));
446 j++;
451 /* If all values in the constructor vector are the same, return the value.
452 Otherwise return NULL_TREE. Not supposed to be called for empty
453 vectors. */
455 tree
456 switch_conversion::contains_same_values_p (vec<constructor_elt, va_gc> *vec)
458 unsigned int i;
459 tree prev = NULL_TREE;
460 constructor_elt *elt;
462 FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
464 if (!prev)
465 prev = elt->value;
466 else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
467 return NULL_TREE;
469 return prev;
472 /* Return type which should be used for array elements, either TYPE's
473 main variant or, for integral types, some smaller integral type
474 that can still hold all the constants. */
476 tree
477 switch_conversion::array_value_type (tree type, int num)
479 unsigned int i, len = vec_safe_length (m_constructors[num]);
480 constructor_elt *elt;
481 int sign = 0;
482 tree smaller_type;
484 /* Types with alignments greater than their size can reach here, e.g. out of
485 SRA. We couldn't use these as an array component type so get back to the
486 main variant first, which, for our purposes, is fine for other types as
487 well. */
489 type = TYPE_MAIN_VARIANT (type);
491 if (!INTEGRAL_TYPE_P (type))
492 return type;
494 scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
495 scalar_int_mode mode = get_narrowest_mode (type_mode);
496 if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
497 return type;
499 if (len < (optimize_bb_for_size_p (gimple_bb (m_switch)) ? 2 : 32))
500 return type;
502 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
504 wide_int cst;
506 if (TREE_CODE (elt->value) != INTEGER_CST)
507 return type;
509 cst = wi::to_wide (elt->value);
510 while (1)
512 unsigned int prec = GET_MODE_BITSIZE (mode);
513 if (prec > HOST_BITS_PER_WIDE_INT)
514 return type;
516 if (sign >= 0 && cst == wi::zext (cst, prec))
518 if (sign == 0 && cst == wi::sext (cst, prec))
519 break;
520 sign = 1;
521 break;
523 if (sign <= 0 && cst == wi::sext (cst, prec))
525 sign = -1;
526 break;
529 if (sign == 1)
530 sign = 0;
532 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
533 || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
534 return type;
538 if (sign == 0)
539 sign = TYPE_UNSIGNED (type) ? 1 : -1;
540 smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
541 if (GET_MODE_SIZE (type_mode)
542 <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
543 return type;
545 return smaller_type;
548 /* Create an appropriate array type and declaration and assemble a static
549 array variable. Also create a load statement that initializes
550 the variable in question with a value from the static array. SWTCH is
551 the switch statement being converted, NUM is the index to
552 arrays of constructors, default values and target SSA names
553 for this particular array. ARR_INDEX_TYPE is the type of the index
554 of the new array, PHI is the phi node of the final BB that corresponds
555 to the value that will be loaded from the created array. TIDX
556 is an ssa name of a temporary variable holding the index for loads from the
557 new array. */
559 void
560 switch_conversion::build_one_array (int num, tree arr_index_type,
561 gphi *phi, tree tidx)
563 tree name, cst;
564 gimple *load;
565 gimple_stmt_iterator gsi = gsi_for_stmt (m_switch);
566 location_t loc = gimple_location (m_switch);
568 gcc_assert (m_default_values[num]);
570 name = copy_ssa_name (PHI_RESULT (phi));
571 m_target_inbound_names[num] = name;
573 cst = contains_same_values_p (m_constructors[num]);
574 if (cst)
575 load = gimple_build_assign (name, cst);
576 else
578 tree array_type, ctor, decl, value_type, fetch, default_type;
580 default_type = TREE_TYPE (m_default_values[num]);
581 value_type = array_value_type (default_type, num);
582 array_type = build_array_type (value_type, arr_index_type);
583 if (default_type != value_type)
585 unsigned int i;
586 constructor_elt *elt;
588 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
589 elt->value = fold_convert (value_type, elt->value);
591 ctor = build_constructor (array_type, m_constructors[num]);
592 TREE_CONSTANT (ctor) = true;
593 TREE_STATIC (ctor) = true;
595 decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
596 TREE_STATIC (decl) = 1;
597 DECL_INITIAL (decl) = ctor;
599 DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
600 DECL_ARTIFICIAL (decl) = 1;
601 DECL_IGNORED_P (decl) = 1;
602 TREE_CONSTANT (decl) = 1;
603 TREE_READONLY (decl) = 1;
604 DECL_IGNORED_P (decl) = 1;
605 if (offloading_function_p (cfun->decl))
606 DECL_ATTRIBUTES (decl)
607 = tree_cons (get_identifier ("omp declare target"), NULL_TREE,
608 NULL_TREE);
609 varpool_node::finalize_decl (decl);
611 fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
612 NULL_TREE);
613 if (default_type != value_type)
615 fetch = fold_convert (default_type, fetch);
616 fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
617 true, GSI_SAME_STMT);
619 load = gimple_build_assign (name, fetch);
622 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
623 update_stmt (load);
624 m_arr_ref_last = load;
627 /* Builds and initializes static arrays initialized with values gathered from
628 the switch statement. Also creates statements that load values from
629 them. */
631 void
632 switch_conversion::build_arrays ()
634 tree arr_index_type;
635 tree tidx, sub, utype;
636 gimple *stmt;
637 gimple_stmt_iterator gsi;
638 gphi_iterator gpi;
639 int i;
640 location_t loc = gimple_location (m_switch);
642 gsi = gsi_for_stmt (m_switch);
644 /* Make sure we do not generate arithmetics in a subrange. */
645 utype = TREE_TYPE (m_index_expr);
646 if (TREE_TYPE (utype))
647 utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
648 else
649 utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
651 arr_index_type = build_index_type (m_range_size);
652 tidx = make_ssa_name (utype);
653 sub = fold_build2_loc (loc, MINUS_EXPR, utype,
654 fold_convert_loc (loc, utype, m_index_expr),
655 fold_convert_loc (loc, utype, m_range_min));
656 sub = force_gimple_operand_gsi (&gsi, sub,
657 false, NULL, true, GSI_SAME_STMT);
658 stmt = gimple_build_assign (tidx, sub);
660 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
661 update_stmt (stmt);
662 m_arr_ref_first = stmt;
664 for (gpi = gsi_start_phis (m_final_bb), i = 0;
665 !gsi_end_p (gpi); gsi_next (&gpi))
667 gphi *phi = gpi.phi ();
668 if (!virtual_operand_p (gimple_phi_result (phi)))
669 build_one_array (i++, arr_index_type, phi, tidx);
670 else
672 edge e;
673 edge_iterator ei;
674 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
676 if (e->dest == m_final_bb)
677 break;
678 if (!m_default_case_nonstandard
679 || e->dest != m_default_bb)
681 e = single_succ_edge (e->dest);
682 break;
685 gcc_assert (e && e->dest == m_final_bb);
686 m_target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
691 /* Generates and appropriately inserts loads of default values at the position
692 given by GSI. Returns the last inserted statement. */
694 gassign *
695 switch_conversion::gen_def_assigns (gimple_stmt_iterator *gsi)
697 int i;
698 gassign *assign = NULL;
700 for (i = 0; i < m_phi_count; i++)
702 tree name = copy_ssa_name (m_target_inbound_names[i]);
703 m_target_outbound_names[i] = name;
704 assign = gimple_build_assign (name, m_default_values[i]);
705 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
706 update_stmt (assign);
708 return assign;
711 /* Deletes the unused bbs and edges that now contain the switch statement and
712 its empty branch bbs. BBD is the now dead BB containing
713 the original switch statement, FINAL is the last BB of the converted
714 switch statement (in terms of succession). */
716 void
717 switch_conversion::prune_bbs (basic_block bbd, basic_block final,
718 basic_block default_bb)
720 edge_iterator ei;
721 edge e;
723 for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
725 basic_block bb;
726 bb = e->dest;
727 remove_edge (e);
728 if (bb != final && bb != default_bb)
729 delete_basic_block (bb);
731 delete_basic_block (bbd);
734 /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
735 from the basic block loading values from an array and E2F from the basic
736 block loading default values. BBF is the last switch basic block (see the
737 bbf description in the comment below). */
739 void
740 switch_conversion::fix_phi_nodes (edge e1f, edge e2f, basic_block bbf)
742 gphi_iterator gsi;
743 int i;
745 for (gsi = gsi_start_phis (bbf), i = 0;
746 !gsi_end_p (gsi); gsi_next (&gsi))
748 gphi *phi = gsi.phi ();
749 tree inbound, outbound;
750 if (virtual_operand_p (gimple_phi_result (phi)))
751 inbound = outbound = m_target_vop;
752 else
754 inbound = m_target_inbound_names[i];
755 outbound = m_target_outbound_names[i++];
757 add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
758 if (!m_default_case_nonstandard)
759 add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
763 /* Creates a check whether the switch expression value actually falls into the
764 range given by all the cases. If it does not, the temporaries are loaded
765 with default values instead. */
767 void
768 switch_conversion::gen_inbound_check ()
770 tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
771 tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
772 tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
773 glabel *label1, *label2, *label3;
774 tree utype, tidx;
775 tree bound;
777 gcond *cond_stmt;
779 gassign *last_assign = NULL;
780 gimple_stmt_iterator gsi;
781 basic_block bb0, bb1, bb2, bbf, bbd;
782 edge e01 = NULL, e02, e21, e1d, e1f, e2f;
783 location_t loc = gimple_location (m_switch);
785 gcc_assert (m_default_values);
787 bb0 = gimple_bb (m_switch);
789 tidx = gimple_assign_lhs (m_arr_ref_first);
790 utype = TREE_TYPE (tidx);
792 /* (end of) block 0 */
793 gsi = gsi_for_stmt (m_arr_ref_first);
794 gsi_next (&gsi);
796 bound = fold_convert_loc (loc, utype, m_range_size);
797 cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
798 gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
799 update_stmt (cond_stmt);
801 /* block 2 */
802 if (!m_default_case_nonstandard)
804 label2 = gimple_build_label (label_decl2);
805 gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
806 last_assign = gen_def_assigns (&gsi);
809 /* block 1 */
810 label1 = gimple_build_label (label_decl1);
811 gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
813 /* block F */
814 gsi = gsi_start_bb (m_final_bb);
815 label3 = gimple_build_label (label_decl3);
816 gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
818 /* cfg fix */
819 e02 = split_block (bb0, cond_stmt);
820 bb2 = e02->dest;
822 if (m_default_case_nonstandard)
824 bb1 = bb2;
825 bb2 = m_default_bb;
826 e01 = e02;
827 e01->flags = EDGE_TRUE_VALUE;
828 e02 = make_edge (bb0, bb2, EDGE_FALSE_VALUE);
829 edge e_default = find_edge (bb1, bb2);
830 for (gphi_iterator gsi = gsi_start_phis (bb2);
831 !gsi_end_p (gsi); gsi_next (&gsi))
833 gphi *phi = gsi.phi ();
834 tree arg = PHI_ARG_DEF_FROM_EDGE (phi, e_default);
835 add_phi_arg (phi, arg, e02,
836 gimple_phi_arg_location_from_edge (phi, e_default));
838 /* Partially fix the dominator tree, if it is available. */
839 if (dom_info_available_p (CDI_DOMINATORS))
840 redirect_immediate_dominators (CDI_DOMINATORS, bb1, bb0);
842 else
844 e21 = split_block (bb2, last_assign);
845 bb1 = e21->dest;
846 remove_edge (e21);
849 e1d = split_block (bb1, m_arr_ref_last);
850 bbd = e1d->dest;
851 remove_edge (e1d);
853 /* Flags and profiles of the edge for in-range values. */
854 if (!m_default_case_nonstandard)
855 e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
856 e01->probability = m_default_prob.invert ();
858 /* Flags and profiles of the edge taking care of out-of-range values. */
859 e02->flags &= ~EDGE_FALLTHRU;
860 e02->flags |= EDGE_FALSE_VALUE;
861 e02->probability = m_default_prob;
863 bbf = m_final_bb;
865 e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
866 e1f->probability = profile_probability::always ();
868 if (m_default_case_nonstandard)
869 e2f = NULL;
870 else
872 e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
873 e2f->probability = profile_probability::always ();
876 /* frequencies of the new BBs */
877 bb1->count = e01->count ();
878 bb2->count = e02->count ();
879 if (!m_default_case_nonstandard)
880 bbf->count = e1f->count () + e2f->count ();
882 /* Tidy blocks that have become unreachable. */
883 prune_bbs (bbd, m_final_bb,
884 m_default_case_nonstandard ? m_default_bb : NULL);
886 /* Fixup the PHI nodes in bbF. */
887 fix_phi_nodes (e1f, e2f, bbf);
889 /* Fix the dominator tree, if it is available. */
890 if (dom_info_available_p (CDI_DOMINATORS))
892 vec<basic_block> bbs_to_fix_dom;
894 set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
895 if (!m_default_case_nonstandard)
896 set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
897 if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
898 /* If bbD was the immediate dominator ... */
899 set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
901 bbs_to_fix_dom.create (3 + (bb2 != bbf));
902 bbs_to_fix_dom.quick_push (bb0);
903 bbs_to_fix_dom.quick_push (bb1);
904 if (bb2 != bbf)
905 bbs_to_fix_dom.quick_push (bb2);
906 bbs_to_fix_dom.quick_push (bbf);
908 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
909 bbs_to_fix_dom.release ();
913 /* The following function is invoked on every switch statement (the current
914 one is given in SWTCH) and runs the individual phases of switch
915 conversion on it one after another until one fails or the conversion
916 is completed. On success, NULL is in m_reason, otherwise points
917 to a string with the reason why the conversion failed. */
919 void
920 switch_conversion::expand (gswitch *swtch)
922 /* Group case labels so that we get the right results from the heuristics
923 that decide on the code generation approach for this switch. */
924 m_cfg_altered |= group_case_labels_stmt (swtch);
926 /* If this switch is now a degenerate case with only a default label,
927 there is nothing left for us to do. */
928 if (gimple_switch_num_labels (swtch) < 2)
930 m_reason = "switch is a degenerate case";
931 return;
934 collect (swtch);
936 /* No error markers should reach here (they should be filtered out
937 during gimplification). */
938 gcc_checking_assert (TREE_TYPE (m_index_expr) != error_mark_node);
940 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
941 gcc_checking_assert (!TREE_CONSTANT (m_index_expr));
943 /* Prefer bit test if possible. */
944 if (tree_fits_uhwi_p (m_range_size)
945 && bit_test_cluster::can_be_handled (tree_to_uhwi (m_range_size), m_uniq)
946 && bit_test_cluster::is_beneficial (m_count, m_uniq))
948 m_reason = "expanding as bit test is preferable";
949 return;
952 if (m_uniq <= 2)
954 /* This will be expanded as a decision tree . */
955 m_reason = "expanding as jumps is preferable";
956 return;
959 /* If there is no common successor, we cannot do the transformation. */
960 if (!m_final_bb)
962 m_reason = "no common successor to all case label target blocks found";
963 return;
966 /* Check the case label values are within reasonable range: */
967 if (!check_range ())
969 gcc_assert (m_reason);
970 return;
973 /* For all the cases, see whether they are empty, the assignments they
974 represent constant and so on... */
975 if (!check_all_empty_except_final ())
977 gcc_assert (m_reason);
978 return;
980 if (!check_final_bb ())
982 gcc_assert (m_reason);
983 return;
986 /* At this point all checks have passed and we can proceed with the
987 transformation. */
989 create_temp_arrays ();
990 gather_default_values (m_default_case_nonstandard
991 ? gimple_switch_label (swtch, 1)
992 : gimple_switch_default_label (swtch));
993 build_constructors ();
995 build_arrays (); /* Build the static arrays and assignments. */
996 gen_inbound_check (); /* Build the bounds check. */
998 m_cfg_altered = true;
1001 /* Destructor. */
1003 switch_conversion::~switch_conversion ()
1005 XDELETEVEC (m_constructors);
1006 XDELETEVEC (m_default_values);
1009 /* Constructor. */
1011 group_cluster::group_cluster (vec<cluster *> &clusters,
1012 unsigned start, unsigned end)
1014 gcc_checking_assert (end - start + 1 >= 1);
1015 m_prob = profile_probability::never ();
1016 m_cases.create (end - start + 1);
1017 for (unsigned i = start; i <= end; i++)
1019 m_cases.quick_push (static_cast<simple_cluster *> (clusters[i]));
1020 m_prob += clusters[i]->m_prob;
1022 m_subtree_prob = m_prob;
1025 /* Destructor. */
1027 group_cluster::~group_cluster ()
1029 for (unsigned i = 0; i < m_cases.length (); i++)
1030 delete m_cases[i];
1032 m_cases.release ();
1035 /* Dump content of a cluster. */
1037 void
1038 group_cluster::dump (FILE *f, bool details)
1040 unsigned total_values = 0;
1041 for (unsigned i = 0; i < m_cases.length (); i++)
1042 total_values += m_cases[i]->get_range (m_cases[i]->get_low (),
1043 m_cases[i]->get_high ());
1045 unsigned comparison_count = 0;
1046 for (unsigned i = 0; i < m_cases.length (); i++)
1048 simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1049 comparison_count += sc->m_range_p ? 2 : 1;
1052 unsigned HOST_WIDE_INT range = get_range (get_low (), get_high ());
1053 fprintf (f, "%s", get_type () == JUMP_TABLE ? "JT" : "BT");
1055 if (details)
1056 fprintf (f, "(values:%d comparisons:%d range:" HOST_WIDE_INT_PRINT_DEC
1057 " density: %.2f%%)", total_values, comparison_count, range,
1058 100.0f * comparison_count / range);
1060 fprintf (f, ":");
1061 PRINT_CASE (f, get_low ());
1062 fprintf (f, "-");
1063 PRINT_CASE (f, get_high ());
1064 fprintf (f, " ");
1067 /* Emit GIMPLE code to handle the cluster. */
1069 void
1070 jump_table_cluster::emit (tree index_expr, tree,
1071 tree default_label_expr, basic_block default_bb)
1073 /* For jump table we just emit a new gswitch statement that will
1074 be latter lowered to jump table. */
1075 auto_vec <tree> labels;
1076 labels.create (m_cases.length ());
1078 make_edge (m_case_bb, default_bb, 0);
1079 for (unsigned i = 0; i < m_cases.length (); i++)
1081 labels.quick_push (unshare_expr (m_cases[i]->m_case_label_expr));
1082 make_edge (m_case_bb, m_cases[i]->m_case_bb, 0);
1085 gswitch *s = gimple_build_switch (index_expr,
1086 unshare_expr (default_label_expr), labels);
1087 gimple_stmt_iterator gsi = gsi_start_bb (m_case_bb);
1088 gsi_insert_after (&gsi, s, GSI_NEW_STMT);
1091 /* Find jump tables of given CLUSTERS, where all members of the vector
1092 are of type simple_cluster. New clusters are returned. */
1094 vec<cluster *>
1095 jump_table_cluster::find_jump_tables (vec<cluster *> &clusters)
1097 if (!is_enabled ())
1098 return clusters.copy ();
1100 unsigned l = clusters.length ();
1101 auto_vec<min_cluster_item> min;
1102 min.reserve (l + 1);
1104 min.quick_push (min_cluster_item (0, 0, 0));
1106 for (unsigned i = 1; i <= l; i++)
1108 /* Set minimal # of clusters with i-th item to infinite. */
1109 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1111 for (unsigned j = 0; j < i; j++)
1113 unsigned HOST_WIDE_INT s = min[j].m_non_jt_cases;
1114 if (i - j < case_values_threshold ())
1115 s += i - j;
1117 /* Prefer clusters with smaller number of numbers covered. */
1118 if ((min[j].m_count + 1 < min[i].m_count
1119 || (min[j].m_count + 1 == min[i].m_count
1120 && s < min[i].m_non_jt_cases))
1121 && can_be_handled (clusters, j, i - 1))
1122 min[i] = min_cluster_item (min[j].m_count + 1, j, s);
1125 gcc_checking_assert (min[i].m_count != INT_MAX);
1128 /* No result. */
1129 if (min[l].m_count == INT_MAX)
1130 return clusters.copy ();
1132 vec<cluster *> output;
1133 output.create (4);
1135 /* Find and build the clusters. */
1136 for (int end = l;;)
1138 int start = min[end].m_start;
1140 /* Do not allow clusters with small number of cases. */
1141 if (is_beneficial (clusters, start, end - 1))
1142 output.safe_push (new jump_table_cluster (clusters, start, end - 1));
1143 else
1144 for (int i = end - 1; i >= start; i--)
1145 output.safe_push (clusters[i]);
1147 end = start;
1149 if (start <= 0)
1150 break;
1153 output.reverse ();
1154 return output;
1157 /* Return true when cluster starting at START and ending at END (inclusive)
1158 can build a jump-table. */
1160 bool
1161 jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1162 unsigned start, unsigned end)
1164 /* If the switch is relatively small such that the cost of one
1165 indirect jump on the target are higher than the cost of a
1166 decision tree, go with the decision tree.
1168 If range of values is much bigger than number of values,
1169 or if it is too large to represent in a HOST_WIDE_INT,
1170 make a sequence of conditional branches instead of a dispatch.
1172 The definition of "much bigger" depends on whether we are
1173 optimizing for size or for speed. */
1174 if (!flag_jump_tables)
1175 return false;
1177 /* For algorithm correctness, jump table for a single case must return
1178 true. We bail out in is_beneficial if it's called just for
1179 a single case. */
1180 if (start == end)
1181 return true;
1183 unsigned HOST_WIDE_INT max_ratio
1184 = optimize_insn_for_size_p () ? max_ratio_for_size : max_ratio_for_speed;
1185 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1186 clusters[end]->get_high ());
1187 /* Check overflow. */
1188 if (range == 0)
1189 return false;
1191 unsigned HOST_WIDE_INT comparison_count = 0;
1192 for (unsigned i = start; i <= end; i++)
1194 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1195 comparison_count += sc->m_range_p ? 2 : 1;
1198 return range <= max_ratio * comparison_count;
1201 /* Return true if cluster starting at START and ending at END (inclusive)
1202 is profitable transformation. */
1204 bool
1205 jump_table_cluster::is_beneficial (const vec<cluster *> &,
1206 unsigned start, unsigned end)
1208 /* Single case bail out. */
1209 if (start == end)
1210 return false;
1212 return end - start + 1 >= case_values_threshold ();
1215 /* Definition of jump_table_cluster constants. */
1217 const unsigned HOST_WIDE_INT jump_table_cluster::max_ratio_for_size;
1218 const unsigned HOST_WIDE_INT jump_table_cluster::max_ratio_for_speed;
1220 /* Find bit tests of given CLUSTERS, where all members of the vector
1221 are of type simple_cluster. New clusters are returned. */
1223 vec<cluster *>
1224 bit_test_cluster::find_bit_tests (vec<cluster *> &clusters)
1226 vec<cluster *> output;
1227 output.create (4);
1229 unsigned l = clusters.length ();
1230 auto_vec<min_cluster_item> min;
1231 min.reserve (l + 1);
1233 min.quick_push (min_cluster_item (0, 0, 0));
1235 for (unsigned i = 1; i <= l; i++)
1237 /* Set minimal # of clusters with i-th item to infinite. */
1238 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1240 for (unsigned j = 0; j < i; j++)
1242 if (min[j].m_count + 1 < min[i].m_count
1243 && can_be_handled (clusters, j, i - 1))
1244 min[i] = min_cluster_item (min[j].m_count + 1, j, INT_MAX);
1247 gcc_checking_assert (min[i].m_count != INT_MAX);
1250 /* No result. */
1251 if (min[l].m_count == INT_MAX)
1252 return clusters.copy ();
1254 /* Find and build the clusters. */
1255 for (int end = l;;)
1257 int start = min[end].m_start;
1259 if (is_beneficial (clusters, start, end - 1))
1260 output.safe_push (new bit_test_cluster (clusters, start, end - 1));
1261 else
1262 for (int i = end - 1; i >= start; i--)
1263 output.safe_push (clusters[i]);
1265 end = start;
1267 if (start <= 0)
1268 break;
1271 output.reverse ();
1272 return output;
1275 /* Return true when RANGE of case values with UNIQ labels
1276 can build a bit test. */
1278 bool
1279 bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1280 unsigned int uniq)
1282 /* Check overflow. */
1283 if (range == 0)
1284 return 0;
1286 if (range >= GET_MODE_BITSIZE (word_mode))
1287 return false;
1289 return uniq <= 3;
1292 /* Return true when cluster starting at START and ending at END (inclusive)
1293 can build a bit test. */
1295 bool
1296 bit_test_cluster::can_be_handled (const vec<cluster *> &clusters,
1297 unsigned start, unsigned end)
1299 /* For algorithm correctness, bit test for a single case must return
1300 true. We bail out in is_beneficial if it's called just for
1301 a single case. */
1302 if (start == end)
1303 return true;
1305 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1306 clusters[end]->get_high ());
1307 auto_bitmap dest_bbs;
1309 for (unsigned i = start; i <= end; i++)
1311 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1312 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
1315 return can_be_handled (range, bitmap_count_bits (dest_bbs));
1318 /* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1319 transformation. */
1321 bool
1322 bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
1324 return (((uniq == 1 && count >= 3)
1325 || (uniq == 2 && count >= 5)
1326 || (uniq == 3 && count >= 6)));
1329 /* Return true if cluster starting at START and ending at END (inclusive)
1330 is profitable transformation. */
1332 bool
1333 bit_test_cluster::is_beneficial (const vec<cluster *> &clusters,
1334 unsigned start, unsigned end)
1336 /* Single case bail out. */
1337 if (start == end)
1338 return false;
1340 auto_bitmap dest_bbs;
1342 for (unsigned i = start; i <= end; i++)
1344 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1345 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
1348 unsigned uniq = bitmap_count_bits (dest_bbs);
1349 unsigned count = end - start + 1;
1350 return is_beneficial (count, uniq);
1353 /* Comparison function for qsort to order bit tests by decreasing
1354 probability of execution. */
1357 case_bit_test::cmp (const void *p1, const void *p2)
1359 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
1360 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
1362 if (d2->bits != d1->bits)
1363 return d2->bits - d1->bits;
1365 /* Stabilize the sort. */
1366 return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1367 - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1370 /* Expand a switch statement by a short sequence of bit-wise
1371 comparisons. "switch(x)" is effectively converted into
1372 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1373 integer constants.
1375 INDEX_EXPR is the value being switched on.
1377 MINVAL is the lowest case value of in the case nodes,
1378 and RANGE is highest value minus MINVAL. MINVAL and RANGE
1379 are not guaranteed to be of the same type as INDEX_EXPR
1380 (the gimplifier doesn't change the type of case label values,
1381 and MINVAL and RANGE are derived from those values).
1382 MAXVAL is MINVAL + RANGE.
1384 There *MUST* be max_case_bit_tests or less unique case
1385 node targets. */
1387 void
1388 bit_test_cluster::emit (tree index_expr, tree index_type,
1389 tree, basic_block default_bb)
1391 struct case_bit_test test[m_max_case_bit_tests] = { {} };
1392 unsigned int i, j, k;
1393 unsigned int count;
1395 tree unsigned_index_type = unsigned_type_for (index_type);
1397 gimple_stmt_iterator gsi;
1398 gassign *shift_stmt;
1400 tree idx, tmp, csui;
1401 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1402 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1403 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1404 int prec = TYPE_PRECISION (word_type_node);
1405 wide_int wone = wi::one (prec);
1407 tree minval = get_low ();
1408 tree maxval = get_high ();
1409 tree range = int_const_binop (MINUS_EXPR, maxval, minval);
1411 /* Go through all case labels, and collect the case labels, profile
1412 counts, and other information we need to build the branch tests. */
1413 count = 0;
1414 for (i = 0; i < m_cases.length (); i++)
1416 unsigned int lo, hi;
1417 simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
1418 for (k = 0; k < count; k++)
1419 if (n->m_case_bb == test[k].target_bb)
1420 break;
1422 if (k == count)
1424 gcc_checking_assert (count < m_max_case_bit_tests);
1425 test[k].mask = wi::zero (prec);
1426 test[k].target_bb = n->m_case_bb;
1427 test[k].label = n->m_case_label_expr;
1428 test[k].bits = 1;
1429 count++;
1431 else
1432 test[k].bits++;
1434 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
1435 if (n->get_high () == NULL_TREE)
1436 hi = lo;
1437 else
1438 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
1439 minval));
1441 for (j = lo; j <= hi; j++)
1442 test[k].mask |= wi::lshift (wone, j);
1445 qsort (test, count, sizeof (*test), case_bit_test::cmp);
1447 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
1448 the minval subtractions, but it might make the mask constants more
1449 expensive. So, compare the costs. */
1450 if (compare_tree_int (minval, 0) > 0
1451 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
1453 int cost_diff;
1454 HOST_WIDE_INT m = tree_to_uhwi (minval);
1455 rtx reg = gen_raw_REG (word_mode, 10000);
1456 bool speed_p = optimize_insn_for_speed_p ();
1457 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
1458 GEN_INT (-m)), speed_p);
1459 for (i = 0; i < count; i++)
1461 rtx r = immed_wide_int_const (test[i].mask, word_mode);
1462 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
1463 word_mode, speed_p);
1464 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
1465 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
1466 word_mode, speed_p);
1468 if (cost_diff > 0)
1470 for (i = 0; i < count; i++)
1471 test[i].mask = wi::lshift (test[i].mask, m);
1472 minval = build_zero_cst (TREE_TYPE (minval));
1473 range = maxval;
1477 /* Now build the test-and-branch code. */
1479 gsi = gsi_last_bb (m_case_bb);
1481 /* idx = (unsigned)x - minval. */
1482 idx = fold_convert (unsigned_index_type, index_expr);
1483 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
1484 fold_convert (unsigned_index_type, minval));
1485 idx = force_gimple_operand_gsi (&gsi, idx,
1486 /*simple=*/true, NULL_TREE,
1487 /*before=*/true, GSI_SAME_STMT);
1489 /* if (idx > range) goto default */
1490 range = force_gimple_operand_gsi (&gsi,
1491 fold_convert (unsigned_index_type, range),
1492 /*simple=*/true, NULL_TREE,
1493 /*before=*/true, GSI_SAME_STMT);
1494 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
1495 basic_block new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb);
1496 gsi = gsi_last_bb (new_bb);
1498 /* csui = (1 << (word_mode) idx) */
1499 csui = make_ssa_name (word_type_node);
1500 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
1501 fold_convert (word_type_node, idx));
1502 tmp = force_gimple_operand_gsi (&gsi, tmp,
1503 /*simple=*/false, NULL_TREE,
1504 /*before=*/true, GSI_SAME_STMT);
1505 shift_stmt = gimple_build_assign (csui, tmp);
1506 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
1507 update_stmt (shift_stmt);
1509 /* for each unique set of cases:
1510 if (const & csui) goto target */
1511 for (k = 0; k < count; k++)
1513 tmp = wide_int_to_tree (word_type_node, test[k].mask);
1514 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
1515 tmp = force_gimple_operand_gsi (&gsi, tmp,
1516 /*simple=*/true, NULL_TREE,
1517 /*before=*/true, GSI_SAME_STMT);
1518 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
1519 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb);
1520 gsi = gsi_last_bb (new_bb);
1523 /* We should have removed all edges now. */
1524 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
1526 /* If nothing matched, go to the default label. */
1527 make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
1530 /* Split the basic block at the statement pointed to by GSIP, and insert
1531 a branch to the target basic block of E_TRUE conditional on tree
1532 expression COND.
1534 It is assumed that there is already an edge from the to-be-split
1535 basic block to E_TRUE->dest block. This edge is removed, and the
1536 profile information on the edge is re-used for the new conditional
1537 jump.
1539 The CFG is updated. The dominator tree will not be valid after
1540 this transformation, but the immediate dominators are updated if
1541 UPDATE_DOMINATORS is true.
1543 Returns the newly created basic block. */
1545 basic_block
1546 bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
1547 tree cond, basic_block case_bb)
1549 tree tmp;
1550 gcond *cond_stmt;
1551 edge e_false;
1552 basic_block new_bb, split_bb = gsi_bb (*gsip);
1554 edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
1555 gcc_assert (e_true->src == split_bb);
1557 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
1558 /*before=*/true, GSI_SAME_STMT);
1559 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
1560 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
1562 e_false = split_block (split_bb, cond_stmt);
1563 new_bb = e_false->dest;
1564 redirect_edge_pred (e_true, split_bb);
1566 e_false->flags &= ~EDGE_FALLTHRU;
1567 e_false->flags |= EDGE_FALSE_VALUE;
1568 e_false->probability = e_true->probability.invert ();
1569 new_bb->count = e_false->count ();
1571 return new_bb;
1574 /* Compute the number of case labels that correspond to each outgoing edge of
1575 switch statement. Record this information in the aux field of the edge. */
1577 void
1578 switch_decision_tree::compute_cases_per_edge ()
1580 basic_block bb = gimple_bb (m_switch);
1581 reset_out_edges_aux ();
1582 int ncases = gimple_switch_num_labels (m_switch);
1583 for (int i = ncases - 1; i >= 1; --i)
1585 tree elt = gimple_switch_label (m_switch, i);
1586 tree lab = CASE_LABEL (elt);
1587 basic_block case_bb = label_to_block_fn (cfun, lab);
1588 edge case_edge = find_edge (bb, case_bb);
1589 case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
1593 /* Analyze switch statement and return true when the statement is expanded
1594 as decision tree. */
1596 bool
1597 switch_decision_tree::analyze_switch_statement ()
1599 unsigned l = gimple_switch_num_labels (m_switch);
1600 basic_block bb = gimple_bb (m_switch);
1601 auto_vec<cluster *> clusters;
1602 clusters.create (l - 1);
1604 tree default_label = CASE_LABEL (gimple_switch_default_label (m_switch));
1605 basic_block default_bb = label_to_block_fn (cfun, default_label);
1606 m_case_bbs.reserve (l);
1607 m_case_bbs.quick_push (default_bb);
1609 compute_cases_per_edge ();
1611 for (unsigned i = 1; i < l; i++)
1613 tree elt = gimple_switch_label (m_switch, i);
1614 tree lab = CASE_LABEL (elt);
1615 basic_block case_bb = label_to_block_fn (cfun, lab);
1616 edge case_edge = find_edge (bb, case_bb);
1617 tree low = CASE_LOW (elt);
1618 tree high = CASE_HIGH (elt);
1620 profile_probability p
1621 = case_edge->probability.apply_scale (1, (intptr_t) (case_edge->aux));
1622 clusters.quick_push (new simple_cluster (low, high, elt, case_bb, p));
1623 m_case_bbs.quick_push (case_bb);
1626 reset_out_edges_aux ();
1628 /* Find jump table clusters. */
1629 vec<cluster *> output = jump_table_cluster::find_jump_tables (clusters);
1631 /* Find bit test clusters. */
1632 vec<cluster *> output2;
1633 auto_vec<cluster *> tmp;
1634 output2.create (1);
1635 tmp.create (1);
1637 for (unsigned i = 0; i < output.length (); i++)
1639 cluster *c = output[i];
1640 if (c->get_type () != SIMPLE_CASE)
1642 if (!tmp.is_empty ())
1644 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1645 output2.safe_splice (n);
1646 n.release ();
1647 tmp.truncate (0);
1649 output2.safe_push (c);
1651 else
1652 tmp.safe_push (c);
1655 /* We still can have a temporary vector to test. */
1656 if (!tmp.is_empty ())
1658 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1659 output2.safe_splice (n);
1660 n.release ();
1663 if (dump_file)
1665 fprintf (dump_file, ";; GIMPLE switch case clusters: ");
1666 for (unsigned i = 0; i < output2.length (); i++)
1667 output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
1668 fprintf (dump_file, "\n");
1671 output.release ();
1673 bool expanded = try_switch_expansion (output2);
1675 for (unsigned i = 0; i < output2.length (); i++)
1676 delete output2[i];
1678 output2.release ();
1680 return expanded;
1683 /* Attempt to expand CLUSTERS as a decision tree. Return true when
1684 expanded. */
1686 bool
1687 switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
1689 tree index_expr = gimple_switch_index (m_switch);
1690 tree index_type = TREE_TYPE (index_expr);
1691 basic_block bb = gimple_bb (m_switch);
1693 if (gimple_switch_num_labels (m_switch) == 1)
1694 return false;
1696 /* Find the default case target label. */
1697 tree default_label_expr = CASE_LABEL (gimple_switch_default_label (m_switch));
1698 m_default_bb = label_to_block_fn (cfun, default_label_expr);
1699 edge default_edge = find_edge (bb, m_default_bb);
1701 /* Do the insertion of a case label into m_case_list. The labels are
1702 fed to us in descending order from the sorted vector of case labels used
1703 in the tree part of the middle end. So the list we construct is
1704 sorted in ascending order. */
1706 for (int i = clusters.length () - 1; i >= 0; i--)
1708 case_tree_node *r = m_case_list;
1709 m_case_list = m_case_node_pool.allocate ();
1710 m_case_list->m_right = r;
1711 m_case_list->m_c = clusters[i];
1714 record_phi_operand_mapping ();
1716 /* Split basic block that contains the gswitch statement. */
1717 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1718 edge e;
1719 if (gsi_end_p (gsi))
1720 e = split_block_after_labels (bb);
1721 else
1723 gsi_prev (&gsi);
1724 e = split_block (bb, gsi_stmt (gsi));
1726 bb = split_edge (e);
1728 /* Create new basic blocks for non-case clusters where specific expansion
1729 needs to happen. */
1730 for (unsigned i = 0; i < clusters.length (); i++)
1731 if (clusters[i]->get_type () != SIMPLE_CASE)
1733 clusters[i]->m_case_bb = create_empty_bb (bb);
1734 clusters[i]->m_case_bb->loop_father = bb->loop_father;
1737 /* Do not do an extra work for a single cluster. */
1738 if (clusters.length () == 1
1739 && clusters[0]->get_type () != SIMPLE_CASE)
1741 cluster *c = clusters[0];
1742 c->emit (index_expr, index_type,
1743 gimple_switch_default_label (m_switch), m_default_bb);
1744 redirect_edge_succ (single_succ_edge (bb), c->m_case_bb);
1746 else
1748 emit (bb, index_expr, default_edge->probability, index_type);
1750 /* Emit cluster-specific switch handling. */
1751 for (unsigned i = 0; i < clusters.length (); i++)
1752 if (clusters[i]->get_type () != SIMPLE_CASE)
1753 clusters[i]->emit (index_expr, index_type,
1754 gimple_switch_default_label (m_switch),
1755 m_default_bb);
1758 fix_phi_operands_for_edges ();
1760 return true;
1763 /* Before switch transformation, record all SSA_NAMEs defined in switch BB
1764 and used in a label basic block. */
1766 void
1767 switch_decision_tree::record_phi_operand_mapping ()
1769 basic_block switch_bb = gimple_bb (m_switch);
1770 /* Record all PHI nodes that have to be fixed after conversion. */
1771 for (unsigned i = 0; i < m_case_bbs.length (); i++)
1773 gphi_iterator gsi;
1774 basic_block bb = m_case_bbs[i];
1775 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1777 gphi *phi = gsi.phi ();
1779 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
1781 basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
1782 if (phi_src_bb == switch_bb)
1784 tree def = gimple_phi_arg_def (phi, i);
1785 tree result = gimple_phi_result (phi);
1786 m_phi_mapping.put (result, def);
1787 break;
1794 /* Append new operands to PHI statements that were introduced due to
1795 addition of new edges to case labels. */
1797 void
1798 switch_decision_tree::fix_phi_operands_for_edges ()
1800 gphi_iterator gsi;
1802 for (unsigned i = 0; i < m_case_bbs.length (); i++)
1804 basic_block bb = m_case_bbs[i];
1805 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1807 gphi *phi = gsi.phi ();
1808 for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
1810 tree def = gimple_phi_arg_def (phi, j);
1811 if (def == NULL_TREE)
1813 edge e = gimple_phi_arg_edge (phi, j);
1814 tree *definition
1815 = m_phi_mapping.get (gimple_phi_result (phi));
1816 gcc_assert (definition);
1817 add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
1824 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1825 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1827 We generate a binary decision tree to select the appropriate target
1828 code. */
1830 void
1831 switch_decision_tree::emit (basic_block bb, tree index_expr,
1832 profile_probability default_prob, tree index_type)
1834 balance_case_nodes (&m_case_list, NULL);
1836 if (dump_file)
1837 dump_function_to_file (current_function_decl, dump_file, dump_flags);
1838 if (dump_file && (dump_flags & TDF_DETAILS))
1840 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1841 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1842 gcc_assert (m_case_list != NULL);
1843 dump_case_nodes (dump_file, m_case_list, indent_step, 0);
1846 bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type);
1848 if (bb)
1849 emit_jump (bb, m_default_bb);
1851 /* Remove all edges and do just an edge that will reach default_bb. */
1852 bb = gimple_bb (m_switch);
1853 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1854 gsi_remove (&gsi, true);
1856 delete_basic_block (bb);
1859 /* Take an ordered list of case nodes
1860 and transform them into a near optimal binary tree,
1861 on the assumption that any target code selection value is as
1862 likely as any other.
1864 The transformation is performed by splitting the ordered
1865 list into two equal sections plus a pivot. The parts are
1866 then attached to the pivot as left and right branches. Each
1867 branch is then transformed recursively. */
1869 void
1870 switch_decision_tree::balance_case_nodes (case_tree_node **head,
1871 case_tree_node *parent)
1873 case_tree_node *np;
1875 np = *head;
1876 if (np)
1878 int i = 0;
1879 int ranges = 0;
1880 case_tree_node **npp;
1881 case_tree_node *left;
1883 /* Count the number of entries on branch. Also count the ranges. */
1885 while (np)
1887 if (!tree_int_cst_equal (np->m_c->get_low (), np->m_c->get_high ()))
1888 ranges++;
1890 i++;
1891 np = np->m_right;
1894 if (i > 2)
1896 /* Split this list if it is long enough for that to help. */
1897 npp = head;
1898 left = *npp;
1900 /* If there are just three nodes, split at the middle one. */
1901 if (i == 3)
1902 npp = &(*npp)->m_right;
1903 else
1905 /* Find the place in the list that bisects the list's total cost,
1906 where ranges count as 2.
1907 Here I gets half the total cost. */
1908 i = (i + ranges + 1) / 2;
1909 while (1)
1911 /* Skip nodes while their cost does not reach that amount. */
1912 if (!tree_int_cst_equal ((*npp)->m_c->get_low (),
1913 (*npp)->m_c->get_high ()))
1914 i--;
1915 i--;
1916 if (i <= 0)
1917 break;
1918 npp = &(*npp)->m_right;
1921 *head = np = *npp;
1922 *npp = 0;
1923 np->m_parent = parent;
1924 np->m_left = left;
1926 /* Optimize each of the two split parts. */
1927 balance_case_nodes (&np->m_left, np);
1928 balance_case_nodes (&np->m_right, np);
1929 np->m_c->m_subtree_prob = np->m_c->m_prob;
1930 np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
1931 np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1933 else
1935 /* Else leave this branch as one level,
1936 but fill in `parent' fields. */
1937 np = *head;
1938 np->m_parent = parent;
1939 np->m_c->m_subtree_prob = np->m_c->m_prob;
1940 for (; np->m_right; np = np->m_right)
1942 np->m_right->m_parent = np;
1943 (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1949 /* Dump ROOT, a list or tree of case nodes, to file. */
1951 void
1952 switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
1953 int indent_step, int indent_level)
1955 if (root == 0)
1956 return;
1957 indent_level++;
1959 dump_case_nodes (f, root->m_left, indent_step, indent_level);
1961 fputs (";; ", f);
1962 fprintf (f, "%*s", indent_step * indent_level, "");
1963 root->m_c->dump (f);
1964 root->m_c->m_prob.dump (f);
1965 fputs ("\n", f);
1967 dump_case_nodes (f, root->m_right, indent_step, indent_level);
1971 /* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1973 void
1974 switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
1976 edge e = single_succ_edge (bb);
1977 redirect_edge_succ (e, case_bb);
1980 /* Generate code to compare OP0 with OP1 so that the condition codes are
1981 set and to jump to LABEL_BB if the condition is true.
1982 COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
1983 PROB is the probability of jumping to LABEL_BB. */
1985 basic_block
1986 switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
1987 tree op1, tree_code comparison,
1988 basic_block label_bb,
1989 profile_probability prob)
1991 // TODO: it's once called with lhs != index.
1992 op1 = fold_convert (TREE_TYPE (op0), op1);
1994 gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
1995 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1996 gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
1998 gcc_assert (single_succ_p (bb));
2000 /* Make a new basic block where false branch will take place. */
2001 edge false_edge = split_block (bb, cond);
2002 false_edge->flags = EDGE_FALSE_VALUE;
2003 false_edge->probability = prob.invert ();
2005 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2006 true_edge->probability = prob;
2008 return false_edge->dest;
2011 /* Emit step-by-step code to select a case for the value of INDEX.
2012 The thus generated decision tree follows the form of the
2013 case-node binary tree NODE, whose nodes represent test conditions.
2014 DEFAULT_PROB is probability of cases leading to default BB.
2015 INDEX_TYPE is the type of the index of the switch. */
2017 basic_block
2018 switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
2019 case_tree_node *node,
2020 profile_probability default_prob,
2021 tree index_type)
2023 /* If node is null, we are done. */
2024 if (node == NULL)
2025 return bb;
2027 /* Branch to a label where we will handle it later. */
2028 basic_block test_bb = split_edge (single_succ_edge (bb));
2029 redirect_edge_succ (single_pred_edge (test_bb),
2030 single_succ_edge (bb)->dest);
2032 profile_probability probability
2033 = (node->m_right
2034 ? node->m_right->m_c->m_subtree_prob : profile_probability::never ());
2035 probability = ((probability + default_prob.apply_scale (1, 2))
2036 / (node->m_c->m_subtree_prob + default_prob));
2037 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (), GT_EXPR,
2038 test_bb, probability);
2039 default_prob = default_prob.apply_scale (1, 2);
2041 /* Value belongs to this node or to the left-hand subtree. */
2042 probability = node->m_c->m_prob /
2043 (node->m_c->m_subtree_prob + default_prob);
2044 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (), GE_EXPR,
2045 node->m_c->m_case_bb, probability);
2047 /* Handle the left-hand subtree. */
2048 bb = emit_case_nodes (bb, index, node->m_left,
2049 default_prob, index_type);
2051 /* If the left-hand subtree fell through,
2052 don't let it fall into the right-hand subtree. */
2053 if (m_default_bb)
2054 emit_jump (bb, m_default_bb);
2056 bb = emit_case_nodes (test_bb, index, node->m_right,
2057 default_prob, index_type);
2059 return bb;
2062 /* The main function of the pass scans statements for switches and invokes
2063 process_switch on them. */
2065 namespace {
2067 const pass_data pass_data_convert_switch =
2069 GIMPLE_PASS, /* type */
2070 "switchconv", /* name */
2071 OPTGROUP_NONE, /* optinfo_flags */
2072 TV_TREE_SWITCH_CONVERSION, /* tv_id */
2073 ( PROP_cfg | PROP_ssa ), /* properties_required */
2074 0, /* properties_provided */
2075 0, /* properties_destroyed */
2076 0, /* todo_flags_start */
2077 TODO_update_ssa, /* todo_flags_finish */
2080 class pass_convert_switch : public gimple_opt_pass
2082 public:
2083 pass_convert_switch (gcc::context *ctxt)
2084 : gimple_opt_pass (pass_data_convert_switch, ctxt)
2087 /* opt_pass methods: */
2088 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
2089 virtual unsigned int execute (function *);
2091 }; // class pass_convert_switch
2093 unsigned int
2094 pass_convert_switch::execute (function *fun)
2096 basic_block bb;
2097 bool cfg_altered = false;
2099 FOR_EACH_BB_FN (bb, fun)
2101 gimple *stmt = last_stmt (bb);
2102 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2104 if (dump_file)
2106 expanded_location loc = expand_location (gimple_location (stmt));
2108 fprintf (dump_file, "beginning to process the following "
2109 "SWITCH statement (%s:%d) : ------- \n",
2110 loc.file, loc.line);
2111 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2112 putc ('\n', dump_file);
2115 switch_conversion sconv;
2116 sconv.expand (as_a <gswitch *> (stmt));
2117 cfg_altered |= sconv.m_cfg_altered;
2118 if (!sconv.m_reason)
2120 if (dump_file)
2122 fputs ("Switch converted\n", dump_file);
2123 fputs ("--------------------------------\n", dump_file);
2126 /* Make no effort to update the post-dominator tree.
2127 It is actually not that hard for the transformations
2128 we have performed, but it is not supported
2129 by iterate_fix_dominators. */
2130 free_dominance_info (CDI_POST_DOMINATORS);
2132 else
2134 if (dump_file)
2136 fputs ("Bailing out - ", dump_file);
2137 fputs (sconv.m_reason, dump_file);
2138 fputs ("\n--------------------------------\n", dump_file);
2144 return cfg_altered ? TODO_cleanup_cfg : 0;;
2147 } // anon namespace
2149 gimple_opt_pass *
2150 make_pass_convert_switch (gcc::context *ctxt)
2152 return new pass_convert_switch (ctxt);
2155 /* The main function of the pass scans statements for switches and invokes
2156 process_switch on them. */
2158 namespace {
2160 template <bool O0> class pass_lower_switch: public gimple_opt_pass
2162 public:
2163 pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
2165 static const pass_data data;
2166 opt_pass *
2167 clone ()
2169 return new pass_lower_switch<O0> (m_ctxt);
2172 virtual bool
2173 gate (function *)
2175 return !O0 || !optimize;
2178 virtual unsigned int execute (function *fun);
2179 }; // class pass_lower_switch
2181 template <bool O0>
2182 const pass_data pass_lower_switch<O0>::data = {
2183 GIMPLE_PASS, /* type */
2184 O0 ? "switchlower_O0" : "switchlower", /* name */
2185 OPTGROUP_NONE, /* optinfo_flags */
2186 TV_TREE_SWITCH_LOWERING, /* tv_id */
2187 ( PROP_cfg | PROP_ssa ), /* properties_required */
2188 0, /* properties_provided */
2189 0, /* properties_destroyed */
2190 0, /* todo_flags_start */
2191 TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
2194 template <bool O0>
2195 unsigned int
2196 pass_lower_switch<O0>::execute (function *fun)
2198 basic_block bb;
2199 bool expanded = false;
2201 auto_vec<gimple *> switch_statements;
2202 switch_statements.create (1);
2204 FOR_EACH_BB_FN (bb, fun)
2206 gimple *stmt = last_stmt (bb);
2207 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2208 switch_statements.safe_push (stmt);
2211 for (unsigned i = 0; i < switch_statements.length (); i++)
2213 gimple *stmt = switch_statements[i];
2214 if (dump_file)
2216 expanded_location loc = expand_location (gimple_location (stmt));
2218 fprintf (dump_file, "beginning to process the following "
2219 "SWITCH statement (%s:%d) : ------- \n",
2220 loc.file, loc.line);
2221 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2222 putc ('\n', dump_file);
2225 gswitch *swtch = dyn_cast<gswitch *> (stmt);
2226 if (swtch)
2228 switch_decision_tree dt (swtch);
2229 expanded |= dt.analyze_switch_statement ();
2233 if (expanded)
2235 free_dominance_info (CDI_DOMINATORS);
2236 free_dominance_info (CDI_POST_DOMINATORS);
2237 mark_virtual_operands_for_renaming (cfun);
2240 return 0;
2243 } // anon namespace
2245 gimple_opt_pass *
2246 make_pass_lower_switch_O0 (gcc::context *ctxt)
2248 return new pass_lower_switch<true> (ctxt);
2250 gimple_opt_pass *
2251 make_pass_lower_switch (gcc::context *ctxt)
2253 return new pass_lower_switch<false> (ctxt);