]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/tree-switch-conversion.c
dumpfile.c: add indentation via DUMP_VECT_SCOPE
[thirdparty/gcc.git] / gcc / tree-switch-conversion.c
CommitLineData
531b10fc
SB
1/* Lower GIMPLE_SWITCH expressions to something more efficient than
2 a jump table.
85ec4feb 3 Copyright (C) 2006-2018 Free Software Foundation, Inc.
b6e99746
MJ
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 3, or (at your option) any
10later version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT
13ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not, write to the Free
19Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
2002110-1301, USA. */
21
531b10fc
SB
22/* This file handles the lowering of GIMPLE_SWITCH to an indexed
23 load, or a series of bit-test-and-branch expressions. */
24
25#include "config.h"
26#include "system.h"
27#include "coretypes.h"
c7131fb2 28#include "backend.h"
957060b5
AM
29#include "insn-codes.h"
30#include "rtl.h"
c7131fb2
AM
31#include "tree.h"
32#include "gimple.h"
957060b5
AM
33#include "cfghooks.h"
34#include "tree-pass.h"
c7131fb2 35#include "ssa.h"
957060b5
AM
36#include "optabs-tree.h"
37#include "cgraph.h"
38#include "gimple-pretty-print.h"
531b10fc 39#include "params.h"
40e23961 40#include "fold-const.h"
d8a2d370
DN
41#include "varasm.h"
42#include "stor-layout.h"
60393bbc 43#include "cfganal.h"
45b0be94 44#include "gimplify.h"
5be5c238 45#include "gimple-iterator.h"
18f429e2 46#include "gimplify-me.h"
442b4905 47#include "tree-cfg.h"
a9e0d843 48#include "cfgloop.h"
9dc3d6a9
ML
49#include "alloc-pool.h"
50#include "target.h"
51#include "tree-into-ssa.h"
46dbeb40 52#include "omp-general.h"
7ee2468b
SB
53
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? */
531b10fc
SB
56#include "langhooks.h"
57
789410e4 58#include "tree-switch-conversion.h"
531b10fc 59\f
789410e4 60using namespace tree_switch_conversion;
531b10fc 61
789410e4 62/* Constructor. */
531b10fc 63
789410e4
ML
64switch_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)
531b10fc 68{
531b10fc 69}
b6e99746 70
789410e4 71/* Collection information about SWTCH statement. */
886cd84f 72
789410e4
ML
73void
74switch_conversion::collect (gswitch *swtch)
b6e99746 75{
726a989a 76 unsigned int branch_num = gimple_switch_num_labels (swtch);
886cd84f 77 tree min_case, max_case;
789410e4 78 unsigned int i;
18bfe940 79 edge e, e_default, e_first;
886cd84f 80 edge_iterator ei;
18bfe940 81 basic_block first;
886cd84f 82
789410e4 83 m_switch = swtch;
b6e99746
MJ
84
85 /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
fd8d363e
SB
86 is a default label which is the first in the vector.
87 Collect the bits we can deduce from the CFG. */
789410e4
ML
88 m_index_expr = gimple_switch_index (swtch);
89 m_switch_bb = gimple_bb (swtch);
90 m_default_bb
18bfe940 91 = label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
789410e4
ML
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)
886cd84f 96 if (e != e_default)
789410e4 97 m_other_count += e->count ();
b6e99746 98
18bfe940
JJ
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);
102
789410e4 103 m_range_min = CASE_LOW (min_case);
18bfe940 104 if (CASE_HIGH (max_case) != NULL_TREE)
789410e4 105 m_range_max = CASE_HIGH (max_case);
18bfe940 106 else
789410e4 107 m_range_max = CASE_LOW (max_case);
18bfe940 108
789410e4
ML
109 m_contiguous_range = true;
110 tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : m_range_min;
18bfe940
JJ
111 for (i = 2; i < branch_num; i++)
112 {
113 tree elt = gimple_switch_label (swtch, i);
8e6cdc90 114 if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
18bfe940 115 {
789410e4 116 m_contiguous_range = false;
18bfe940
JJ
117 break;
118 }
119 last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
120 }
121
789410e4 122 if (m_contiguous_range)
18bfe940
JJ
123 {
124 first = label_to_block (CASE_LABEL (gimple_switch_label (swtch, 1)));
789410e4 125 e_first = find_edge (m_switch_bb, first);
18bfe940
JJ
126 }
127 else
128 {
789410e4 129 first = m_default_bb;
18bfe940
JJ
130 e_first = e_default;
131 }
132
886cd84f 133 /* See if there is one common successor block for all branch
866f20d6 134 targets. If it exists, record it in FINAL_BB.
18bfe940
JJ
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))
789410e4 139 m_final_bb = e_first->dest;
18bfe940
JJ
140 else if (single_succ_p (e_first->dest)
141 && ! single_pred_p (single_succ (e_first->dest)))
789410e4 142 m_final_bb = single_succ (e_first->dest);
866f20d6 143 /* Require that all switch destinations are either that common
18bfe940
JJ
144 FINAL_BB or a forwarder to it, except for the default
145 case if contiguous range. */
789410e4
ML
146 if (m_final_bb)
147 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
886cd84f 148 {
789410e4 149 if (e->dest == m_final_bb)
886cd84f
SB
150 continue;
151
152 if (single_pred_p (e->dest)
153 && single_succ_p (e->dest)
789410e4 154 && single_succ (e->dest) == m_final_bb)
886cd84f
SB
155 continue;
156
789410e4 157 if (e == e_default && m_contiguous_range)
18bfe940 158 {
789410e4 159 m_default_case_nonstandard = true;
18bfe940
JJ
160 continue;
161 }
162
789410e4 163 m_final_bb = NULL;
886cd84f
SB
164 break;
165 }
166
789410e4
ML
167 m_range_size
168 = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
b6e99746 169
886cd84f
SB
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. */
789410e4 173 m_count = 0;
886cd84f
SB
174 for (i = 1; i < branch_num; i++)
175 {
176 tree elt = gimple_switch_label (swtch, i);
789410e4 177 m_count++;
886cd84f
SB
178 if (CASE_HIGH (elt)
179 && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
789410e4 180 m_count++;
886cd84f 181 }
dc223ad4
ML
182
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;
886cd84f 187}
b6e99746 188
789410e4 189/* Checks whether the range given by individual case statements of the switch
886cd84f
SB
190 switch statement isn't too big and whether the number of branches actually
191 satisfies the size of the new array. */
b6e99746 192
789410e4
ML
193bool
194switch_conversion::check_range ()
886cd84f 195{
789410e4
ML
196 gcc_assert (m_range_size);
197 if (!tree_fits_uhwi_p (m_range_size))
b6e99746 198 {
789410e4 199 m_reason = "index range way too large or otherwise unusable";
b6e99746
MJ
200 return false;
201 }
202
789410e4
ML
203 if (tree_to_uhwi (m_range_size)
204 > ((unsigned) m_count * SWITCH_CONVERSION_BRANCH_RATIO))
b6e99746 205 {
789410e4 206 m_reason = "the maximum range-branch ratio exceeded";
b6e99746
MJ
207 return false;
208 }
209
210 return true;
211}
212
789410e4 213/* Checks whether all but the final BB basic blocks are empty. */
b6e99746 214
789410e4
ML
215bool
216switch_conversion::check_all_empty_except_final ()
b6e99746 217{
789410e4 218 edge e, e_default = find_edge (m_switch_bb, m_default_bb);
886cd84f 219 edge_iterator ei;
b6e99746 220
789410e4 221 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
b6e99746 222 {
789410e4 223 if (e->dest == m_final_bb)
886cd84f 224 continue;
b6e99746 225
886cd84f 226 if (!empty_block_p (e->dest))
b6e99746 227 {
789410e4 228 if (m_contiguous_range && e == e_default)
18bfe940 229 {
789410e4 230 m_default_case_nonstandard = true;
18bfe940
JJ
231 continue;
232 }
233
789410e4 234 m_reason = "bad case - a non-final BB not empty";
b6e99746
MJ
235 return false;
236 }
b6e99746
MJ
237 }
238
239 return true;
240}
241
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. */
246
789410e4
ML
247bool
248switch_conversion::check_final_bb ()
b6e99746 249{
538dd0b7 250 gphi_iterator gsi;
b6e99746 251
789410e4
ML
252 m_phi_count = 0;
253 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 254 {
538dd0b7 255 gphi *phi = gsi.phi ();
726a989a 256 unsigned int i;
b6e99746 257
18bfe940
JJ
258 if (virtual_operand_p (gimple_phi_result (phi)))
259 continue;
260
789410e4 261 m_phi_count++;
b6e99746 262
726a989a 263 for (i = 0; i < gimple_phi_num_args (phi); i++)
b6e99746 264 {
726a989a 265 basic_block bb = gimple_phi_arg_edge (phi, i)->src;
b6e99746 266
789410e4 267 if (bb == m_switch_bb
18bfe940 268 || (single_pred_p (bb)
789410e4
ML
269 && single_pred (bb) == m_switch_bb
270 && (!m_default_case_nonstandard
18bfe940 271 || empty_block_p (bb))))
b6e99746 272 {
f6e6e990 273 tree reloc, val;
18bfe940 274 const char *reason = NULL;
f6e6e990
JJ
275
276 val = gimple_phi_arg_def (phi, i);
277 if (!is_gimple_ip_invariant (val))
18bfe940
JJ
278 reason = "non-invariant value from a case";
279 else
f6e6e990 280 {
18bfe940
JJ
281 reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
282 if ((flag_pic && reloc != null_pointer_node)
283 || (!flag_pic && reloc == NULL_TREE))
284 {
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";
291 }
f6e6e990 292 }
18bfe940 293 if (reason)
f6e6e990 294 {
18bfe940
JJ
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. */
789410e4
ML
298 if (bb == m_switch_bb)
299 bb = m_final_bb;
300 if (!m_contiguous_range || bb != m_default_bb)
18bfe940 301 {
789410e4 302 m_reason = reason;
18bfe940
JJ
303 return false;
304 }
305
789410e4 306 unsigned int branch_num = gimple_switch_num_labels (m_switch);
18bfe940
JJ
307 for (unsigned int i = 1; i < branch_num; i++)
308 {
789410e4 309 tree lab = CASE_LABEL (gimple_switch_label (m_switch, i));
18bfe940
JJ
310 if (label_to_block (lab) == bb)
311 {
789410e4 312 m_reason = reason;
18bfe940
JJ
313 return false;
314 }
315 }
789410e4 316 m_default_case_nonstandard = true;
f6e6e990 317 }
b6e99746
MJ
318 }
319 }
320 }
321
322 return true;
323}
324
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. */
328
789410e4
ML
329void
330switch_conversion::create_temp_arrays ()
b6e99746
MJ
331{
332 int i;
333
789410e4 334 m_default_values = XCNEWVEC (tree, m_phi_count * 3);
9771b263
DN
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;
789410e4
ML
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);
b6e99746
MJ
343}
344
345/* Populate the array of default values in the order of phi nodes.
18bfe940
JJ
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. */
b6e99746 349
789410e4
ML
350void
351switch_conversion::gather_default_values (tree default_case)
b6e99746 352{
538dd0b7 353 gphi_iterator gsi;
b6e99746
MJ
354 basic_block bb = label_to_block (CASE_LABEL (default_case));
355 edge e;
726a989a 356 int i = 0;
b6e99746 357
18bfe940 358 gcc_assert (CASE_LOW (default_case) == NULL_TREE
789410e4 359 || m_default_case_nonstandard);
b6e99746 360
789410e4
ML
361 if (bb == m_final_bb)
362 e = find_edge (m_switch_bb, bb);
b6e99746
MJ
363 else
364 e = single_succ_edge (bb);
365
789410e4 366 for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 367 {
538dd0b7 368 gphi *phi = gsi.phi ();
18bfe940
JJ
369 if (virtual_operand_p (gimple_phi_result (phi)))
370 continue;
b6e99746
MJ
371 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
372 gcc_assert (val);
789410e4 373 m_default_values[i++] = val;
b6e99746
MJ
374 }
375}
376
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
789410e4 379 order of phi nodes. */
b6e99746 380
789410e4
ML
381void
382switch_conversion::build_constructors ()
b6e99746 383{
789410e4
ML
384 unsigned i, branch_num = gimple_switch_num_labels (m_switch);
385 tree pos = m_range_min;
18bfe940 386 tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
b6e99746 387
726a989a 388 for (i = 1; i < branch_num; i++)
b6e99746 389 {
789410e4 390 tree cs = gimple_switch_label (m_switch, i);
b6e99746
MJ
391 basic_block bb = label_to_block (CASE_LABEL (cs));
392 edge e;
726a989a 393 tree high;
538dd0b7 394 gphi_iterator gsi;
b6e99746
MJ
395 int j;
396
789410e4
ML
397 if (bb == m_final_bb)
398 e = find_edge (m_switch_bb, bb);
b6e99746
MJ
399 else
400 e = single_succ_edge (bb);
401 gcc_assert (e);
402
403 while (tree_int_cst_lt (pos, CASE_LOW (cs)))
404 {
405 int k;
789410e4 406 for (k = 0; k < m_phi_count; k++)
b6e99746 407 {
f32682ca 408 constructor_elt elt;
b6e99746 409
789410e4 410 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
d1f98542 411 elt.value
789410e4
ML
412 = unshare_expr_without_location (m_default_values[k]);
413 m_constructors[k]->quick_push (elt);
b6e99746
MJ
414 }
415
18bfe940 416 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
b6e99746 417 }
b1ae1681 418 gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
b6e99746
MJ
419
420 j = 0;
421 if (CASE_HIGH (cs))
422 high = CASE_HIGH (cs);
423 else
b1ae1681 424 high = CASE_LOW (cs);
789410e4 425 for (gsi = gsi_start_phis (m_final_bb);
726a989a 426 !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 427 {
538dd0b7 428 gphi *phi = gsi.phi ();
18bfe940
JJ
429 if (virtual_operand_p (gimple_phi_result (phi)))
430 continue;
b6e99746 431 tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
7f2a9982 432 tree low = CASE_LOW (cs);
b6e99746
MJ
433 pos = CASE_LOW (cs);
434
b8698a0f 435 do
b6e99746 436 {
f32682ca 437 constructor_elt elt;
b6e99746 438
789410e4 439 elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
d1f98542 440 elt.value = unshare_expr_without_location (val);
789410e4 441 m_constructors[j]->quick_push (elt);
b6e99746 442
18bfe940 443 pos = int_const_binop (PLUS_EXPR, pos, pos_one);
7156c8ab
MJ
444 } while (!tree_int_cst_lt (high, pos)
445 && tree_int_cst_lt (low, pos));
b6e99746
MJ
446 j++;
447 }
448 }
449}
450
7156c8ab
MJ
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. */
454
789410e4
ML
455tree
456switch_conversion::contains_same_values_p (vec<constructor_elt, va_gc> *vec)
7156c8ab 457{
8e97bc2b 458 unsigned int i;
7156c8ab 459 tree prev = NULL_TREE;
8e97bc2b 460 constructor_elt *elt;
7156c8ab 461
9771b263 462 FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
7156c8ab 463 {
7156c8ab
MJ
464 if (!prev)
465 prev = elt->value;
466 else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
467 return NULL_TREE;
468 }
469 return prev;
470}
471
f1b0632a
OH
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. */
8e97bc2b 475
789410e4
ML
476tree
477switch_conversion::array_value_type (tree type, int num)
8e97bc2b 478{
789410e4 479 unsigned int i, len = vec_safe_length (m_constructors[num]);
8e97bc2b 480 constructor_elt *elt;
8e97bc2b
JJ
481 int sign = 0;
482 tree smaller_type;
483
f1b0632a
OH
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. */
488
489 type = TYPE_MAIN_VARIANT (type);
490
8e97bc2b
JJ
491 if (!INTEGRAL_TYPE_P (type))
492 return type;
493
7a504f33 494 scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
095a2d76 495 scalar_int_mode mode = get_narrowest_mode (type_mode);
ec35d572 496 if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
8e97bc2b
JJ
497 return type;
498
789410e4 499 if (len < (optimize_bb_for_size_p (gimple_bb (m_switch)) ? 2 : 32))
8e97bc2b
JJ
500 return type;
501
789410e4 502 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
8e97bc2b 503 {
807e902e 504 wide_int cst;
8e97bc2b
JJ
505
506 if (TREE_CODE (elt->value) != INTEGER_CST)
507 return type;
508
8e6cdc90 509 cst = wi::to_wide (elt->value);
8e97bc2b
JJ
510 while (1)
511 {
512 unsigned int prec = GET_MODE_BITSIZE (mode);
513 if (prec > HOST_BITS_PER_WIDE_INT)
514 return type;
515
807e902e 516 if (sign >= 0 && cst == wi::zext (cst, prec))
8e97bc2b 517 {
807e902e 518 if (sign == 0 && cst == wi::sext (cst, prec))
8e97bc2b
JJ
519 break;
520 sign = 1;
521 break;
522 }
807e902e 523 if (sign <= 0 && cst == wi::sext (cst, prec))
8e97bc2b
JJ
524 {
525 sign = -1;
526 break;
527 }
528
529 if (sign == 1)
530 sign = 0;
531
490d0f6c 532 if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
ec35d572 533 || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
8e97bc2b
JJ
534 return type;
535 }
536 }
537
538 if (sign == 0)
539 sign = TYPE_UNSIGNED (type) ? 1 : -1;
540 smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
7a504f33
RS
541 if (GET_MODE_SIZE (type_mode)
542 <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
8e97bc2b
JJ
543 return type;
544
545 return smaller_type;
546}
547
789410e4
ML
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
7156c8ab
MJ
556 is an ssa name of a temporary variable holding the index for loads from the
557 new array. */
b6e99746 558
789410e4
ML
559void
560switch_conversion::build_one_array (int num, tree arr_index_type,
561 gphi *phi, tree tidx)
b6e99746 562{
7156c8ab 563 tree name, cst;
355fe088 564 gimple *load;
789410e4
ML
565 gimple_stmt_iterator gsi = gsi_for_stmt (m_switch);
566 location_t loc = gimple_location (m_switch);
b6e99746 567
789410e4 568 gcc_assert (m_default_values[num]);
b6e99746 569
b731b390 570 name = copy_ssa_name (PHI_RESULT (phi));
789410e4 571 m_target_inbound_names[num] = name;
b6e99746 572
789410e4 573 cst = contains_same_values_p (m_constructors[num]);
7156c8ab
MJ
574 if (cst)
575 load = gimple_build_assign (name, cst);
576 else
577 {
8e97bc2b 578 tree array_type, ctor, decl, value_type, fetch, default_type;
7156c8ab 579
789410e4
ML
580 default_type = TREE_TYPE (m_default_values[num]);
581 value_type = array_value_type (default_type, num);
7156c8ab 582 array_type = build_array_type (value_type, arr_index_type);
8e97bc2b
JJ
583 if (default_type != value_type)
584 {
585 unsigned int i;
586 constructor_elt *elt;
587
789410e4 588 FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
8e97bc2b
JJ
589 elt->value = fold_convert (value_type, elt->value);
590 }
789410e4 591 ctor = build_constructor (array_type, m_constructors[num]);
7156c8ab 592 TREE_CONSTANT (ctor) = true;
5f7ae6b6 593 TREE_STATIC (ctor) = true;
7156c8ab 594
c2255bc4 595 decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
7156c8ab
MJ
596 TREE_STATIC (decl) = 1;
597 DECL_INITIAL (decl) = ctor;
598
599 DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
600 DECL_ARTIFICIAL (decl) = 1;
f8d851c6 601 DECL_IGNORED_P (decl) = 1;
7156c8ab 602 TREE_CONSTANT (decl) = 1;
2e3b4885 603 TREE_READONLY (decl) = 1;
d7438551 604 DECL_IGNORED_P (decl) = 1;
46dbeb40
TV
605 if (offloading_function_p (cfun->decl))
606 DECL_ATTRIBUTES (decl)
607 = tree_cons (get_identifier ("omp declare target"), NULL_TREE,
608 NULL_TREE);
9041d2e6 609 varpool_node::finalize_decl (decl);
7156c8ab
MJ
610
611 fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
612 NULL_TREE);
8e97bc2b
JJ
613 if (default_type != value_type)
614 {
615 fetch = fold_convert (default_type, fetch);
616 fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
617 true, GSI_SAME_STMT);
618 }
7156c8ab
MJ
619 load = gimple_build_assign (name, fetch);
620 }
b6e99746 621
726a989a 622 gsi_insert_before (&gsi, load, GSI_SAME_STMT);
7156c8ab 623 update_stmt (load);
789410e4 624 m_arr_ref_last = load;
b6e99746
MJ
625}
626
627/* Builds and initializes static arrays initialized with values gathered from
789410e4 628 the switch statement. Also creates statements that load values from
b6e99746
MJ
629 them. */
630
789410e4
ML
631void
632switch_conversion::build_arrays ()
b6e99746
MJ
633{
634 tree arr_index_type;
83d5977e 635 tree tidx, sub, utype;
355fe088 636 gimple *stmt;
726a989a 637 gimple_stmt_iterator gsi;
538dd0b7 638 gphi_iterator gpi;
b6e99746 639 int i;
789410e4 640 location_t loc = gimple_location (m_switch);
b6e99746 641
789410e4 642 gsi = gsi_for_stmt (m_switch);
04e78aa9 643
edb9b69e 644 /* Make sure we do not generate arithmetics in a subrange. */
789410e4 645 utype = TREE_TYPE (m_index_expr);
edb9b69e
JJ
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);
650
789410e4 651 arr_index_type = build_index_type (m_range_size);
b731b390 652 tidx = make_ssa_name (utype);
edb9b69e 653 sub = fold_build2_loc (loc, MINUS_EXPR, utype,
789410e4
ML
654 fold_convert_loc (loc, utype, m_index_expr),
655 fold_convert_loc (loc, utype, m_range_min));
fae1034e 656 sub = force_gimple_operand_gsi (&gsi, sub,
726a989a
RB
657 false, NULL, true, GSI_SAME_STMT);
658 stmt = gimple_build_assign (tidx, sub);
b6e99746 659
726a989a 660 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
7156c8ab 661 update_stmt (stmt);
789410e4 662 m_arr_ref_first = stmt;
b6e99746 663
789410e4 664 for (gpi = gsi_start_phis (m_final_bb), i = 0;
18bfe940
JJ
665 !gsi_end_p (gpi); gsi_next (&gpi))
666 {
667 gphi *phi = gpi.phi ();
668 if (!virtual_operand_p (gimple_phi_result (phi)))
789410e4 669 build_one_array (i++, arr_index_type, phi, tidx);
8dc6a926
JJ
670 else
671 {
672 edge e;
673 edge_iterator ei;
789410e4 674 FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
8dc6a926 675 {
789410e4 676 if (e->dest == m_final_bb)
8dc6a926 677 break;
789410e4
ML
678 if (!m_default_case_nonstandard
679 || e->dest != m_default_bb)
8dc6a926
JJ
680 {
681 e = single_succ_edge (e->dest);
682 break;
683 }
684 }
789410e4
ML
685 gcc_assert (e && e->dest == m_final_bb);
686 m_target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
8dc6a926 687 }
18bfe940 688 }
b6e99746
MJ
689}
690
691/* Generates and appropriately inserts loads of default values at the position
789410e4 692 given by GSI. Returns the last inserted statement. */
b6e99746 693
789410e4
ML
694gassign *
695switch_conversion::gen_def_assigns (gimple_stmt_iterator *gsi)
b6e99746
MJ
696{
697 int i;
538dd0b7 698 gassign *assign = NULL;
b6e99746 699
789410e4 700 for (i = 0; i < m_phi_count; i++)
b6e99746 701 {
789410e4
ML
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]);
726a989a 705 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
7156c8ab 706 update_stmt (assign);
b6e99746
MJ
707 }
708 return assign;
709}
710
711/* Deletes the unused bbs and edges that now contain the switch statement and
789410e4
ML
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). */
b6e99746 715
789410e4
ML
716void
717switch_conversion::prune_bbs (basic_block bbd, basic_block final,
718 basic_block default_bb)
b6e99746
MJ
719{
720 edge_iterator ei;
721 edge e;
722
723 for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
724 {
725 basic_block bb;
726 bb = e->dest;
727 remove_edge (e);
18bfe940 728 if (bb != final && bb != default_bb)
b6e99746
MJ
729 delete_basic_block (bb);
730 }
731 delete_basic_block (bbd);
732}
733
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). */
738
789410e4
ML
739void
740switch_conversion::fix_phi_nodes (edge e1f, edge e2f, basic_block bbf)
b6e99746 741{
538dd0b7 742 gphi_iterator gsi;
b6e99746
MJ
743 int i;
744
726a989a 745 for (gsi = gsi_start_phis (bbf), i = 0;
18bfe940 746 !gsi_end_p (gsi); gsi_next (&gsi))
b6e99746 747 {
538dd0b7 748 gphi *phi = gsi.phi ();
18bfe940
JJ
749 tree inbound, outbound;
750 if (virtual_operand_p (gimple_phi_result (phi)))
789410e4 751 inbound = outbound = m_target_vop;
18bfe940
JJ
752 else
753 {
789410e4
ML
754 inbound = m_target_inbound_names[i];
755 outbound = m_target_outbound_names[i++];
18bfe940
JJ
756 }
757 add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
789410e4 758 if (!m_default_case_nonstandard)
18bfe940 759 add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
b6e99746 760 }
b6e99746
MJ
761}
762
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
789410e4 765 with default values instead. */
b6e99746 766
789410e4
ML
767void
768switch_conversion::gen_inbound_check ()
b6e99746 769{
c2255bc4
AH
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);
538dd0b7 773 glabel *label1, *label2, *label3;
edb9b69e 774 tree utype, tidx;
b6e99746
MJ
775 tree bound;
776
538dd0b7 777 gcond *cond_stmt;
b6e99746 778
18bfe940 779 gassign *last_assign = NULL;
726a989a 780 gimple_stmt_iterator gsi;
b6e99746 781 basic_block bb0, bb1, bb2, bbf, bbd;
18bfe940 782 edge e01 = NULL, e02, e21, e1d, e1f, e2f;
789410e4 783 location_t loc = gimple_location (m_switch);
b6e99746 784
789410e4 785 gcc_assert (m_default_values);
6ab1ab14 786
789410e4 787 bb0 = gimple_bb (m_switch);
b6e99746 788
789410e4 789 tidx = gimple_assign_lhs (m_arr_ref_first);
edb9b69e 790 utype = TREE_TYPE (tidx);
145544ab 791
b6e99746 792 /* (end of) block 0 */
789410e4 793 gsi = gsi_for_stmt (m_arr_ref_first);
edb9b69e 794 gsi_next (&gsi);
b6e99746 795
789410e4 796 bound = fold_convert_loc (loc, utype, m_range_size);
edb9b69e 797 cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
726a989a 798 gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
7156c8ab 799 update_stmt (cond_stmt);
b6e99746
MJ
800
801 /* block 2 */
789410e4 802 if (!m_default_case_nonstandard)
18bfe940
JJ
803 {
804 label2 = gimple_build_label (label_decl2);
805 gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
789410e4 806 last_assign = gen_def_assigns (&gsi);
18bfe940 807 }
b6e99746
MJ
808
809 /* block 1 */
726a989a
RB
810 label1 = gimple_build_label (label_decl1);
811 gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
b6e99746
MJ
812
813 /* block F */
789410e4 814 gsi = gsi_start_bb (m_final_bb);
726a989a
RB
815 label3 = gimple_build_label (label_decl3);
816 gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
b6e99746
MJ
817
818 /* cfg fix */
726a989a 819 e02 = split_block (bb0, cond_stmt);
b6e99746
MJ
820 bb2 = e02->dest;
821
789410e4 822 if (m_default_case_nonstandard)
18bfe940
JJ
823 {
824 bb1 = bb2;
789410e4 825 bb2 = m_default_bb;
18bfe940
JJ
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))
832 {
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));
837 }
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);
841 }
842 else
843 {
844 e21 = split_block (bb2, last_assign);
845 bb1 = e21->dest;
846 remove_edge (e21);
847 }
b6e99746 848
789410e4 849 e1d = split_block (bb1, m_arr_ref_last);
b6e99746
MJ
850 bbd = e1d->dest;
851 remove_edge (e1d);
852
789410e4
ML
853 /* Flags and profiles of the edge for in-range values. */
854 if (!m_default_case_nonstandard)
18bfe940 855 e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
789410e4 856 e01->probability = m_default_prob.invert ();
b6e99746 857
789410e4 858 /* Flags and profiles of the edge taking care of out-of-range values. */
b6e99746
MJ
859 e02->flags &= ~EDGE_FALLTHRU;
860 e02->flags |= EDGE_FALSE_VALUE;
789410e4 861 e02->probability = m_default_prob;
b6e99746 862
789410e4 863 bbf = m_final_bb;
b6e99746
MJ
864
865 e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
357067f2 866 e1f->probability = profile_probability::always ();
b6e99746 867
789410e4 868 if (m_default_case_nonstandard)
18bfe940
JJ
869 e2f = NULL;
870 else
871 {
872 e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
357067f2 873 e2f->probability = profile_probability::always ();
18bfe940 874 }
b6e99746
MJ
875
876 /* frequencies of the new BBs */
e7a74006
JH
877 bb1->count = e01->count ();
878 bb2->count = e02->count ();
789410e4 879 if (!m_default_case_nonstandard)
e7a74006 880 bbf->count = e1f->count () + e2f->count ();
b6e99746 881
6ab1ab14 882 /* Tidy blocks that have become unreachable. */
789410e4
ML
883 prune_bbs (bbd, m_final_bb,
884 m_default_case_nonstandard ? m_default_bb : NULL);
b6e99746 885
6ab1ab14 886 /* Fixup the PHI nodes in bbF. */
789410e4 887 fix_phi_nodes (e1f, e2f, bbf);
b6e99746 888
6ab1ab14
SB
889 /* Fix the dominator tree, if it is available. */
890 if (dom_info_available_p (CDI_DOMINATORS))
891 {
9771b263 892 vec<basic_block> bbs_to_fix_dom;
6ab1ab14
SB
893
894 set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
789410e4 895 if (!m_default_case_nonstandard)
18bfe940 896 set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
531b10fc 897 if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
6ab1ab14
SB
898 /* If bbD was the immediate dominator ... */
899 set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
900
18bfe940 901 bbs_to_fix_dom.create (3 + (bb2 != bbf));
9771b263
DN
902 bbs_to_fix_dom.quick_push (bb0);
903 bbs_to_fix_dom.quick_push (bb1);
18bfe940
JJ
904 if (bb2 != bbf)
905 bbs_to_fix_dom.quick_push (bb2);
9771b263 906 bbs_to_fix_dom.quick_push (bbf);
6ab1ab14
SB
907
908 iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
9771b263 909 bbs_to_fix_dom.release ();
6ab1ab14 910 }
b6e99746
MJ
911}
912
789410e4
ML
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. */
b6e99746 918
789410e4
ML
919void
920switch_conversion::expand (gswitch *swtch)
b6e99746 921{
238065a7
SB
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. */
789410e4 924 m_cfg_altered |= group_case_labels_stmt (swtch);
238065a7
SB
925
926 /* If this switch is now a degenerate case with only a default label,
789410e4 927 there is nothing left for us to do. */
238065a7 928 if (gimple_switch_num_labels (swtch) < 2)
789410e4
ML
929 {
930 m_reason = "switch is a degenerate case";
931 return;
932 }
886cd84f 933
789410e4 934 collect (swtch);
886cd84f
SB
935
936 /* No error markers should reach here (they should be filtered out
937 during gimplification). */
789410e4 938 gcc_checking_assert (TREE_TYPE (m_index_expr) != error_mark_node);
886cd84f 939
531b10fc 940 /* A switch on a constant should have been optimized in tree-cfg-cleanup. */
789410e4 941 gcc_checking_assert (!TREE_CONSTANT (m_index_expr));
886cd84f 942
dc223ad4
ML
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))
947 {
948 m_reason = "expanding as bit test is preferable";
949 return;
950 }
951
952 if (m_uniq <= 2)
953 {
954 /* This will be expanded as a decision tree . */
955 m_reason = "expanding as jumps is preferable";
956 return;
957 }
958
789410e4
ML
959 /* If there is no common successor, we cannot do the transformation. */
960 if (!m_final_bb)
886cd84f 961 {
789410e4
ML
962 m_reason = "no common successor to all case label target blocks found";
963 return;
886cd84f 964 }
b6e99746
MJ
965
966 /* Check the case label values are within reasonable range: */
789410e4 967 if (!check_range ())
fade902a 968 {
789410e4
ML
969 gcc_assert (m_reason);
970 return;
fade902a 971 }
b6e99746
MJ
972
973 /* For all the cases, see whether they are empty, the assignments they
974 represent constant and so on... */
789410e4 975 if (!check_all_empty_except_final ())
8e97bc2b 976 {
789410e4
ML
977 gcc_assert (m_reason);
978 return;
8e97bc2b 979 }
789410e4 980 if (!check_final_bb ())
fade902a 981 {
789410e4
ML
982 gcc_assert (m_reason);
983 return;
fade902a 984 }
b6e99746
MJ
985
986 /* At this point all checks have passed and we can proceed with the
987 transformation. */
988
789410e4
ML
989 create_temp_arrays ();
990 gather_default_values (m_default_case_nonstandard
18bfe940 991 ? gimple_switch_label (swtch, 1)
789410e4
ML
992 : gimple_switch_default_label (swtch));
993 build_constructors ();
b6e99746 994
789410e4
ML
995 build_arrays (); /* Build the static arrays and assignments. */
996 gen_inbound_check (); /* Build the bounds check. */
b6e99746 997
789410e4
ML
998 m_cfg_altered = true;
999}
1000
1001/* Destructor. */
1002
1003switch_conversion::~switch_conversion ()
1004{
1005 XDELETEVEC (m_constructors);
1006 XDELETEVEC (m_default_values);
b6e99746
MJ
1007}
1008
dc223ad4 1009/* Constructor. */
be55bfe6 1010
dc223ad4
ML
1011group_cluster::group_cluster (vec<cluster *> &clusters,
1012 unsigned start, unsigned end)
be55bfe6 1013{
dc223ad4
ML
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++)
1018 {
1019 m_cases.quick_push (static_cast<simple_cluster *> (clusters[i]));
1020 m_prob += clusters[i]->m_prob;
1021 }
1022 m_subtree_prob = m_prob;
1023}
be55bfe6 1024
dc223ad4
ML
1025/* Destructor. */
1026
1027group_cluster::~group_cluster ()
be55bfe6 1028{
dc223ad4
ML
1029 for (unsigned i = 0; i < m_cases.length (); i++)
1030 delete m_cases[i];
be55bfe6 1031
dc223ad4
ML
1032 m_cases.release ();
1033}
be55bfe6 1034
dc223ad4 1035/* Dump content of a cluster. */
be55bfe6 1036
dc223ad4
ML
1037void
1038group_cluster::dump (FILE *f, bool details)
b6e99746 1039{
dc223ad4
ML
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 ());
726a989a 1044
dc223ad4
ML
1045 unsigned comparison_count = 0;
1046 for (unsigned i = 0; i < m_cases.length (); i++)
1047 {
1048 simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1049 comparison_count += sc->m_range_p ? 2 : 1;
1050 }
b6e99746 1051
dc223ad4
ML
1052 unsigned HOST_WIDE_INT range = get_range (get_low (), get_high ());
1053 fprintf (f, "%s", get_type () == JUMP_TABLE ? "JT" : "BT");
531b10fc 1054
dc223ad4
ML
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);
b6e99746 1059
dc223ad4
ML
1060 fprintf (f, ":");
1061 PRINT_CASE (f, get_low ());
1062 fprintf (f, "-");
1063 PRINT_CASE (f, get_high ());
1064 fprintf (f, " ");
b6e99746
MJ
1065}
1066
dc223ad4 1067/* Emit GIMPLE code to handle the cluster. */
27a4cd48 1068
dc223ad4
ML
1069void
1070jump_table_cluster::emit (tree index_expr, tree,
1071 tree default_label_expr, basic_block default_bb)
27a4cd48 1072{
dc223ad4
ML
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 ());
1077
1078 make_edge (m_case_bb, default_bb, 0);
1079 for (unsigned i = 0; i < m_cases.length (); i++)
1080 {
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);
1083 }
1084
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);
27a4cd48 1089}
9dc3d6a9 1090
2f928c1b
ML
1091/* Find jump tables of given CLUSTERS, where all members of the vector
1092 are of type simple_cluster. New clusters are returned. */
1093
1094vec<cluster *>
1095jump_table_cluster::find_jump_tables (vec<cluster *> &clusters)
1096{
5885a1bd
ML
1097 if (!is_enabled ())
1098 return clusters.copy ();
1099
2f928c1b
ML
1100 unsigned l = clusters.length ();
1101 auto_vec<min_cluster_item> min;
1102 min.reserve (l + 1);
1103
1104 min.quick_push (min_cluster_item (0, 0, 0));
1105
1106 for (unsigned i = 1; i <= l; i++)
1107 {
1108 /* Set minimal # of clusters with i-th item to infinite. */
1109 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1110
1111 for (unsigned j = 0; j < i; j++)
1112 {
1113 unsigned HOST_WIDE_INT s = min[j].m_non_jt_cases;
1114 if (i - j < case_values_threshold ())
1115 s += i - j;
1116
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);
1123 }
df7c7974
ML
1124
1125 gcc_checking_assert (min[i].m_count != INT_MAX);
2f928c1b
ML
1126 }
1127
1128 /* No result. */
1129 if (min[l].m_count == INT_MAX)
1130 return clusters.copy ();
1131
1132 vec<cluster *> output;
1133 output.create (4);
1134
1135 /* Find and build the clusters. */
1136 for (int end = l;;)
1137 {
1138 int start = min[end].m_start;
1139
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]);
1146
1147 end = start;
1148
1149 if (start <= 0)
1150 break;
1151 }
1152
1153 output.reverse ();
1154 return output;
1155}
1156
dc223ad4
ML
1157/* Return true when cluster starting at START and ending at END (inclusive)
1158 can build a jump-table. */
1159
1160bool
1161jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1162 unsigned start, unsigned end)
9dc3d6a9 1163{
dc223ad4
ML
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.
9dc3d6a9 1167
dc223ad4
ML
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.
9dc3d6a9 1171
dc223ad4 1172 The definition of "much bigger" depends on whether we are
de840bde 1173 optimizing for size or for speed. */
dc223ad4
ML
1174 if (!flag_jump_tables)
1175 return false;
9dc3d6a9 1176
df7c7974
ML
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;
9dc3d6a9 1182
1aabb71d
ML
1183 unsigned HOST_WIDE_INT max_ratio
1184 = optimize_insn_for_size_p () ? max_ratio_for_size : max_ratio_for_speed;
dc223ad4
ML
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;
9dc3d6a9 1190
dc223ad4
ML
1191 unsigned HOST_WIDE_INT comparison_count = 0;
1192 for (unsigned i = start; i <= end; i++)
1193 {
1194 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1195 comparison_count += sc->m_range_p ? 2 : 1;
1196 }
9dc3d6a9 1197
dc223ad4 1198 return range <= max_ratio * comparison_count;
9dc3d6a9
ML
1199}
1200
dc223ad4
ML
1201/* Return true if cluster starting at START and ending at END (inclusive)
1202 is profitable transformation. */
9dc3d6a9 1203
dc223ad4
ML
1204bool
1205jump_table_cluster::is_beneficial (const vec<cluster *> &,
1206 unsigned start, unsigned end)
9dc3d6a9 1207{
df7c7974
ML
1208 /* Single case bail out. */
1209 if (start == end)
1210 return false;
1211
dc223ad4 1212 return end - start + 1 >= case_values_threshold ();
9dc3d6a9
ML
1213}
1214
2f928c1b
ML
1215/* Find bit tests of given CLUSTERS, where all members of the vector
1216 are of type simple_cluster. New clusters are returned. */
1217
1218vec<cluster *>
1219bit_test_cluster::find_bit_tests (vec<cluster *> &clusters)
1220{
1221 vec<cluster *> output;
1222 output.create (4);
1223
1224 unsigned l = clusters.length ();
1225 auto_vec<min_cluster_item> min;
1226 min.reserve (l + 1);
1227
1228 min.quick_push (min_cluster_item (0, 0, 0));
1229
1230 for (unsigned i = 1; i <= l; i++)
1231 {
1232 /* Set minimal # of clusters with i-th item to infinite. */
1233 min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1234
1235 for (unsigned j = 0; j < i; j++)
1236 {
1237 if (min[j].m_count + 1 < min[i].m_count
1238 && can_be_handled (clusters, j, i - 1))
1239 min[i] = min_cluster_item (min[j].m_count + 1, j, INT_MAX);
1240 }
df7c7974
ML
1241
1242 gcc_checking_assert (min[i].m_count != INT_MAX);
2f928c1b
ML
1243 }
1244
1245 /* No result. */
1246 if (min[l].m_count == INT_MAX)
1247 return clusters.copy ();
1248
1249 /* Find and build the clusters. */
1250 for (int end = l;;)
1251 {
1252 int start = min[end].m_start;
1253
1254 if (is_beneficial (clusters, start, end - 1))
1255 output.safe_push (new bit_test_cluster (clusters, start, end - 1));
1256 else
1257 for (int i = end - 1; i >= start; i--)
1258 output.safe_push (clusters[i]);
1259
1260 end = start;
1261
1262 if (start <= 0)
1263 break;
1264 }
1265
1266 output.reverse ();
1267 return output;
1268}
1269
dc223ad4
ML
1270/* Return true when RANGE of case values with UNIQ labels
1271 can build a bit test. */
9dc3d6a9 1272
dc223ad4
ML
1273bool
1274bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1275 unsigned int uniq)
9dc3d6a9 1276{
dc223ad4
ML
1277 /* Check overflow. */
1278 if (range == 0)
1279 return 0;
1280
1281 if (range >= GET_MODE_BITSIZE (word_mode))
1282 return false;
1283
1284 return uniq <= 3;
1285}
1286
1287/* Return true when cluster starting at START and ending at END (inclusive)
1288 can build a bit test. */
1289
1290bool
1291bit_test_cluster::can_be_handled (const vec<cluster *> &clusters,
1292 unsigned start, unsigned end)
1293{
df7c7974
ML
1294 /* For algorithm correctness, bit test for a single case must return
1295 true. We bail out in is_beneficial if it's called just for
1296 a single case. */
1297 if (start == end)
1298 return true;
1299
dc223ad4
ML
1300 unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1301 clusters[end]->get_high ());
1302 auto_bitmap dest_bbs;
1303
1304 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1305 {
dc223ad4
ML
1306 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1307 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1308 }
9dc3d6a9 1309
dc223ad4
ML
1310 return can_be_handled (range, bitmap_count_bits (dest_bbs));
1311}
9dc3d6a9 1312
dc223ad4
ML
1313/* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1314 transformation. */
9dc3d6a9 1315
dc223ad4
ML
1316bool
1317bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
9dc3d6a9 1318{
dc223ad4
ML
1319 return (((uniq == 1 && count >= 3)
1320 || (uniq == 2 && count >= 5)
1321 || (uniq == 3 && count >= 6)));
9dc3d6a9
ML
1322}
1323
dc223ad4
ML
1324/* Return true if cluster starting at START and ending at END (inclusive)
1325 is profitable transformation. */
9dc3d6a9 1326
dc223ad4
ML
1327bool
1328bit_test_cluster::is_beneficial (const vec<cluster *> &clusters,
1329 unsigned start, unsigned end)
9dc3d6a9 1330{
df7c7974
ML
1331 /* Single case bail out. */
1332 if (start == end)
1333 return false;
1334
dc223ad4 1335 auto_bitmap dest_bbs;
9dc3d6a9 1336
dc223ad4 1337 for (unsigned i = start; i <= end; i++)
9dc3d6a9 1338 {
dc223ad4
ML
1339 simple_cluster *sc = static_cast<simple_cluster *> (clusters[i]);
1340 bitmap_set_bit (dest_bbs, sc->m_case_bb->index);
9dc3d6a9 1341 }
9dc3d6a9 1342
dc223ad4
ML
1343 unsigned uniq = bitmap_count_bits (dest_bbs);
1344 unsigned count = end - start + 1;
1345 return is_beneficial (count, uniq);
9dc3d6a9
ML
1346}
1347
dc223ad4
ML
1348/* Comparison function for qsort to order bit tests by decreasing
1349 probability of execution. */
9dc3d6a9 1350
dc223ad4
ML
1351int
1352case_bit_test::cmp (const void *p1, const void *p2)
1353{
1354 const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
1355 const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
1356
1357 if (d2->bits != d1->bits)
1358 return d2->bits - d1->bits;
1359
1360 /* Stabilize the sort. */
1361 return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1362 - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1363}
1364
1365/* Expand a switch statement by a short sequence of bit-wise
1366 comparisons. "switch(x)" is effectively converted into
1367 "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1368 integer constants.
1369
1370 INDEX_EXPR is the value being switched on.
1371
1372 MINVAL is the lowest case value of in the case nodes,
1373 and RANGE is highest value minus MINVAL. MINVAL and RANGE
1374 are not guaranteed to be of the same type as INDEX_EXPR
1375 (the gimplifier doesn't change the type of case label values,
1376 and MINVAL and RANGE are derived from those values).
1377 MAXVAL is MINVAL + RANGE.
9dc3d6a9 1378
dc223ad4
ML
1379 There *MUST* be max_case_bit_tests or less unique case
1380 node targets. */
1381
1382void
1383bit_test_cluster::emit (tree index_expr, tree index_type,
1384 tree, basic_block default_bb)
9dc3d6a9 1385{
dc223ad4
ML
1386 struct case_bit_test test[m_max_case_bit_tests] = { {} };
1387 unsigned int i, j, k;
1388 unsigned int count;
9dc3d6a9 1389
dc223ad4 1390 tree unsigned_index_type = unsigned_type_for (index_type);
9dc3d6a9 1391
dc223ad4
ML
1392 gimple_stmt_iterator gsi;
1393 gassign *shift_stmt;
9dc3d6a9 1394
dc223ad4
ML
1395 tree idx, tmp, csui;
1396 tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1397 tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1398 tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1399 int prec = TYPE_PRECISION (word_type_node);
1400 wide_int wone = wi::one (prec);
9dc3d6a9 1401
dc223ad4
ML
1402 tree minval = get_low ();
1403 tree maxval = get_high ();
1404 tree range = int_const_binop (MINUS_EXPR, maxval, minval);
9dc3d6a9 1405
dc223ad4
ML
1406 /* Go through all case labels, and collect the case labels, profile
1407 counts, and other information we need to build the branch tests. */
1408 count = 0;
1409 for (i = 0; i < m_cases.length (); i++)
1410 {
1411 unsigned int lo, hi;
1412 simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
1413 for (k = 0; k < count; k++)
1414 if (n->m_case_bb == test[k].target_bb)
1415 break;
1416
1417 if (k == count)
9dc3d6a9 1418 {
dc223ad4
ML
1419 gcc_checking_assert (count < m_max_case_bit_tests);
1420 test[k].mask = wi::zero (prec);
1421 test[k].target_bb = n->m_case_bb;
1422 test[k].label = n->m_case_label_expr;
1423 test[k].bits = 1;
1424 count++;
1425 }
1426 else
1427 test[k].bits++;
9dc3d6a9 1428
dc223ad4
ML
1429 lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
1430 if (n->get_high () == NULL_TREE)
1431 hi = lo;
1432 else
1433 hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
1434 minval));
9dc3d6a9 1435
dc223ad4
ML
1436 for (j = lo; j <= hi; j++)
1437 test[k].mask |= wi::lshift (wone, j);
1438 }
1439
1440 qsort (test, count, sizeof (*test), case_bit_test::cmp);
1441
1442 /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
1443 the minval subtractions, but it might make the mask constants more
1444 expensive. So, compare the costs. */
1445 if (compare_tree_int (minval, 0) > 0
1446 && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
1447 {
1448 int cost_diff;
1449 HOST_WIDE_INT m = tree_to_uhwi (minval);
1450 rtx reg = gen_raw_REG (word_mode, 10000);
1451 bool speed_p = optimize_insn_for_speed_p ();
1452 cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
1453 GEN_INT (-m)), speed_p);
1454 for (i = 0; i < count; i++)
1455 {
1456 rtx r = immed_wide_int_const (test[i].mask, word_mode);
1457 cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
1458 word_mode, speed_p);
1459 r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
1460 cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
1461 word_mode, speed_p);
9dc3d6a9 1462 }
dc223ad4 1463 if (cost_diff > 0)
9dc3d6a9 1464 {
dc223ad4
ML
1465 for (i = 0; i < count; i++)
1466 test[i].mask = wi::lshift (test[i].mask, m);
1467 minval = build_zero_cst (TREE_TYPE (minval));
1468 range = maxval;
9dc3d6a9
ML
1469 }
1470 }
9dc3d6a9 1471
dc223ad4
ML
1472 /* Now build the test-and-branch code. */
1473
1474 gsi = gsi_last_bb (m_case_bb);
1475
1476 /* idx = (unsigned)x - minval. */
1477 idx = fold_convert (unsigned_index_type, index_expr);
1478 idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
1479 fold_convert (unsigned_index_type, minval));
1480 idx = force_gimple_operand_gsi (&gsi, idx,
1481 /*simple=*/true, NULL_TREE,
1482 /*before=*/true, GSI_SAME_STMT);
1483
1484 /* if (idx > range) goto default */
1485 range = force_gimple_operand_gsi (&gsi,
1486 fold_convert (unsigned_index_type, range),
1487 /*simple=*/true, NULL_TREE,
1488 /*before=*/true, GSI_SAME_STMT);
1489 tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
1490 basic_block new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb);
1491 gsi = gsi_last_bb (new_bb);
1492
1493 /* csui = (1 << (word_mode) idx) */
1494 csui = make_ssa_name (word_type_node);
1495 tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
1496 fold_convert (word_type_node, idx));
1497 tmp = force_gimple_operand_gsi (&gsi, tmp,
1498 /*simple=*/false, NULL_TREE,
1499 /*before=*/true, GSI_SAME_STMT);
1500 shift_stmt = gimple_build_assign (csui, tmp);
1501 gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
1502 update_stmt (shift_stmt);
1503
1504 /* for each unique set of cases:
1505 if (const & csui) goto target */
1506 for (k = 0; k < count; k++)
1507 {
1508 tmp = wide_int_to_tree (word_type_node, test[k].mask);
1509 tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
1510 tmp = force_gimple_operand_gsi (&gsi, tmp,
1511 /*simple=*/true, NULL_TREE,
1512 /*before=*/true, GSI_SAME_STMT);
1513 tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
1514 new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb);
1515 gsi = gsi_last_bb (new_bb);
1516 }
9dc3d6a9 1517
dc223ad4
ML
1518 /* We should have removed all edges now. */
1519 gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
9dc3d6a9 1520
dc223ad4
ML
1521 /* If nothing matched, go to the default label. */
1522 make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
1523}
9dc3d6a9 1524
dc223ad4
ML
1525/* Split the basic block at the statement pointed to by GSIP, and insert
1526 a branch to the target basic block of E_TRUE conditional on tree
1527 expression COND.
9dc3d6a9 1528
dc223ad4
ML
1529 It is assumed that there is already an edge from the to-be-split
1530 basic block to E_TRUE->dest block. This edge is removed, and the
1531 profile information on the edge is re-used for the new conditional
1532 jump.
9dc3d6a9 1533
dc223ad4
ML
1534 The CFG is updated. The dominator tree will not be valid after
1535 this transformation, but the immediate dominators are updated if
1536 UPDATE_DOMINATORS is true.
9dc3d6a9 1537
dc223ad4 1538 Returns the newly created basic block. */
9dc3d6a9 1539
dc223ad4
ML
1540basic_block
1541bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
1542 tree cond, basic_block case_bb)
9dc3d6a9 1543{
dc223ad4
ML
1544 tree tmp;
1545 gcond *cond_stmt;
1546 edge e_false;
1547 basic_block new_bb, split_bb = gsi_bb (*gsip);
9dc3d6a9 1548
dc223ad4
ML
1549 edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
1550 gcc_assert (e_true->src == split_bb);
9dc3d6a9 1551
dc223ad4
ML
1552 tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
1553 /*before=*/true, GSI_SAME_STMT);
1554 cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
1555 gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
9dc3d6a9 1556
dc223ad4
ML
1557 e_false = split_block (split_bb, cond_stmt);
1558 new_bb = e_false->dest;
1559 redirect_edge_pred (e_true, split_bb);
9dc3d6a9 1560
dc223ad4
ML
1561 e_false->flags &= ~EDGE_FALLTHRU;
1562 e_false->flags |= EDGE_FALSE_VALUE;
1563 e_false->probability = e_true->probability.invert ();
1564 new_bb->count = e_false->count ();
1565
1566 return new_bb;
9dc3d6a9
ML
1567}
1568
dc223ad4
ML
1569/* Compute the number of case labels that correspond to each outgoing edge of
1570 switch statement. Record this information in the aux field of the edge. */
9dc3d6a9 1571
dc223ad4
ML
1572void
1573switch_decision_tree::compute_cases_per_edge ()
1574{
1575 basic_block bb = gimple_bb (m_switch);
1576 reset_out_edges_aux ();
1577 int ncases = gimple_switch_num_labels (m_switch);
1578 for (int i = ncases - 1; i >= 1; --i)
1579 {
1580 tree elt = gimple_switch_label (m_switch, i);
1581 tree lab = CASE_LABEL (elt);
1582 basic_block case_bb = label_to_block_fn (cfun, lab);
1583 edge case_edge = find_edge (bb, case_bb);
1584 case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
1585 }
1586}
1587
1588/* Analyze switch statement and return true when the statement is expanded
1589 as decision tree. */
9dc3d6a9 1590
dc223ad4
ML
1591bool
1592switch_decision_tree::analyze_switch_statement ()
9dc3d6a9 1593{
dc223ad4
ML
1594 unsigned l = gimple_switch_num_labels (m_switch);
1595 basic_block bb = gimple_bb (m_switch);
1596 auto_vec<cluster *> clusters;
1597 clusters.create (l - 1);
1598
1599 tree default_label = CASE_LABEL (gimple_switch_default_label (m_switch));
1600 basic_block default_bb = label_to_block_fn (cfun, default_label);
1601 m_case_bbs.reserve (l);
1602 m_case_bbs.quick_push (default_bb);
1603
1604 compute_cases_per_edge ();
1605
1606 for (unsigned i = 1; i < l; i++)
1607 {
1608 tree elt = gimple_switch_label (m_switch, i);
1609 tree lab = CASE_LABEL (elt);
1610 basic_block case_bb = label_to_block_fn (cfun, lab);
1611 edge case_edge = find_edge (bb, case_bb);
1612 tree low = CASE_LOW (elt);
1613 tree high = CASE_HIGH (elt);
1614
1615 profile_probability p
1616 = case_edge->probability.apply_scale (1, (intptr_t) (case_edge->aux));
1617 clusters.quick_push (new simple_cluster (low, high, elt, case_bb, p));
1618 m_case_bbs.quick_push (case_bb);
1619 }
1620
1621 reset_out_edges_aux ();
1622
2f928c1b
ML
1623 /* Find jump table clusters. */
1624 vec<cluster *> output = jump_table_cluster::find_jump_tables (clusters);
1625
df7c7974 1626 /* Find bit test clusters. */
2f928c1b
ML
1627 vec<cluster *> output2;
1628 auto_vec<cluster *> tmp;
1629 output2.create (1);
1630 tmp.create (1);
1631
1632 for (unsigned i = 0; i < output.length (); i++)
1633 {
1634 cluster *c = output[i];
1635 if (c->get_type () != SIMPLE_CASE)
1636 {
1637 if (!tmp.is_empty ())
1638 {
1639 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1640 output2.safe_splice (n);
1641 n.release ();
1642 tmp.truncate (0);
1643 }
1644 output2.safe_push (c);
1645 }
1646 else
1647 tmp.safe_push (c);
1648 }
1649
1650 /* We still can have a temporary vector to test. */
1651 if (!tmp.is_empty ())
1652 {
1653 vec<cluster *> n = bit_test_cluster::find_bit_tests (tmp);
1654 output2.safe_splice (n);
1655 n.release ();
1656 }
9dc3d6a9
ML
1657
1658 if (dump_file)
9dc3d6a9 1659 {
dc223ad4 1660 fprintf (dump_file, ";; GIMPLE switch case clusters: ");
2f928c1b
ML
1661 for (unsigned i = 0; i < output2.length (); i++)
1662 output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
dc223ad4
ML
1663 fprintf (dump_file, "\n");
1664 }
1665
2f928c1b 1666 output.release ();
dc223ad4 1667
2f928c1b
ML
1668 bool expanded = try_switch_expansion (output2);
1669
1670 for (unsigned i = 0; i < output2.length (); i++)
1671 delete output2[i];
1672
1673 output2.release ();
dc223ad4
ML
1674
1675 return expanded;
1676}
1677
1678/* Attempt to expand CLUSTERS as a decision tree. Return true when
1679 expanded. */
1680
1681bool
1682switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
1683{
1684 tree index_expr = gimple_switch_index (m_switch);
1685 tree index_type = TREE_TYPE (index_expr);
1686 basic_block bb = gimple_bb (m_switch);
1687
1688 if (gimple_switch_num_labels (m_switch) == 1)
1689 return false;
1690
1691 /* Find the default case target label. */
1692 tree default_label_expr = CASE_LABEL (gimple_switch_default_label (m_switch));
1693 m_default_bb = label_to_block_fn (cfun, default_label_expr);
1694 edge default_edge = find_edge (bb, m_default_bb);
1695
1696 /* Do the insertion of a case label into m_case_list. The labels are
1697 fed to us in descending order from the sorted vector of case labels used
1698 in the tree part of the middle end. So the list we construct is
1699 sorted in ascending order. */
1700
1701 for (int i = clusters.length () - 1; i >= 0; i--)
1702 {
1703 case_tree_node *r = m_case_list;
1704 m_case_list = m_case_node_pool.allocate ();
1705 m_case_list->m_right = r;
1706 m_case_list->m_c = clusters[i];
9dc3d6a9
ML
1707 }
1708
dc223ad4
ML
1709 record_phi_operand_mapping ();
1710
1711 /* Split basic block that contains the gswitch statement. */
9dc3d6a9
ML
1712 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1713 edge e;
1714 if (gsi_end_p (gsi))
1715 e = split_block_after_labels (bb);
1716 else
1717 {
1718 gsi_prev (&gsi);
1719 e = split_block (bb, gsi_stmt (gsi));
1720 }
1721 bb = split_edge (e);
1722
dc223ad4
ML
1723 /* Create new basic blocks for non-case clusters where specific expansion
1724 needs to happen. */
1725 for (unsigned i = 0; i < clusters.length (); i++)
1726 if (clusters[i]->get_type () != SIMPLE_CASE)
1727 {
1728 clusters[i]->m_case_bb = create_empty_bb (bb);
1729 clusters[i]->m_case_bb->loop_father = bb->loop_father;
1730 }
9dc3d6a9 1731
dc223ad4
ML
1732 /* Do not do an extra work for a single cluster. */
1733 if (clusters.length () == 1
1734 && clusters[0]->get_type () != SIMPLE_CASE)
1735 clusters[0]->emit (index_expr, index_type,
1736 gimple_switch_default_label (m_switch), m_default_bb);
1737 else
1738 {
1739 emit (bb, index_expr, default_edge->probability, index_type);
1740
1741 /* Emit cluster-specific switch handling. */
1742 for (unsigned i = 0; i < clusters.length (); i++)
1743 if (clusters[i]->get_type () != SIMPLE_CASE)
1744 clusters[i]->emit (index_expr, index_type,
1745 gimple_switch_default_label (m_switch),
1746 m_default_bb);
1747 }
9dc3d6a9 1748
dc223ad4
ML
1749 fix_phi_operands_for_edges ();
1750
1751 return true;
9dc3d6a9
ML
1752}
1753
dc223ad4
ML
1754/* Before switch transformation, record all SSA_NAMEs defined in switch BB
1755 and used in a label basic block. */
1756
1757void
1758switch_decision_tree::record_phi_operand_mapping ()
9dc3d6a9 1759{
dc223ad4 1760 basic_block switch_bb = gimple_bb (m_switch);
9dc3d6a9 1761 /* Record all PHI nodes that have to be fixed after conversion. */
dc223ad4 1762 for (unsigned i = 0; i < m_case_bbs.length (); i++)
9dc3d6a9 1763 {
9dc3d6a9 1764 gphi_iterator gsi;
dc223ad4 1765 basic_block bb = m_case_bbs[i];
9dc3d6a9
ML
1766 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1767 {
1768 gphi *phi = gsi.phi ();
1769
1770 for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
1771 {
1772 basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
1773 if (phi_src_bb == switch_bb)
1774 {
1775 tree def = gimple_phi_arg_def (phi, i);
1776 tree result = gimple_phi_result (phi);
dc223ad4 1777 m_phi_mapping.put (result, def);
9dc3d6a9
ML
1778 break;
1779 }
1780 }
1781 }
1782 }
1783}
1784
dc223ad4
ML
1785/* Append new operands to PHI statements that were introduced due to
1786 addition of new edges to case labels. */
9dc3d6a9 1787
dc223ad4
ML
1788void
1789switch_decision_tree::fix_phi_operands_for_edges ()
9dc3d6a9 1790{
dc223ad4 1791 gphi_iterator gsi;
9dc3d6a9 1792
dc223ad4
ML
1793 for (unsigned i = 0; i < m_case_bbs.length (); i++)
1794 {
1795 basic_block bb = m_case_bbs[i];
1796 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1797 {
1798 gphi *phi = gsi.phi ();
1799 for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
1800 {
1801 tree def = gimple_phi_arg_def (phi, j);
1802 if (def == NULL_TREE)
1803 {
1804 edge e = gimple_phi_arg_edge (phi, j);
1805 tree *definition
1806 = m_phi_mapping.get (gimple_phi_result (phi));
1807 gcc_assert (definition);
1808 add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
1809 }
1810 }
1811 }
1812 }
1813}
9dc3d6a9 1814
dc223ad4
ML
1815/* Generate a decision tree, switching on INDEX_EXPR and jumping to
1816 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
9dc3d6a9 1817
dc223ad4
ML
1818 We generate a binary decision tree to select the appropriate target
1819 code. */
9dc3d6a9 1820
dc223ad4
ML
1821void
1822switch_decision_tree::emit (basic_block bb, tree index_expr,
1823 profile_probability default_prob, tree index_type)
1824{
1825 balance_case_nodes (&m_case_list, NULL);
9dc3d6a9 1826
dc223ad4
ML
1827 if (dump_file)
1828 dump_function_to_file (current_function_decl, dump_file, dump_flags);
1829 if (dump_file && (dump_flags & TDF_DETAILS))
1830 {
1831 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1832 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1833 gcc_assert (m_case_list != NULL);
1834 dump_case_nodes (dump_file, m_case_list, indent_step, 0);
1835 }
9dc3d6a9 1836
dc223ad4 1837 bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type);
9dc3d6a9 1838
dc223ad4
ML
1839 if (bb)
1840 emit_jump (bb, m_default_bb);
9dc3d6a9 1841
dc223ad4
ML
1842 /* Remove all edges and do just an edge that will reach default_bb. */
1843 bb = gimple_bb (m_switch);
1844 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1845 gsi_remove (&gsi, true);
9dc3d6a9 1846
dc223ad4
ML
1847 delete_basic_block (bb);
1848}
1849
1850/* Take an ordered list of case nodes
1851 and transform them into a near optimal binary tree,
1852 on the assumption that any target code selection value is as
1853 likely as any other.
1854
1855 The transformation is performed by splitting the ordered
1856 list into two equal sections plus a pivot. The parts are
1857 then attached to the pivot as left and right branches. Each
1858 branch is then transformed recursively. */
1859
1860void
1861switch_decision_tree::balance_case_nodes (case_tree_node **head,
1862 case_tree_node *parent)
1863{
1864 case_tree_node *np;
1865
1866 np = *head;
1867 if (np)
9dc3d6a9 1868 {
dc223ad4
ML
1869 int i = 0;
1870 int ranges = 0;
1871 case_tree_node **npp;
1872 case_tree_node *left;
9dc3d6a9 1873
dc223ad4 1874 /* Count the number of entries on branch. Also count the ranges. */
9dc3d6a9 1875
dc223ad4
ML
1876 while (np)
1877 {
1878 if (!tree_int_cst_equal (np->m_c->get_low (), np->m_c->get_high ()))
1879 ranges++;
9dc3d6a9 1880
dc223ad4
ML
1881 i++;
1882 np = np->m_right;
1883 }
9dc3d6a9 1884
dc223ad4
ML
1885 if (i > 2)
1886 {
1887 /* Split this list if it is long enough for that to help. */
1888 npp = head;
1889 left = *npp;
9dc3d6a9 1890
dc223ad4
ML
1891 /* If there are just three nodes, split at the middle one. */
1892 if (i == 3)
1893 npp = &(*npp)->m_right;
1894 else
1895 {
1896 /* Find the place in the list that bisects the list's total cost,
1897 where ranges count as 2.
1898 Here I gets half the total cost. */
1899 i = (i + ranges + 1) / 2;
1900 while (1)
1901 {
1902 /* Skip nodes while their cost does not reach that amount. */
1903 if (!tree_int_cst_equal ((*npp)->m_c->get_low (),
1904 (*npp)->m_c->get_high ()))
1905 i--;
1906 i--;
1907 if (i <= 0)
1908 break;
1909 npp = &(*npp)->m_right;
1910 }
1911 }
1912 *head = np = *npp;
1913 *npp = 0;
1914 np->m_parent = parent;
1915 np->m_left = left;
9dc3d6a9 1916
dc223ad4
ML
1917 /* Optimize each of the two split parts. */
1918 balance_case_nodes (&np->m_left, np);
1919 balance_case_nodes (&np->m_right, np);
1920 np->m_c->m_subtree_prob = np->m_c->m_prob;
1921 np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
1922 np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1923 }
1924 else
1925 {
1926 /* Else leave this branch as one level,
1927 but fill in `parent' fields. */
1928 np = *head;
1929 np->m_parent = parent;
1930 np->m_c->m_subtree_prob = np->m_c->m_prob;
1931 for (; np->m_right; np = np->m_right)
1932 {
1933 np->m_right->m_parent = np;
1934 (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
1935 }
1936 }
9dc3d6a9 1937 }
dc223ad4
ML
1938}
1939
1940/* Dump ROOT, a list or tree of case nodes, to file. */
9dc3d6a9 1941
dc223ad4
ML
1942void
1943switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
1944 int indent_step, int indent_level)
1945{
1946 if (root == 0)
1947 return;
1948 indent_level++;
1949
1950 dump_case_nodes (f, root->m_left, indent_step, indent_level);
1951
1952 fputs (";; ", f);
1953 fprintf (f, "%*s", indent_step * indent_level, "");
1954 root->m_c->dump (f);
1955 root->m_c->m_prob.dump (f);
1956 fputs ("\n", f);
1957
1958 dump_case_nodes (f, root->m_right, indent_step, indent_level);
1959}
1960
1961
1962/* Add an unconditional jump to CASE_BB that happens in basic block BB. */
1963
1964void
1965switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
1966{
1967 edge e = single_succ_edge (bb);
1968 redirect_edge_succ (e, case_bb);
1969}
1970
1971/* Generate code to compare OP0 with OP1 so that the condition codes are
1972 set and to jump to LABEL_BB if the condition is true.
1973 COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
1974 PROB is the probability of jumping to LABEL_BB. */
1975
1976basic_block
1977switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
1978 tree op1, tree_code comparison,
1979 basic_block label_bb,
1980 profile_probability prob)
1981{
1982 // TODO: it's once called with lhs != index.
1983 op1 = fold_convert (TREE_TYPE (op0), op1);
1984
1985 gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
1986 gimple_stmt_iterator gsi = gsi_last_bb (bb);
1987 gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
1988
1989 gcc_assert (single_succ_p (bb));
1990
1991 /* Make a new basic block where false branch will take place. */
1992 edge false_edge = split_block (bb, cond);
1993 false_edge->flags = EDGE_FALSE_VALUE;
1994 false_edge->probability = prob.invert ();
1995
1996 edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
1997 true_edge->probability = prob;
1998
1999 return false_edge->dest;
2000}
2001
2002/* Emit step-by-step code to select a case for the value of INDEX.
2003 The thus generated decision tree follows the form of the
2004 case-node binary tree NODE, whose nodes represent test conditions.
2005 DEFAULT_PROB is probability of cases leading to default BB.
2006 INDEX_TYPE is the type of the index of the switch. */
2007
2008basic_block
2009switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
2010 case_tree_node *node,
2011 profile_probability default_prob,
2012 tree index_type)
2013{
2014 /* If node is null, we are done. */
2015 if (node == NULL)
2016 return bb;
2017
2018 /* Branch to a label where we will handle it later. */
2019 basic_block test_bb = split_edge (single_succ_edge (bb));
2020 redirect_edge_succ (single_pred_edge (test_bb),
2021 single_succ_edge (bb)->dest);
2022
2023 profile_probability probability
2024 = (node->m_right
2025 ? node->m_right->m_c->m_subtree_prob : profile_probability::never ());
2026 probability = ((probability + default_prob.apply_scale (1, 2))
2027 / (node->m_c->m_subtree_prob + default_prob));
2028 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (), GT_EXPR,
2029 test_bb, probability);
2030 default_prob = default_prob.apply_scale (1, 2);
2031
2032 /* Value belongs to this node or to the left-hand subtree. */
2033 probability = node->m_c->m_prob /
2034 (node->m_c->m_subtree_prob + default_prob);
2035 bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (), GE_EXPR,
2036 node->m_c->m_case_bb, probability);
2037
2038 /* Handle the left-hand subtree. */
2039 bb = emit_case_nodes (bb, index, node->m_left,
2040 default_prob, index_type);
2041
2042 /* If the left-hand subtree fell through,
2043 don't let it fall into the right-hand subtree. */
2044 if (m_default_bb)
2045 emit_jump (bb, m_default_bb);
2046
2047 bb = emit_case_nodes (test_bb, index, node->m_right,
2048 default_prob, index_type);
2049
2050 return bb;
2051}
2052
2053/* The main function of the pass scans statements for switches and invokes
2054 process_switch on them. */
2055
2056namespace {
2057
2058const pass_data pass_data_convert_switch =
2059{
2060 GIMPLE_PASS, /* type */
2061 "switchconv", /* name */
2062 OPTGROUP_NONE, /* optinfo_flags */
2063 TV_TREE_SWITCH_CONVERSION, /* tv_id */
2064 ( PROP_cfg | PROP_ssa ), /* properties_required */
2065 0, /* properties_provided */
2066 0, /* properties_destroyed */
2067 0, /* todo_flags_start */
2068 TODO_update_ssa, /* todo_flags_finish */
2069};
2070
2071class pass_convert_switch : public gimple_opt_pass
2072{
2073public:
2074 pass_convert_switch (gcc::context *ctxt)
2075 : gimple_opt_pass (pass_data_convert_switch, ctxt)
2076 {}
2077
2078 /* opt_pass methods: */
2079 virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
2080 virtual unsigned int execute (function *);
2081
2082}; // class pass_convert_switch
2083
2084unsigned int
2085pass_convert_switch::execute (function *fun)
2086{
2087 basic_block bb;
2088 bool cfg_altered = false;
2089
2090 FOR_EACH_BB_FN (bb, fun)
2091 {
2092 gimple *stmt = last_stmt (bb);
2093 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
2094 {
2095 if (dump_file)
2096 {
2097 expanded_location loc = expand_location (gimple_location (stmt));
2098
2099 fprintf (dump_file, "beginning to process the following "
2100 "SWITCH statement (%s:%d) : ------- \n",
2101 loc.file, loc.line);
2102 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2103 putc ('\n', dump_file);
2104 }
2105
2106 switch_conversion sconv;
2107 sconv.expand (as_a <gswitch *> (stmt));
2108 cfg_altered |= sconv.m_cfg_altered;
2109 if (!sconv.m_reason)
2110 {
2111 if (dump_file)
2112 {
2113 fputs ("Switch converted\n", dump_file);
2114 fputs ("--------------------------------\n", dump_file);
2115 }
2116
2117 /* Make no effort to update the post-dominator tree.
2118 It is actually not that hard for the transformations
2119 we have performed, but it is not supported
2120 by iterate_fix_dominators. */
2121 free_dominance_info (CDI_POST_DOMINATORS);
2122 }
2123 else
2124 {
2125 if (dump_file)
2126 {
2127 fputs ("Bailing out - ", dump_file);
2128 fputs (sconv.m_reason, dump_file);
2129 fputs ("\n--------------------------------\n", dump_file);
2130 }
2131 }
2132 }
2133 }
2134
2135 return cfg_altered ? TODO_cleanup_cfg : 0;;
2136}
2137
2138} // anon namespace
2139
2140gimple_opt_pass *
2141make_pass_convert_switch (gcc::context *ctxt)
2142{
2143 return new pass_convert_switch (ctxt);
9dc3d6a9
ML
2144}
2145
2146/* The main function of the pass scans statements for switches and invokes
2147 process_switch on them. */
2148
2149namespace {
2150
eb63c01f 2151template <bool O0> class pass_lower_switch: public gimple_opt_pass
9dc3d6a9 2152{
eb63c01f
ML
2153public:
2154 pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
2155
2156 static const pass_data data;
2157 opt_pass *
2158 clone ()
2159 {
2160 return new pass_lower_switch<O0> (m_ctxt);
2161 }
2162
2163 virtual bool
2164 gate (function *)
2165 {
2166 return !O0 || !optimize;
2167 }
2168
2169 virtual unsigned int execute (function *fun);
2170}; // class pass_lower_switch
2171
2172template <bool O0>
2173const pass_data pass_lower_switch<O0>::data = {
2174 GIMPLE_PASS, /* type */
2175 O0 ? "switchlower_O0" : "switchlower", /* name */
9dc3d6a9
ML
2176 OPTGROUP_NONE, /* optinfo_flags */
2177 TV_TREE_SWITCH_LOWERING, /* tv_id */
2178 ( PROP_cfg | PROP_ssa ), /* properties_required */
2179 0, /* properties_provided */
2180 0, /* properties_destroyed */
2181 0, /* todo_flags_start */
2182 TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
2183};
2184
eb63c01f 2185template <bool O0>
9dc3d6a9 2186unsigned int
eb63c01f 2187pass_lower_switch<O0>::execute (function *fun)
9dc3d6a9
ML
2188{
2189 basic_block bb;
2190 bool expanded = false;
2191
dc223ad4
ML
2192 auto_vec<gimple *> switch_statements;
2193 switch_statements.create (1);
2194
9dc3d6a9
ML
2195 FOR_EACH_BB_FN (bb, fun)
2196 {
2197 gimple *stmt = last_stmt (bb);
2198 if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
dc223ad4
ML
2199 switch_statements.safe_push (stmt);
2200 }
2201
2202 for (unsigned i = 0; i < switch_statements.length (); i++)
2203 {
2204 gimple *stmt = switch_statements[i];
2205 if (dump_file)
9dc3d6a9 2206 {
dc223ad4 2207 expanded_location loc = expand_location (gimple_location (stmt));
9dc3d6a9 2208
dc223ad4
ML
2209 fprintf (dump_file, "beginning to process the following "
2210 "SWITCH statement (%s:%d) : ------- \n",
2211 loc.file, loc.line);
2212 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2213 putc ('\n', dump_file);
2214 }
9dc3d6a9 2215
dc223ad4
ML
2216 gswitch *swtch = dyn_cast<gswitch *> (stmt);
2217 if (swtch)
2218 {
2219 switch_decision_tree dt (swtch);
2220 expanded |= dt.analyze_switch_statement ();
9dc3d6a9
ML
2221 }
2222 }
2223
2224 if (expanded)
2225 {
2226 free_dominance_info (CDI_DOMINATORS);
2227 free_dominance_info (CDI_POST_DOMINATORS);
2228 mark_virtual_operands_for_renaming (cfun);
2229 }
2230
2231 return 0;
2232}
2233
2234} // anon namespace
2235
2236gimple_opt_pass *
eb63c01f 2237make_pass_lower_switch_O0 (gcc::context *ctxt)
9dc3d6a9 2238{
eb63c01f 2239 return new pass_lower_switch<true> (ctxt);
9dc3d6a9 2240}
eb63c01f
ML
2241gimple_opt_pass *
2242make_pass_lower_switch (gcc::context *ctxt)
9dc3d6a9 2243{
eb63c01f 2244 return new pass_lower_switch<false> (ctxt);
9dc3d6a9
ML
2245}
2246
9dc3d6a9 2247