Branch data Line data Source code
1 : : /* Lower GIMPLE_SWITCH expressions to something more efficient than
2 : : a jump table.
3 : : Copyright (C) 2006-2025 Free Software Foundation, Inc.
4 : :
5 : : This file is part of GCC.
6 : :
7 : : GCC is free software; you can redistribute it and/or modify it
8 : : under the terms of the GNU General Public License as published by the
9 : : Free Software Foundation; either version 3, or (at your option) any
10 : : later version.
11 : :
12 : : GCC is distributed in the hope that it will be useful, but WITHOUT
13 : : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 : : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 : : for more details.
16 : :
17 : : You should have received a copy of the GNU General Public License
18 : : along with GCC; see the file COPYING3. If not, write to the Free
19 : : Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
20 : : 02110-1301, USA. */
21 : :
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"
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 "fold-const.h"
40 : : #include "varasm.h"
41 : : #include "stor-layout.h"
42 : : #include "cfganal.h"
43 : : #include "gimplify.h"
44 : : #include "gimple-iterator.h"
45 : : #include "gimplify-me.h"
46 : : #include "gimple-fold.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"
53 : : #include "gimple-range.h"
54 : : #include "tree-cfgcleanup.h"
55 : : #include "hwint.h"
56 : : #include "internal-fn.h"
57 : : #include "diagnostic-core.h"
58 : :
59 : : /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
60 : : type in the GIMPLE type system that is language-independent? */
61 : : #include "langhooks.h"
62 : :
63 : : #include "tree-switch-conversion.h"
64 : :
65 : : using namespace tree_switch_conversion;
66 : :
67 : : /* Does the target have optabs needed to efficiently compute exact base two
68 : : logarithm of a variable with type TYPE?
69 : :
70 : : If yes, returns TYPE. If no, returns NULL_TREE. May also return another
71 : : type. This indicates that logarithm of the variable can be computed but
72 : : only after it is converted to this type.
73 : :
74 : : Also see gen_log2. */
75 : :
76 : : static tree
77 : 7047 : can_log2 (tree type, optimization_type opt_type)
78 : : {
79 : : /* Check if target supports FFS for given type. */
80 : 7047 : if (direct_internal_fn_supported_p (IFN_FFS, type, opt_type))
81 : : return type;
82 : :
83 : : /* Check if target supports FFS for some type we could convert to. */
84 : 1458 : int prec = TYPE_PRECISION (type);
85 : 1458 : int i_prec = TYPE_PRECISION (integer_type_node);
86 : 1458 : int li_prec = TYPE_PRECISION (long_integer_type_node);
87 : 1458 : int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
88 : 1458 : tree new_type;
89 : 1458 : if (prec <= i_prec
90 : 1458 : && direct_internal_fn_supported_p (IFN_FFS, integer_type_node, opt_type))
91 : 1448 : new_type = integer_type_node;
92 : 10 : else if (prec <= li_prec
93 : 10 : && direct_internal_fn_supported_p (IFN_FFS, long_integer_type_node,
94 : : opt_type))
95 : 0 : new_type = long_integer_type_node;
96 : 10 : else if (prec <= lli_prec
97 : 10 : && direct_internal_fn_supported_p (IFN_FFS,
98 : : long_long_integer_type_node,
99 : : opt_type))
100 : 0 : new_type = long_long_integer_type_node;
101 : : else
102 : 10 : return NULL_TREE;
103 : : return new_type;
104 : : }
105 : :
106 : : /* Assume that OP is a power of two. Build a sequence of gimple statements
107 : : efficiently computing the base two logarithm of OP using special optabs.
108 : : Return the ssa name represeting the result of the logarithm through RESULT.
109 : :
110 : : Before computing the logarithm, OP may have to be converted to another type.
111 : : This should be specified in TYPE. Use can_log2 to decide what this type
112 : : should be.
113 : :
114 : : Should only be used if can_log2 doesn't reject the type of OP. */
115 : :
116 : : static gimple_seq
117 : 21 : gen_log2 (tree op, location_t loc, tree *result, tree type)
118 : : {
119 : 21 : gimple_seq stmts = NULL;
120 : 21 : gimple_stmt_iterator gsi = gsi_last (stmts);
121 : :
122 : 21 : tree orig_type = TREE_TYPE (op);
123 : 21 : tree tmp1;
124 : 21 : if (type != orig_type)
125 : 4 : tmp1 = gimple_convert (&gsi, false, GSI_NEW_STMT, loc, type, op);
126 : : else
127 : : tmp1 = op;
128 : : /* Build FFS (op) - 1. */
129 : 21 : tree tmp2 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, IFN_FFS, orig_type,
130 : : tmp1);
131 : 21 : tree tmp3 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, MINUS_EXPR,
132 : : orig_type, tmp2, build_one_cst (orig_type));
133 : 21 : *result = tmp3;
134 : 21 : return stmts;
135 : : }
136 : :
137 : : /* Build a sequence of gimple statements checking that OP is a power of 2.
138 : : Return the result as a boolean_type_node ssa name through RESULT. Assumes
139 : : that OP's value will be non-negative. The generated check may give
140 : : arbitrary answer for negative values. */
141 : :
142 : : static gimple_seq
143 : 21 : gen_pow2p (tree op, location_t loc, tree *result)
144 : : {
145 : 21 : gimple_seq stmts = NULL;
146 : 21 : gimple_stmt_iterator gsi = gsi_last (stmts);
147 : :
148 : 21 : tree type = TREE_TYPE (op);
149 : 21 : tree utype = unsigned_type_for (type);
150 : :
151 : : /* Build (op ^ (op - 1)) > (op - 1). */
152 : 21 : tree tmp1;
153 : 21 : if (types_compatible_p (type, utype))
154 : : tmp1 = op;
155 : : else
156 : 13 : tmp1 = gimple_convert (&gsi, false, GSI_NEW_STMT, loc, utype, op);
157 : 21 : tree tmp2 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, MINUS_EXPR, utype,
158 : : tmp1, build_one_cst (utype));
159 : 21 : tree tmp3 = gimple_build (&gsi, false, GSI_NEW_STMT, loc, BIT_XOR_EXPR,
160 : : utype, tmp1, tmp2);
161 : 21 : *result = gimple_build (&gsi, false, GSI_NEW_STMT, loc, GT_EXPR,
162 : : boolean_type_node, tmp3, tmp2);
163 : :
164 : 21 : return stmts;
165 : : }
166 : :
167 : :
168 : : /* Constructor. */
169 : :
170 : 28936 : switch_conversion::switch_conversion (): m_final_bb (NULL),
171 : 28936 : m_constructors (NULL), m_default_values (NULL),
172 : 28936 : m_arr_ref_first (NULL), m_arr_ref_last (NULL),
173 : 28936 : m_reason (NULL), m_default_case_nonstandard (false), m_cfg_altered (false),
174 : 28936 : m_exp_index_transform_applied (false)
175 : : {
176 : 28936 : }
177 : :
178 : : /* Collection information about SWTCH statement. */
179 : :
180 : : void
181 : 28936 : switch_conversion::collect (gswitch *swtch)
182 : : {
183 : 28936 : unsigned int branch_num = gimple_switch_num_labels (swtch);
184 : 28936 : tree min_case, max_case;
185 : 28936 : unsigned int i;
186 : 28936 : edge e, e_default, e_first;
187 : 28936 : edge_iterator ei;
188 : :
189 : 28936 : m_switch = swtch;
190 : :
191 : : /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
192 : : is a default label which is the first in the vector.
193 : : Collect the bits we can deduce from the CFG. */
194 : 28936 : m_index_expr = gimple_switch_index (swtch);
195 : 28936 : m_switch_bb = gimple_bb (swtch);
196 : 28936 : e_default = gimple_switch_default_edge (cfun, swtch);
197 : 28936 : m_default_bb = e_default->dest;
198 : 28936 : m_default_prob = e_default->probability;
199 : :
200 : : /* Get upper and lower bounds of case values, and the covered range. */
201 : 28936 : min_case = gimple_switch_label (swtch, 1);
202 : 28936 : max_case = gimple_switch_label (swtch, branch_num - 1);
203 : :
204 : 28936 : m_range_min = CASE_LOW (min_case);
205 : 28936 : if (CASE_HIGH (max_case) != NULL_TREE)
206 : 2689 : m_range_max = CASE_HIGH (max_case);
207 : : else
208 : 26247 : m_range_max = CASE_LOW (max_case);
209 : :
210 : 28936 : m_contiguous_range = true;
211 : 28936 : tree last = CASE_HIGH (min_case) ? CASE_HIGH (min_case) : m_range_min;
212 : 92994 : for (i = 2; i < branch_num; i++)
213 : : {
214 : 79942 : tree elt = gimple_switch_label (swtch, i);
215 : 79943 : if (wi::to_wide (last) + 1 != wi::to_wide (CASE_LOW (elt)))
216 : : {
217 : 15884 : m_contiguous_range = false;
218 : 15884 : break;
219 : : }
220 : 64058 : last = CASE_HIGH (elt) ? CASE_HIGH (elt) : CASE_LOW (elt);
221 : : }
222 : :
223 : 28936 : if (m_contiguous_range)
224 : 13052 : e_first = gimple_switch_edge (cfun, swtch, 1);
225 : : else
226 : : e_first = e_default;
227 : :
228 : : /* See if there is one common successor block for all branch
229 : : targets. If it exists, record it in FINAL_BB.
230 : : Start with the destination of the first non-default case
231 : : if the range is contiguous and default case otherwise as
232 : : guess or its destination in case it is a forwarder block. */
233 : 28936 : if (! single_pred_p (e_first->dest))
234 : 8524 : m_final_bb = e_first->dest;
235 : 20412 : else if (single_succ_p (e_first->dest)
236 : 17199 : && ! single_pred_p (single_succ (e_first->dest)))
237 : 12101 : m_final_bb = single_succ (e_first->dest);
238 : : /* Require that all switch destinations are either that common
239 : : FINAL_BB or a forwarder to it, except for the default
240 : : case if contiguous range. */
241 : 28936 : auto_vec<edge, 10> fw_edges;
242 : 28936 : m_uniq = 0;
243 : 28936 : if (m_final_bb)
244 : 101080 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
245 : : {
246 : 89369 : edge phi_e = nullptr;
247 : 89369 : if (e->dest == m_final_bb)
248 : 13522 : phi_e = e;
249 : 75847 : else if (single_pred_p (e->dest)
250 : 157214 : && single_succ_p (e->dest)
251 : 143692 : && single_succ (e->dest) == m_final_bb)
252 : 64766 : phi_e = single_succ_edge (e->dest);
253 : 89369 : if (phi_e)
254 : : {
255 : 78288 : if (e == e_default)
256 : : ;
257 : 60241 : else if (phi_e == e || empty_block_p (e->dest))
258 : : {
259 : : /* For empty blocks consider forwarders with equal
260 : : PHI arguments in m_final_bb as unique. */
261 : : unsigned i;
262 : 109081 : for (i = 0; i < fw_edges.length (); ++i)
263 : 93937 : if (phi_alternatives_equal (m_final_bb, fw_edges[i], phi_e))
264 : : break;
265 : 32164 : if (i == fw_edges.length ())
266 : : {
267 : : /* But limit the above possibly quadratic search. */
268 : 15144 : if (fw_edges.length () < 10)
269 : 6768 : fw_edges.quick_push (phi_e);
270 : 15144 : m_uniq++;
271 : : }
272 : : }
273 : : else
274 : 44159 : m_uniq++;
275 : 80455 : continue;
276 : 78288 : }
277 : :
278 : 11081 : if (e == e_default && m_contiguous_range)
279 : : {
280 : 2167 : m_default_case_nonstandard = true;
281 : 2167 : continue;
282 : : }
283 : :
284 : 8914 : m_final_bb = NULL;
285 : 8914 : break;
286 : : }
287 : :
288 : : /* When there's not a single common successor block conservatively
289 : : approximate the number of unique non-default targets. */
290 : 28936 : if (!m_final_bb)
291 : 34450 : m_uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
292 : :
293 : 28936 : m_range_size
294 : 28936 : = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
295 : :
296 : : /* Get a count of the number of case labels. Single-valued case labels
297 : : simply count as one, but a case range counts double, since it may
298 : : require two compares if it gets lowered as a branching tree. */
299 : 28936 : m_count = 0;
300 : 209087 : for (i = 1; i < branch_num; i++)
301 : : {
302 : 180151 : tree elt = gimple_switch_label (swtch, i);
303 : 180151 : m_count++;
304 : 180151 : if (CASE_HIGH (elt)
305 : 180151 : && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
306 : 12759 : m_count++;
307 : : }
308 : 28936 : }
309 : :
310 : : /* Check that the "exponential index transform" can be applied to this switch.
311 : :
312 : : See comment of the exp_index_transform function for details about this
313 : : transformation.
314 : :
315 : : We want:
316 : : - This form of the switch is more efficient
317 : : - Cases are powers of 2
318 : :
319 : : Expects that SWTCH has at least one case. */
320 : :
321 : : bool
322 : 7047 : switch_conversion::is_exp_index_transform_viable (gswitch *swtch)
323 : : {
324 : 7047 : tree index = gimple_switch_index (swtch);
325 : 7047 : tree index_type = TREE_TYPE (index);
326 : 7047 : basic_block swtch_bb = gimple_bb (swtch);
327 : 7047 : unsigned num_labels = gimple_switch_num_labels (swtch);
328 : :
329 : 7047 : optimization_type opt_type = bb_optimization_type (swtch_bb);
330 : 7047 : m_exp_index_transform_log2_type = can_log2 (index_type, opt_type);
331 : 7047 : if (!m_exp_index_transform_log2_type)
332 : : return false;
333 : :
334 : : /* Check that each case label corresponds only to one value
335 : : (no case 1..3). */
336 : : unsigned i;
337 : 53807 : for (i = 1; i < num_labels; i++)
338 : : {
339 : 47233 : tree label = gimple_switch_label (swtch, i);
340 : 47233 : if (CASE_HIGH (label))
341 : : return false;
342 : : }
343 : :
344 : : /* Check that each label is nonnegative and a power of 2. */
345 : 9764 : for (i = 1; i < num_labels; i++)
346 : : {
347 : 9699 : tree label = gimple_switch_label (swtch, i);
348 : 9699 : wide_int label_wi = wi::to_wide (CASE_LOW (label));
349 : 9699 : if (!wi::ge_p (label_wi, 0, TYPE_SIGN (index_type)))
350 : : return false;
351 : 9600 : if (wi::exact_log2 (label_wi) == -1)
352 : : return false;
353 : 9699 : }
354 : :
355 : 65 : if (dump_file)
356 : 12 : fprintf (dump_file, "Exponential index transform viable\n");
357 : :
358 : : return true;
359 : : }
360 : :
361 : : /* Perform the "exponential index transform".
362 : :
363 : : Assume that cases of SWTCH are powers of 2. The transformation replaces the
364 : : cases by their exponents (2^k -> k). It also inserts a statement that
365 : : computes the exponent of the original index variable (basically taking the
366 : : logarithm) and then sets the result as the new index variable.
367 : :
368 : : The transformation also inserts a conditional statement checking that the
369 : : incoming original index variable is a power of 2 with the false edge leading
370 : : to the default case.
371 : :
372 : : The exponential index transform shrinks the range of case numbers which
373 : : helps switch conversion convert switches it otherwise could not.
374 : :
375 : : Consider for example:
376 : :
377 : : switch (i)
378 : : {
379 : : case (1 << 0): return 0;
380 : : case (1 << 1): return 1;
381 : : case (1 << 2): return 2;
382 : : ...
383 : : case (1 << 30): return 30;
384 : : default: return 31;
385 : : }
386 : :
387 : : First, exponential index transform gets applied. Since each case becomes
388 : : case x: return x;, the rest of switch conversion is then able to get rid of
389 : : the switch statement.
390 : :
391 : : if (i is power of 2)
392 : : return log2 (i);
393 : : else
394 : : return 31;
395 : :
396 : : */
397 : :
398 : : void
399 : 21 : switch_conversion::exp_index_transform (gswitch *swtch)
400 : : {
401 : 21 : if (dump_file)
402 : 11 : fprintf (dump_file, "Applying exponential index transform\n");
403 : :
404 : 21 : tree index = gimple_switch_index (swtch);
405 : 21 : tree index_type = TREE_TYPE (index);
406 : 21 : basic_block swtch_bb = gimple_bb (swtch);
407 : 21 : unsigned num_labels = gimple_switch_num_labels (swtch);
408 : :
409 : : /* Insert a cond stmt that checks if the index variable is a power of 2. */
410 : 21 : gimple_stmt_iterator gsi = gsi_for_stmt (swtch);
411 : 21 : gsi_prev (&gsi);
412 : 21 : gimple *foo = gsi_stmt (gsi);
413 : 21 : edge new_edge1 = split_block (swtch_bb, foo);
414 : :
415 : 21 : swtch_bb = new_edge1->dest;
416 : 21 : basic_block cond_bb = new_edge1->src;
417 : 21 : new_edge1->flags |= EDGE_TRUE_VALUE;
418 : 21 : new_edge1->flags &= ~EDGE_FALLTHRU;
419 : 21 : new_edge1->probability = profile_probability::even ();
420 : :
421 : 21 : basic_block default_bb = gimple_switch_default_bb (cfun, swtch);
422 : 21 : edge new_edge2 = make_edge (cond_bb, default_bb, EDGE_FALSE_VALUE);
423 : 21 : new_edge2->probability = profile_probability::even ();
424 : :
425 : 21 : tree tmp;
426 : 21 : gimple_seq stmts = gen_pow2p (index, UNKNOWN_LOCATION, &tmp);
427 : 21 : gsi = gsi_last_bb (cond_bb);
428 : 21 : gsi_insert_seq_after (&gsi, stmts, GSI_LAST_NEW_STMT);
429 : 21 : gcond *stmt_cond = gimple_build_cond (NE_EXPR, tmp, boolean_false_node,
430 : : NULL, NULL);
431 : 21 : gsi_insert_after (&gsi, stmt_cond, GSI_NEW_STMT);
432 : :
433 : : /* We just added an edge going to default bb so fix PHI nodes in that bb:
434 : : For each PHI add new PHI arg. It will be the same arg as when comming to
435 : : the default bb from the switch bb. */
436 : 21 : edge default_edge = find_edge (swtch_bb, default_bb);
437 : 21 : for (gphi_iterator gsi = gsi_start_phis (default_bb);
438 : 33 : !gsi_end_p (gsi); gsi_next (&gsi))
439 : : {
440 : 12 : gphi *phi = gsi.phi ();
441 : 12 : tree arg = PHI_ARG_DEF_FROM_EDGE (phi, default_edge);
442 : 12 : location_t loc = gimple_phi_arg_location_from_edge (phi, default_edge);
443 : 12 : add_phi_arg (phi, arg, new_edge2, loc);
444 : : }
445 : :
446 : : /* Insert a sequence of stmts that takes the log of the index variable. */
447 : 21 : stmts = gen_log2 (index, UNKNOWN_LOCATION, &tmp,
448 : : m_exp_index_transform_log2_type);
449 : 21 : gsi = gsi_after_labels (swtch_bb);
450 : 21 : gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
451 : :
452 : : /* Use the result of the logarithm as the new index variable. */
453 : 21 : gimple_switch_set_index (swtch, tmp);
454 : 21 : update_stmt (swtch);
455 : :
456 : : /* Replace each case number with its logarithm. */
457 : 21 : unsigned i;
458 : 134 : for (i = 1; i < num_labels; i++)
459 : : {
460 : 113 : tree label = gimple_switch_label (swtch, i);
461 : 226 : CASE_LOW (label) = build_int_cst (index_type,
462 : 113 : tree_log2 (CASE_LOW (label)));
463 : : }
464 : :
465 : : /* Fix the dominator tree, if it is available. */
466 : 21 : if (dom_info_available_p (CDI_DOMINATORS))
467 : : {
468 : : /* Analysis of how dominators should look after we add the edge E going
469 : : from the cond block to the default block.
470 : :
471 : : 1 For the blocks between the switch block and the final block
472 : : (excluding the final block itself): They had the switch block as
473 : : their immediate dominator. That shouldn't change.
474 : :
475 : : 2 The final block may now have the switch block or the cond block as
476 : : its immediate dominator. There's no easy way of knowing (consider
477 : : two cases where in both m_default_case_nonstandard = true, in one a
478 : : path through default intersects the final block and in one all paths
479 : : through default avoid the final block but intersect a successor of the
480 : : final block).
481 : :
482 : : 3 Other blocks that had the switch block as their immediate dominator
483 : : should now have the cond block as their immediate dominator.
484 : :
485 : : 4 Immediate dominators of the rest of the blocks shouldn't change.
486 : :
487 : : Reasoning for 3 and 4:
488 : :
489 : : We'll only consider blocks that do not fall into 1 or 2.
490 : :
491 : : Consider a block X whose original imm dom was the switch block. All
492 : : paths to X must also intersect the cond block since it's the only
493 : : pred of the switch block. The final block doesn't dominate X so at
494 : : least one path P must lead through the default block. Let P' be P but
495 : : instead of going through the switch block, take E. The switch block
496 : : doesn't dominate X so its imm dom must now be the cond block.
497 : :
498 : : Consider a block X whose original imm dom was Y != the switch block.
499 : : We only added an edge so all original paths to X are still present.
500 : : So X gained no new dominators. Observe that Y still dominates X.
501 : : There would have to be a path that avoids Y otherwise. But any block
502 : : we can avoid now except for the switch block we were able to avoid
503 : : before adding E. */
504 : :
505 : 21 : redirect_immediate_dominators (CDI_DOMINATORS, swtch_bb, cond_bb);
506 : :
507 : 21 : edge e;
508 : 21 : edge_iterator ei;
509 : 155 : FOR_EACH_EDGE (e, ei, swtch_bb->succs)
510 : : {
511 : 134 : basic_block bb = e->dest;
512 : 134 : if (bb == m_final_bb || bb == default_bb)
513 : 30 : continue;
514 : 104 : set_immediate_dominator (CDI_DOMINATORS, bb, swtch_bb);
515 : : }
516 : :
517 : 21 : vec<basic_block> v;
518 : 21 : v.create (1);
519 : 21 : v.quick_push (m_final_bb);
520 : 21 : iterate_fix_dominators (CDI_DOMINATORS, v, true);
521 : : }
522 : :
523 : : /* Update information about the switch statement. */
524 : 21 : tree first_label = gimple_switch_label (swtch, 1);
525 : 21 : tree last_label = gimple_switch_label (swtch, num_labels - 1);
526 : :
527 : 21 : m_range_min = CASE_LOW (first_label);
528 : 21 : m_range_max = CASE_LOW (last_label);
529 : 21 : m_index_expr = gimple_switch_index (swtch);
530 : 21 : m_switch_bb = swtch_bb;
531 : :
532 : 21 : m_range_size = int_const_binop (MINUS_EXPR, m_range_max, m_range_min);
533 : :
534 : 21 : m_cfg_altered = true;
535 : :
536 : 21 : m_contiguous_range = true;
537 : 21 : wide_int last_wi = wi::to_wide (CASE_LOW (first_label));
538 : 113 : for (i = 2; i < num_labels; i++)
539 : : {
540 : 92 : tree label = gimple_switch_label (swtch, i);
541 : 92 : wide_int label_wi = wi::to_wide (CASE_LOW (label));
542 : 92 : m_contiguous_range &= wi::eq_p (wi::add (last_wi, 1), label_wi);
543 : 92 : last_wi = label_wi;
544 : 92 : }
545 : :
546 : 21 : m_exp_index_transform_applied = true;
547 : 21 : }
548 : :
549 : : /* Checks whether the range given by individual case statements of the switch
550 : : switch statement isn't too big and whether the number of branches actually
551 : : satisfies the size of the new array. */
552 : :
553 : : bool
554 : 6982 : switch_conversion::check_range ()
555 : : {
556 : 6982 : gcc_assert (m_range_size);
557 : 6982 : if (!tree_fits_uhwi_p (m_range_size))
558 : : {
559 : 18 : m_reason = "index range way too large or otherwise unusable";
560 : 18 : return false;
561 : : }
562 : :
563 : 6964 : if (tree_to_uhwi (m_range_size)
564 : 6964 : > ((unsigned) m_count * param_switch_conversion_branch_ratio))
565 : : {
566 : 718 : m_reason = "the maximum range-branch ratio exceeded";
567 : 718 : return false;
568 : : }
569 : :
570 : : return true;
571 : : }
572 : :
573 : : /* Checks whether all but the final BB basic blocks are empty. */
574 : :
575 : : bool
576 : 6311 : switch_conversion::check_all_empty_except_final ()
577 : : {
578 : 6311 : edge e, e_default = find_edge (m_switch_bb, m_default_bb);
579 : 6311 : edge_iterator ei;
580 : :
581 : 20345 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
582 : : {
583 : 19623 : if (e->dest == m_final_bb)
584 : 4279 : continue;
585 : :
586 : 15344 : if (!empty_block_p (e->dest))
587 : : {
588 : 6836 : if (m_contiguous_range && e == e_default)
589 : : {
590 : 1247 : m_default_case_nonstandard = true;
591 : 1247 : continue;
592 : : }
593 : :
594 : 5589 : m_reason = "bad case - a non-final BB not empty";
595 : 5589 : return false;
596 : : }
597 : : }
598 : :
599 : : return true;
600 : : }
601 : :
602 : : /* This function checks whether all required values in phi nodes in final_bb
603 : : are constants. Required values are those that correspond to a basic block
604 : : which is a part of the examined switch statement. It returns true if the
605 : : phi nodes are OK, otherwise false. */
606 : :
607 : : bool
608 : 722 : switch_conversion::check_final_bb ()
609 : : {
610 : 722 : gphi_iterator gsi;
611 : :
612 : 722 : m_phi_count = 0;
613 : 1432 : for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
614 : : {
615 : 795 : gphi *phi = gsi.phi ();
616 : 795 : unsigned int i;
617 : :
618 : 1590 : if (virtual_operand_p (gimple_phi_result (phi)))
619 : 17 : continue;
620 : :
621 : 778 : m_phi_count++;
622 : :
623 : 9559 : for (i = 0; i < gimple_phi_num_args (phi); i++)
624 : : {
625 : 8866 : basic_block bb = gimple_phi_arg_edge (phi, i)->src;
626 : :
627 : 8866 : if (bb == m_switch_bb
628 : 25720 : || (single_pred_p (bb)
629 : 8073 : && single_pred (bb) == m_switch_bb
630 : 7911 : && (!m_default_case_nonstandard
631 : 479 : || empty_block_p (bb))))
632 : : {
633 : 8663 : tree reloc, val;
634 : 8663 : const char *reason = NULL;
635 : :
636 : 8663 : val = gimple_phi_arg_def (phi, i);
637 : 8663 : if (!is_gimple_ip_invariant (val))
638 : : reason = "non-invariant value from a case";
639 : : else
640 : : {
641 : 8626 : reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
642 : 8626 : if ((flag_pic && reloc != null_pointer_node)
643 : 8561 : || (!flag_pic && reloc == NULL_TREE))
644 : : {
645 : 65 : if (reloc)
646 : : reason
647 : : = "value from a case would need runtime relocations";
648 : : else
649 : : reason
650 : : = "value from a case is not a valid initializer";
651 : : }
652 : : }
653 : : if (reason)
654 : : {
655 : : /* For contiguous range, we can allow non-constant
656 : : or one that needs relocation, as long as it is
657 : : only reachable from the default case. */
658 : 102 : if (bb == m_switch_bb)
659 : 86 : bb = m_final_bb;
660 : 102 : if (!m_contiguous_range || bb != m_default_bb)
661 : : {
662 : 85 : m_reason = reason;
663 : 85 : return false;
664 : : }
665 : :
666 : 17 : unsigned int branch_num = gimple_switch_num_labels (m_switch);
667 : 116 : for (unsigned int i = 1; i < branch_num; i++)
668 : : {
669 : 99 : if (gimple_switch_label_bb (cfun, m_switch, i) == bb)
670 : : {
671 : 0 : m_reason = reason;
672 : 0 : return false;
673 : : }
674 : : }
675 : 17 : m_default_case_nonstandard = true;
676 : : }
677 : : }
678 : : }
679 : : }
680 : :
681 : : return true;
682 : : }
683 : :
684 : : /* The following function allocates default_values, target_{in,out}_names and
685 : : constructors arrays. The last one is also populated with pointers to
686 : : vectors that will become constructors of new arrays. */
687 : :
688 : : void
689 : 637 : switch_conversion::create_temp_arrays ()
690 : : {
691 : 637 : int i;
692 : :
693 : 637 : m_default_values = XCNEWVEC (tree, m_phi_count * 3);
694 : : /* ??? Macros do not support multi argument templates in their
695 : : argument list. We create a typedef to work around that problem. */
696 : 637 : typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
697 : 637 : m_constructors = XCNEWVEC (vec_constructor_elt_gc, m_phi_count);
698 : 637 : m_target_inbound_names = m_default_values + m_phi_count;
699 : 637 : m_target_outbound_names = m_target_inbound_names + m_phi_count;
700 : 1328 : for (i = 0; i < m_phi_count; i++)
701 : 691 : vec_alloc (m_constructors[i], tree_to_uhwi (m_range_size) + 1);
702 : 637 : }
703 : :
704 : : /* Populate the array of default values in the order of phi nodes.
705 : : DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch
706 : : if the range is non-contiguous or the default case has standard
707 : : structure, otherwise it is the first non-default case instead. */
708 : :
709 : : void
710 : 637 : switch_conversion::gather_default_values (tree default_case)
711 : : {
712 : 637 : gphi_iterator gsi;
713 : 637 : basic_block bb = label_to_block (cfun, CASE_LABEL (default_case));
714 : 637 : edge e;
715 : 637 : int i = 0;
716 : :
717 : 637 : gcc_assert (CASE_LOW (default_case) == NULL_TREE
718 : : || m_default_case_nonstandard);
719 : :
720 : 637 : if (bb == m_final_bb)
721 : 210 : e = find_edge (m_switch_bb, bb);
722 : : else
723 : 427 : e = single_succ_edge (bb);
724 : :
725 : 1345 : for (gsi = gsi_start_phis (m_final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
726 : : {
727 : 708 : gphi *phi = gsi.phi ();
728 : 1416 : if (virtual_operand_p (gimple_phi_result (phi)))
729 : 17 : continue;
730 : 691 : tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
731 : 691 : gcc_assert (val);
732 : 691 : m_default_values[i++] = val;
733 : : }
734 : 637 : }
735 : :
736 : : /* The following function populates the vectors in the constructors array with
737 : : future contents of the static arrays. The vectors are populated in the
738 : : order of phi nodes. */
739 : :
740 : : void
741 : 637 : switch_conversion::build_constructors ()
742 : : {
743 : 637 : unsigned i, branch_num = gimple_switch_num_labels (m_switch);
744 : 637 : tree pos = m_range_min;
745 : 637 : tree pos_one = build_int_cst (TREE_TYPE (pos), 1);
746 : :
747 : 8533 : for (i = 1; i < branch_num; i++)
748 : : {
749 : 7896 : tree cs = gimple_switch_label (m_switch, i);
750 : 7896 : basic_block bb = label_to_block (cfun, CASE_LABEL (cs));
751 : 7896 : edge e;
752 : 7896 : tree high;
753 : 7896 : gphi_iterator gsi;
754 : 7896 : int j;
755 : :
756 : 7896 : if (bb == m_final_bb)
757 : 500 : e = find_edge (m_switch_bb, bb);
758 : : else
759 : 7396 : e = single_succ_edge (bb);
760 : 7896 : gcc_assert (e);
761 : :
762 : 11308 : while (tree_int_cst_lt (pos, CASE_LOW (cs)))
763 : : {
764 : : int k;
765 : 8256 : for (k = 0; k < m_phi_count; k++)
766 : : {
767 : 4844 : constructor_elt elt;
768 : :
769 : 4844 : elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
770 : 4844 : if (TYPE_PRECISION (TREE_TYPE (elt.index))
771 : 4844 : > TYPE_PRECISION (sizetype))
772 : 18 : elt.index = fold_convert (sizetype, elt.index);
773 : 4844 : elt.value
774 : 4844 : = unshare_expr_without_location (m_default_values[k]);
775 : 4844 : m_constructors[k]->quick_push (elt);
776 : : }
777 : :
778 : 3412 : pos = int_const_binop (PLUS_EXPR, pos, pos_one);
779 : : }
780 : 7896 : gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
781 : :
782 : 7896 : j = 0;
783 : 7896 : if (CASE_HIGH (cs))
784 : 108 : high = CASE_HIGH (cs);
785 : : else
786 : 7788 : high = CASE_LOW (cs);
787 : 7896 : for (gsi = gsi_start_phis (m_final_bb);
788 : 16316 : !gsi_end_p (gsi); gsi_next (&gsi))
789 : : {
790 : 8420 : gphi *phi = gsi.phi ();
791 : 16840 : if (virtual_operand_p (gimple_phi_result (phi)))
792 : 72 : continue;
793 : 8348 : tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
794 : 8348 : tree low = CASE_LOW (cs);
795 : 8348 : pos = CASE_LOW (cs);
796 : :
797 : 8675 : do
798 : : {
799 : 8675 : constructor_elt elt;
800 : :
801 : 8675 : elt.index = int_const_binop (MINUS_EXPR, pos, m_range_min);
802 : 8675 : if (TYPE_PRECISION (TREE_TYPE (elt.index))
803 : 8675 : > TYPE_PRECISION (sizetype))
804 : 3 : elt.index = fold_convert (sizetype, elt.index);
805 : 8675 : elt.value = unshare_expr_without_location (val);
806 : 8675 : m_constructors[j]->quick_push (elt);
807 : :
808 : 8675 : pos = int_const_binop (PLUS_EXPR, pos, pos_one);
809 : 8675 : } while (!tree_int_cst_lt (high, pos)
810 : 17023 : && tree_int_cst_lt (low, pos));
811 : 8348 : j++;
812 : : }
813 : : }
814 : 637 : }
815 : :
816 : : /* If all values in the constructor vector are products of a linear function
817 : : a * x + b, then return true. When true, COEFF_A and COEFF_B and
818 : : coefficients of the linear function. Note that equal values are special
819 : : case of a linear function with a and b equal to zero. */
820 : :
821 : : bool
822 : 691 : switch_conversion::contains_linear_function_p (vec<constructor_elt, va_gc> *vec,
823 : : wide_int *coeff_a,
824 : : wide_int *coeff_b)
825 : : {
826 : 691 : unsigned int i;
827 : 691 : constructor_elt *elt;
828 : :
829 : 691 : gcc_assert (vec->length () >= 2);
830 : :
831 : : /* Let's try to find any linear function a * x + y that can apply to
832 : : given values. 'a' can be calculated as follows:
833 : :
834 : : a = (y2 - y1) / (x2 - x1) where x2 - x1 = 1 (consecutive case indices)
835 : : a = y2 - y1
836 : :
837 : : and
838 : :
839 : : b = y2 - a * x2
840 : :
841 : : */
842 : :
843 : 691 : tree elt0 = (*vec)[0].value;
844 : 691 : tree elt1 = (*vec)[1].value;
845 : :
846 : 691 : if (TREE_CODE (elt0) != INTEGER_CST || TREE_CODE (elt1) != INTEGER_CST)
847 : : return false;
848 : :
849 : 547 : wide_int range_min
850 : 547 : = wide_int::from (wi::to_wide (m_range_min),
851 : 547 : TYPE_PRECISION (TREE_TYPE (elt0)),
852 : 1641 : TYPE_SIGN (TREE_TYPE (m_range_min)));
853 : 547 : wide_int y1 = wi::to_wide (elt0);
854 : 547 : wide_int y2 = wi::to_wide (elt1);
855 : 547 : wide_int a = y2 - y1;
856 : 547 : wide_int b = y2 - a * (range_min + 1);
857 : :
858 : : /* Verify that all values fulfill the linear function. */
859 : 2138 : FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
860 : : {
861 : 2047 : if (TREE_CODE (elt->value) != INTEGER_CST)
862 : 456 : return false;
863 : :
864 : 2047 : wide_int value = wi::to_wide (elt->value);
865 : 2047 : if (a * range_min + b != value)
866 : 456 : return false;
867 : :
868 : 1591 : ++range_min;
869 : 2047 : }
870 : :
871 : 91 : *coeff_a = a;
872 : 91 : *coeff_b = b;
873 : :
874 : 91 : return true;
875 : 547 : }
876 : :
877 : : /* Return type which should be used for array elements, either TYPE's
878 : : main variant or, for integral types, some smaller integral type
879 : : that can still hold all the constants. */
880 : :
881 : : tree
882 : 600 : switch_conversion::array_value_type (tree type, int num)
883 : : {
884 : 600 : unsigned int i, len = vec_safe_length (m_constructors[num]);
885 : 600 : constructor_elt *elt;
886 : 600 : int sign = 0;
887 : 600 : tree smaller_type;
888 : :
889 : : /* Types with alignments greater than their size can reach here, e.g. out of
890 : : SRA. We couldn't use these as an array component type so get back to the
891 : : main variant first, which, for our purposes, is fine for other types as
892 : : well. */
893 : :
894 : 600 : type = TYPE_MAIN_VARIANT (type);
895 : :
896 : 600 : if (!INTEGRAL_TYPE_P (type)
897 : 600 : || (TREE_CODE (type) == BITINT_TYPE
898 : 0 : && (TYPE_PRECISION (type) > MAX_FIXED_MODE_SIZE
899 : 0 : || TYPE_MODE (type) == BLKmode)))
900 : 144 : return type;
901 : :
902 : 456 : scalar_int_mode type_mode = SCALAR_INT_TYPE_MODE (type);
903 : 456 : scalar_int_mode mode = get_narrowest_mode (type_mode);
904 : 1368 : if (GET_MODE_SIZE (type_mode) <= GET_MODE_SIZE (mode))
905 : : return type;
906 : :
907 : 464 : if (len < (optimize_bb_for_size_p (gimple_bb (m_switch)) ? 2 : 32))
908 : : return type;
909 : :
910 : 2642 : FOR_EACH_VEC_SAFE_ELT (m_constructors[num], i, elt)
911 : : {
912 : 2589 : wide_int cst;
913 : :
914 : 2589 : if (TREE_CODE (elt->value) != INTEGER_CST)
915 : : return type;
916 : :
917 : 2589 : cst = wi::to_wide (elt->value);
918 : 2610 : while (1)
919 : : {
920 : 2612 : unsigned int prec = GET_MODE_BITSIZE (mode);
921 : 2610 : if (prec > HOST_BITS_PER_WIDE_INT)
922 : : return type;
923 : :
924 : 2610 : if (sign >= 0 && cst == wi::zext (cst, prec))
925 : : {
926 : 1411 : if (sign == 0 && cst == wi::sext (cst, prec))
927 : : break;
928 : 457 : sign = 1;
929 : 457 : break;
930 : : }
931 : 1199 : if (sign <= 0 && cst == wi::sext (cst, prec))
932 : : {
933 : : sign = -1;
934 : : break;
935 : : }
936 : :
937 : 23 : if (sign == 1)
938 : : sign = 0;
939 : :
940 : 46 : if (!GET_MODE_WIDER_MODE (mode).exists (&mode)
941 : 48 : || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (type_mode))
942 : : return type;
943 : : }
944 : 2589 : }
945 : :
946 : 53 : if (sign == 0)
947 : 28 : sign = TYPE_UNSIGNED (type) ? 1 : -1;
948 : 53 : smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
949 : 53 : if (GET_MODE_SIZE (type_mode)
950 : 106 : <= GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (smaller_type)))
951 : : return type;
952 : :
953 : : return smaller_type;
954 : : }
955 : :
956 : : /* Create an appropriate array type and declaration and assemble a static
957 : : array variable. Also create a load statement that initializes
958 : : the variable in question with a value from the static array. SWTCH is
959 : : the switch statement being converted, NUM is the index to
960 : : arrays of constructors, default values and target SSA names
961 : : for this particular array. ARR_INDEX_TYPE is the type of the index
962 : : of the new array, PHI is the phi node of the final BB that corresponds
963 : : to the value that will be loaded from the created array. TIDX
964 : : is an ssa name of a temporary variable holding the index for loads from the
965 : : new array. */
966 : :
967 : : void
968 : 691 : switch_conversion::build_one_array (int num, tree arr_index_type,
969 : : gphi *phi, tree tidx)
970 : : {
971 : 691 : tree name;
972 : 691 : gimple *load;
973 : 691 : gimple_stmt_iterator gsi = gsi_for_stmt (m_switch);
974 : 691 : location_t loc = gimple_location (m_switch);
975 : :
976 : 691 : gcc_assert (m_default_values[num]);
977 : :
978 : 691 : name = copy_ssa_name (PHI_RESULT (phi));
979 : 691 : m_target_inbound_names[num] = name;
980 : :
981 : 691 : vec<constructor_elt, va_gc> *constructor = m_constructors[num];
982 : 691 : wide_int coeff_a, coeff_b;
983 : 691 : bool linear_p = contains_linear_function_p (constructor, &coeff_a, &coeff_b);
984 : 691 : tree type;
985 : 691 : if (linear_p
986 : 691 : && (type = range_check_type (TREE_TYPE ((*constructor)[0].value))))
987 : : {
988 : 108 : if (dump_file && coeff_a.to_uhwi () > 0)
989 : 16 : fprintf (dump_file, "Linear transformation with A = %" PRId64
990 : : " and B = %" PRId64 "\n", coeff_a.to_shwi (),
991 : : coeff_b.to_shwi ());
992 : :
993 : : /* We must use type of constructor values. */
994 : 91 : gimple_seq seq = NULL;
995 : 91 : tree tmp = gimple_convert (&seq, type, m_index_expr);
996 : 182 : tree tmp2 = gimple_build (&seq, MULT_EXPR, type,
997 : 91 : wide_int_to_tree (type, coeff_a), tmp);
998 : 182 : tree tmp3 = gimple_build (&seq, PLUS_EXPR, type, tmp2,
999 : 91 : wide_int_to_tree (type, coeff_b));
1000 : 91 : tree tmp4 = gimple_convert (&seq, TREE_TYPE (name), tmp3);
1001 : 91 : gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
1002 : 91 : load = gimple_build_assign (name, tmp4);
1003 : : }
1004 : : else
1005 : : {
1006 : 600 : tree array_type, ctor, decl, value_type, fetch, default_type;
1007 : :
1008 : 600 : default_type = TREE_TYPE (m_default_values[num]);
1009 : 600 : value_type = array_value_type (default_type, num);
1010 : 600 : array_type = build_array_type (value_type, arr_index_type);
1011 : 600 : if (default_type != value_type)
1012 : : {
1013 : : unsigned int i;
1014 : : constructor_elt *elt;
1015 : :
1016 : 3386 : FOR_EACH_VEC_SAFE_ELT (constructor, i, elt)
1017 : 3272 : elt->value = fold_convert (value_type, elt->value);
1018 : : }
1019 : 600 : ctor = build_constructor (array_type, constructor);
1020 : 600 : TREE_CONSTANT (ctor) = true;
1021 : 600 : TREE_STATIC (ctor) = true;
1022 : :
1023 : 600 : decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
1024 : 600 : TREE_STATIC (decl) = 1;
1025 : 600 : DECL_INITIAL (decl) = ctor;
1026 : :
1027 : 600 : DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
1028 : 600 : DECL_ARTIFICIAL (decl) = 1;
1029 : 600 : DECL_IGNORED_P (decl) = 1;
1030 : 600 : TREE_CONSTANT (decl) = 1;
1031 : 600 : TREE_READONLY (decl) = 1;
1032 : 600 : DECL_IGNORED_P (decl) = 1;
1033 : : /* The decl is mergable since we don't take the address ever and
1034 : : just reading from it. */
1035 : 600 : DECL_MERGEABLE (decl) = 1;
1036 : 600 : if (offloading_function_p (cfun->decl))
1037 : 0 : DECL_ATTRIBUTES (decl)
1038 : 0 : = tree_cons (get_identifier ("omp declare target"), NULL_TREE,
1039 : : NULL_TREE);
1040 : 600 : varpool_node::finalize_decl (decl);
1041 : :
1042 : 600 : fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
1043 : : NULL_TREE);
1044 : 600 : if (default_type != value_type)
1045 : : {
1046 : 114 : fetch = fold_convert (default_type, fetch);
1047 : 114 : fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
1048 : : true, GSI_SAME_STMT);
1049 : : }
1050 : 600 : load = gimple_build_assign (name, fetch);
1051 : : }
1052 : :
1053 : 691 : gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1054 : 691 : update_stmt (load);
1055 : 691 : m_arr_ref_last = load;
1056 : 691 : }
1057 : :
1058 : : /* Builds and initializes static arrays initialized with values gathered from
1059 : : the switch statement. Also creates statements that load values from
1060 : : them. */
1061 : :
1062 : : void
1063 : 637 : switch_conversion::build_arrays ()
1064 : : {
1065 : 637 : tree arr_index_type;
1066 : 637 : tree tidx, sub, utype, tidxtype;
1067 : 637 : gimple *stmt;
1068 : 637 : gimple_stmt_iterator gsi;
1069 : 637 : gphi_iterator gpi;
1070 : 637 : int i;
1071 : 637 : location_t loc = gimple_location (m_switch);
1072 : :
1073 : 637 : gsi = gsi_for_stmt (m_switch);
1074 : :
1075 : : /* Make sure we do not generate arithmetics in a subrange. */
1076 : 637 : utype = TREE_TYPE (m_index_expr);
1077 : 637 : if (TREE_TYPE (utype))
1078 : 46 : utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
1079 : 591 : else if (TREE_CODE (utype) == BITINT_TYPE
1080 : 592 : && (TYPE_PRECISION (utype) > MAX_FIXED_MODE_SIZE
1081 : 0 : || TYPE_MODE (utype) == BLKmode))
1082 : 1 : utype = unsigned_type_for (utype);
1083 : : else
1084 : 590 : utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
1085 : 637 : if (TYPE_PRECISION (utype) > TYPE_PRECISION (sizetype))
1086 : 1 : tidxtype = sizetype;
1087 : : else
1088 : : tidxtype = utype;
1089 : :
1090 : 637 : arr_index_type = build_index_type (m_range_size);
1091 : 637 : tidx = make_ssa_name (tidxtype);
1092 : 637 : sub = fold_build2_loc (loc, MINUS_EXPR, utype,
1093 : : fold_convert_loc (loc, utype, m_index_expr),
1094 : : fold_convert_loc (loc, utype, m_range_min));
1095 : 637 : sub = fold_convert (tidxtype, sub);
1096 : 637 : sub = force_gimple_operand_gsi (&gsi, sub,
1097 : : false, NULL, true, GSI_SAME_STMT);
1098 : 637 : stmt = gimple_build_assign (tidx, sub);
1099 : :
1100 : 637 : gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1101 : 637 : update_stmt (stmt);
1102 : 637 : m_arr_ref_first = stmt;
1103 : :
1104 : 637 : for (gpi = gsi_start_phis (m_final_bb), i = 0;
1105 : 1345 : !gsi_end_p (gpi); gsi_next (&gpi))
1106 : : {
1107 : 708 : gphi *phi = gpi.phi ();
1108 : 1416 : if (!virtual_operand_p (gimple_phi_result (phi)))
1109 : 691 : build_one_array (i++, arr_index_type, phi, tidx);
1110 : : else
1111 : : {
1112 : 17 : edge e;
1113 : 17 : edge_iterator ei;
1114 : 21 : FOR_EACH_EDGE (e, ei, m_switch_bb->succs)
1115 : : {
1116 : 21 : if (e->dest == m_final_bb)
1117 : : break;
1118 : 11 : if (!m_default_case_nonstandard
1119 : 4 : || e->dest != m_default_bb)
1120 : : {
1121 : 7 : e = single_succ_edge (e->dest);
1122 : 7 : break;
1123 : : }
1124 : : }
1125 : 17 : gcc_assert (e && e->dest == m_final_bb);
1126 : 17 : m_target_vop = PHI_ARG_DEF_FROM_EDGE (phi, e);
1127 : : }
1128 : : }
1129 : 637 : }
1130 : :
1131 : : /* Generates and appropriately inserts loads of default values at the position
1132 : : given by GSI. Returns the last inserted statement. */
1133 : :
1134 : : gassign *
1135 : 534 : switch_conversion::gen_def_assigns (gimple_stmt_iterator *gsi)
1136 : : {
1137 : 534 : int i;
1138 : 534 : gassign *assign = NULL;
1139 : :
1140 : 1111 : for (i = 0; i < m_phi_count; i++)
1141 : : {
1142 : 577 : tree name = copy_ssa_name (m_target_inbound_names[i]);
1143 : 577 : m_target_outbound_names[i] = name;
1144 : 577 : assign = gimple_build_assign (name, m_default_values[i]);
1145 : 577 : gsi_insert_before (gsi, assign, GSI_SAME_STMT);
1146 : 577 : update_stmt (assign);
1147 : : }
1148 : 534 : return assign;
1149 : : }
1150 : :
1151 : : /* Deletes the unused bbs and edges that now contain the switch statement and
1152 : : its empty branch bbs. BBD is the now dead BB containing
1153 : : the original switch statement, FINAL is the last BB of the converted
1154 : : switch statement (in terms of succession). */
1155 : :
1156 : : void
1157 : 637 : switch_conversion::prune_bbs (basic_block bbd, basic_block final,
1158 : : basic_block default_bb)
1159 : : {
1160 : 637 : edge_iterator ei;
1161 : 637 : edge e;
1162 : :
1163 : 9666 : for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
1164 : : {
1165 : 8392 : basic_block bb;
1166 : 8392 : bb = e->dest;
1167 : 8392 : remove_edge (e);
1168 : 8392 : if (bb != final && bb != default_bb)
1169 : 7663 : delete_basic_block (bb);
1170 : : }
1171 : 637 : delete_basic_block (bbd);
1172 : 637 : }
1173 : :
1174 : : /* Add values to phi nodes in final_bb for the two new edges. E1F is the edge
1175 : : from the basic block loading values from an array and E2F from the basic
1176 : : block loading default values. BBF is the last switch basic block (see the
1177 : : bbf description in the comment below). */
1178 : :
1179 : : void
1180 : 637 : switch_conversion::fix_phi_nodes (edge e1f, edge e2f, basic_block bbf)
1181 : : {
1182 : 637 : gphi_iterator gsi;
1183 : 637 : int i;
1184 : :
1185 : 637 : for (gsi = gsi_start_phis (bbf), i = 0;
1186 : 1345 : !gsi_end_p (gsi); gsi_next (&gsi))
1187 : : {
1188 : 708 : gphi *phi = gsi.phi ();
1189 : 708 : tree inbound, outbound;
1190 : 1416 : if (virtual_operand_p (gimple_phi_result (phi)))
1191 : 17 : inbound = outbound = m_target_vop;
1192 : : else
1193 : : {
1194 : 691 : inbound = m_target_inbound_names[i];
1195 : 691 : outbound = m_target_outbound_names[i++];
1196 : : }
1197 : 708 : add_phi_arg (phi, inbound, e1f, UNKNOWN_LOCATION);
1198 : 708 : if (!m_default_case_nonstandard)
1199 : 590 : add_phi_arg (phi, outbound, e2f, UNKNOWN_LOCATION);
1200 : : }
1201 : 637 : }
1202 : :
1203 : : /* Creates a check whether the switch expression value actually falls into the
1204 : : range given by all the cases. If it does not, the temporaries are loaded
1205 : : with default values instead. */
1206 : :
1207 : : void
1208 : 637 : switch_conversion::gen_inbound_check ()
1209 : : {
1210 : 637 : tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
1211 : 637 : tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
1212 : 637 : tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
1213 : 637 : glabel *label1, *label2, *label3;
1214 : 637 : tree utype, tidx;
1215 : 637 : tree bound;
1216 : :
1217 : 637 : gcond *cond_stmt;
1218 : :
1219 : 637 : gassign *last_assign = NULL;
1220 : 637 : gimple_stmt_iterator gsi;
1221 : 637 : basic_block bb0, bb1, bb2, bbf, bbd;
1222 : 637 : edge e01 = NULL, e02, e21, e1d, e1f, e2f;
1223 : 637 : location_t loc = gimple_location (m_switch);
1224 : :
1225 : 637 : gcc_assert (m_default_values);
1226 : :
1227 : 637 : bb0 = gimple_bb (m_switch);
1228 : :
1229 : 637 : tidx = gimple_assign_lhs (m_arr_ref_first);
1230 : 637 : utype = TREE_TYPE (tidx);
1231 : :
1232 : : /* (end of) block 0 */
1233 : 637 : gsi = gsi_for_stmt (m_arr_ref_first);
1234 : 637 : gsi_next (&gsi);
1235 : :
1236 : 637 : bound = fold_convert_loc (loc, utype, m_range_size);
1237 : 637 : cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
1238 : 637 : gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
1239 : 637 : update_stmt (cond_stmt);
1240 : :
1241 : : /* block 2 */
1242 : 637 : if (!m_default_case_nonstandard)
1243 : : {
1244 : 534 : label2 = gimple_build_label (label_decl2);
1245 : 534 : gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
1246 : 534 : last_assign = gen_def_assigns (&gsi);
1247 : : }
1248 : :
1249 : : /* block 1 */
1250 : 637 : label1 = gimple_build_label (label_decl1);
1251 : 637 : gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
1252 : :
1253 : : /* block F */
1254 : 637 : gsi = gsi_start_bb (m_final_bb);
1255 : 637 : label3 = gimple_build_label (label_decl3);
1256 : 637 : gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
1257 : :
1258 : : /* cfg fix */
1259 : 637 : e02 = split_block (bb0, cond_stmt);
1260 : 637 : bb2 = e02->dest;
1261 : :
1262 : 637 : if (m_default_case_nonstandard)
1263 : : {
1264 : 103 : bb1 = bb2;
1265 : 103 : bb2 = m_default_bb;
1266 : 103 : e01 = e02;
1267 : 103 : e01->flags = EDGE_TRUE_VALUE;
1268 : 103 : e02 = make_edge (bb0, bb2, EDGE_FALSE_VALUE);
1269 : 103 : edge e_default = find_edge (bb1, bb2);
1270 : 103 : for (gphi_iterator gsi = gsi_start_phis (bb2);
1271 : 130 : !gsi_end_p (gsi); gsi_next (&gsi))
1272 : : {
1273 : 27 : gphi *phi = gsi.phi ();
1274 : 27 : tree arg = PHI_ARG_DEF_FROM_EDGE (phi, e_default);
1275 : 27 : add_phi_arg (phi, arg, e02,
1276 : : gimple_phi_arg_location_from_edge (phi, e_default));
1277 : : }
1278 : : /* Partially fix the dominator tree, if it is available. */
1279 : 103 : if (dom_info_available_p (CDI_DOMINATORS))
1280 : 103 : redirect_immediate_dominators (CDI_DOMINATORS, bb1, bb0);
1281 : : }
1282 : : else
1283 : : {
1284 : 534 : e21 = split_block (bb2, last_assign);
1285 : 534 : bb1 = e21->dest;
1286 : 534 : remove_edge (e21);
1287 : : }
1288 : :
1289 : 637 : e1d = split_block (bb1, m_arr_ref_last);
1290 : 637 : bbd = e1d->dest;
1291 : 637 : remove_edge (e1d);
1292 : :
1293 : : /* Flags and profiles of the edge for in-range values. */
1294 : 637 : if (!m_default_case_nonstandard)
1295 : 534 : e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
1296 : 637 : e01->probability = m_default_prob.invert ();
1297 : :
1298 : : /* Flags and profiles of the edge taking care of out-of-range values. */
1299 : 637 : e02->flags &= ~EDGE_FALLTHRU;
1300 : 637 : e02->flags |= EDGE_FALSE_VALUE;
1301 : 637 : e02->probability = m_default_prob;
1302 : :
1303 : 637 : bbf = m_final_bb;
1304 : :
1305 : 637 : e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
1306 : 637 : e1f->probability = profile_probability::always ();
1307 : :
1308 : 637 : if (m_default_case_nonstandard)
1309 : : e2f = NULL;
1310 : : else
1311 : : {
1312 : 534 : e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
1313 : 534 : e2f->probability = profile_probability::always ();
1314 : : }
1315 : :
1316 : : /* frequencies of the new BBs */
1317 : 637 : bb1->count = e01->count ();
1318 : 637 : bb2->count = e02->count ();
1319 : 637 : if (!m_default_case_nonstandard)
1320 : 534 : bbf->count = e1f->count () + e2f->count ();
1321 : :
1322 : : /* Tidy blocks that have become unreachable. */
1323 : 1398 : bool prune_default_bb = !m_default_case_nonstandard
1324 : 637 : && !m_exp_index_transform_applied;
1325 : 637 : prune_bbs (bbd, m_final_bb, prune_default_bb ? NULL : m_default_bb);
1326 : :
1327 : : /* Fixup the PHI nodes in bbF. */
1328 : 637 : fix_phi_nodes (e1f, e2f, bbf);
1329 : :
1330 : : /* Fix the dominator tree, if it is available. */
1331 : 637 : if (dom_info_available_p (CDI_DOMINATORS))
1332 : : {
1333 : 637 : vec<basic_block> bbs_to_fix_dom;
1334 : :
1335 : 637 : set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
1336 : 637 : if (!m_default_case_nonstandard)
1337 : 534 : set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
1338 : 637 : if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
1339 : : /* If bbD was the immediate dominator ... */
1340 : 425 : set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
1341 : :
1342 : 652 : bbs_to_fix_dom.create (3 + (bb2 != bbf));
1343 : 637 : bbs_to_fix_dom.quick_push (bb0);
1344 : 637 : bbs_to_fix_dom.quick_push (bb1);
1345 : 637 : if (bb2 != bbf)
1346 : 622 : bbs_to_fix_dom.quick_push (bb2);
1347 : 637 : bbs_to_fix_dom.quick_push (bbf);
1348 : :
1349 : 637 : iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
1350 : 637 : bbs_to_fix_dom.release ();
1351 : : }
1352 : 637 : }
1353 : :
1354 : : /* The following function is invoked on every switch statement (the current
1355 : : one is given in SWTCH) and runs the individual phases of switch
1356 : : conversion on it one after another until one fails or the conversion
1357 : : is completed. On success, NULL is in m_reason, otherwise points
1358 : : to a string with the reason why the conversion failed. */
1359 : :
1360 : : void
1361 : 28936 : switch_conversion::expand (gswitch *swtch)
1362 : : {
1363 : : /* Group case labels so that we get the right results from the heuristics
1364 : : that decide on the code generation approach for this switch. */
1365 : 28936 : m_cfg_altered |= group_case_labels_stmt (swtch);
1366 : :
1367 : : /* If this switch is now a degenerate case with only a default label,
1368 : : there is nothing left for us to do. */
1369 : 28936 : if (gimple_switch_num_labels (swtch) < 2)
1370 : : {
1371 : 0 : m_reason = "switch is a degenerate case";
1372 : 0 : return;
1373 : : }
1374 : :
1375 : 28936 : collect (swtch);
1376 : :
1377 : : /* No error markers should reach here (they should be filtered out
1378 : : during gimplification). */
1379 : 28936 : gcc_checking_assert (TREE_TYPE (m_index_expr) != error_mark_node);
1380 : :
1381 : : /* Prefer bit test if possible. */
1382 : 28936 : if (tree_fits_uhwi_p (m_range_size)
1383 : 28866 : && bit_test_cluster::can_be_handled (tree_to_uhwi (m_range_size), m_uniq)
1384 : 43588 : && bit_test_cluster::is_beneficial (m_count, m_uniq))
1385 : : {
1386 : 2723 : m_reason = "expanding as bit test is preferable";
1387 : 2723 : return;
1388 : : }
1389 : :
1390 : 26213 : if (m_uniq <= 2)
1391 : : {
1392 : : /* This will be expanded as a decision tree . */
1393 : 7970 : m_reason = "expanding as jumps is preferable";
1394 : 7970 : return;
1395 : : }
1396 : :
1397 : : /* If there is no common successor, we cannot do the transformation. */
1398 : 18243 : if (!m_final_bb)
1399 : : {
1400 : 11196 : m_reason = "no common successor to all case label target blocks found";
1401 : 11196 : return;
1402 : : }
1403 : :
1404 : : /* Sometimes it is possible to use the "exponential index transform" to help
1405 : : switch conversion convert switches which it otherwise could not convert.
1406 : : However, we want to do this transform only when we know that switch
1407 : : conversion will then really be able to convert the switch. So we first
1408 : : check if the transformation is applicable and then maybe later do the
1409 : : transformation. */
1410 : 7047 : bool exp_transform_viable = is_exp_index_transform_viable (swtch);
1411 : :
1412 : : /* Check the case label values are within reasonable range.
1413 : :
1414 : : If we will be doing exponential index transform, the range will be always
1415 : : reasonable. */
1416 : 7047 : if (!exp_transform_viable && !check_range ())
1417 : : {
1418 : 736 : gcc_assert (m_reason);
1419 : : return;
1420 : : }
1421 : :
1422 : : /* For all the cases, see whether they are empty, the assignments they
1423 : : represent constant and so on... */
1424 : 6311 : if (!check_all_empty_except_final ())
1425 : : {
1426 : 5589 : gcc_assert (m_reason);
1427 : : return;
1428 : : }
1429 : 722 : if (!check_final_bb ())
1430 : : {
1431 : 85 : gcc_assert (m_reason);
1432 : : return;
1433 : : }
1434 : :
1435 : : /* At this point all checks have passed and we can proceed with the
1436 : : transformation. */
1437 : :
1438 : 637 : if (exp_transform_viable)
1439 : 21 : exp_index_transform (swtch);
1440 : :
1441 : 637 : create_temp_arrays ();
1442 : 1274 : gather_default_values (m_default_case_nonstandard
1443 : 103 : ? gimple_switch_label (swtch, 1)
1444 : 534 : : gimple_switch_default_label (swtch));
1445 : 637 : build_constructors ();
1446 : :
1447 : 637 : build_arrays (); /* Build the static arrays and assignments. */
1448 : 637 : gen_inbound_check (); /* Build the bounds check. */
1449 : :
1450 : 637 : m_cfg_altered = true;
1451 : : }
1452 : :
1453 : : /* Destructor. */
1454 : :
1455 : 28936 : switch_conversion::~switch_conversion ()
1456 : : {
1457 : 28936 : XDELETEVEC (m_constructors);
1458 : 28936 : XDELETEVEC (m_default_values);
1459 : 28936 : }
1460 : :
1461 : : /* Constructor. */
1462 : :
1463 : 15673 : group_cluster::group_cluster (vec<cluster *> &clusters,
1464 : 15673 : unsigned start, unsigned end)
1465 : : {
1466 : 15673 : gcc_checking_assert (end - start + 1 >= 1);
1467 : 15673 : m_prob = profile_probability::never ();
1468 : 15673 : m_cases.create (end - start + 1);
1469 : 136448 : for (unsigned i = start; i <= end; i++)
1470 : : {
1471 : 120775 : m_cases.quick_push (static_cast<simple_cluster *> (clusters[i]));
1472 : 120775 : m_prob += clusters[i]->m_prob;
1473 : : }
1474 : 15673 : m_subtree_prob = m_prob;
1475 : 15673 : }
1476 : :
1477 : : /* Destructor. */
1478 : :
1479 : 15673 : group_cluster::~group_cluster ()
1480 : : {
1481 : 136448 : for (unsigned i = 0; i < m_cases.length (); i++)
1482 : 120775 : delete m_cases[i];
1483 : :
1484 : 15673 : m_cases.release ();
1485 : 15673 : }
1486 : :
1487 : : /* Dump content of a cluster. */
1488 : :
1489 : : void
1490 : 28 : group_cluster::dump (FILE *f, bool details)
1491 : : {
1492 : 28 : unsigned total_values = 0;
1493 : 390 : for (unsigned i = 0; i < m_cases.length (); i++)
1494 : 334 : total_values += m_cases[i]->get_range (m_cases[i]->get_low (),
1495 : 167 : m_cases[i]->get_high ());
1496 : :
1497 : : unsigned comparison_count = 0;
1498 : 195 : for (unsigned i = 0; i < m_cases.length (); i++)
1499 : : {
1500 : 167 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1501 : 279 : comparison_count += sc->get_comparison_count ();
1502 : : }
1503 : :
1504 : 28 : unsigned HOST_WIDE_INT range = get_range (get_low (), get_high ());
1505 : 46 : fprintf (f, "%s", get_type () == JUMP_TABLE ? "JT" : "BT");
1506 : :
1507 : 28 : if (details)
1508 : 0 : fprintf (f, "(values:%d comparisons:%d range:" HOST_WIDE_INT_PRINT_DEC
1509 : : " density: %.2f%%)", total_values, comparison_count, range,
1510 : 0 : 100.0f * comparison_count / range);
1511 : :
1512 : 28 : fprintf (f, ":");
1513 : 28 : PRINT_CASE (f, get_low ());
1514 : 28 : fprintf (f, "-");
1515 : 28 : PRINT_CASE (f, get_high ());
1516 : 28 : fprintf (f, " ");
1517 : 28 : }
1518 : :
1519 : : /* Emit GIMPLE code to handle the cluster. */
1520 : :
1521 : : void
1522 : 8890 : jump_table_cluster::emit (tree index_expr, tree,
1523 : : tree default_label_expr, basic_block default_bb,
1524 : : location_t loc)
1525 : : {
1526 : 8890 : tree low = get_low ();
1527 : 8890 : unsigned HOST_WIDE_INT range = get_range (low, get_high ());
1528 : 8890 : unsigned HOST_WIDE_INT nondefault_range = 0;
1529 : 8890 : bool bitint = false;
1530 : 8890 : gimple_stmt_iterator gsi = gsi_start_bb (m_case_bb);
1531 : :
1532 : : /* For large/huge _BitInt, subtract low from index_expr, cast to unsigned
1533 : : DImode type (get_range doesn't support ranges larger than 64-bits)
1534 : : and subtract low from all case values as well. */
1535 : 8890 : if (TREE_CODE (TREE_TYPE (index_expr)) == BITINT_TYPE
1536 : 8890 : && TYPE_PRECISION (TREE_TYPE (index_expr)) > GET_MODE_PRECISION (DImode))
1537 : : {
1538 : 2 : bitint = true;
1539 : 2 : tree this_low = low, type;
1540 : 2 : gimple *g;
1541 : 2 : gimple_seq seq = NULL;
1542 : 2 : if (!TYPE_OVERFLOW_WRAPS (TREE_TYPE (index_expr)))
1543 : : {
1544 : 1 : type = unsigned_type_for (TREE_TYPE (index_expr));
1545 : 1 : index_expr = gimple_convert (&seq, type, index_expr);
1546 : 1 : this_low = fold_convert (type, this_low);
1547 : : }
1548 : 2 : this_low = const_unop (NEGATE_EXPR, TREE_TYPE (this_low), this_low);
1549 : 2 : index_expr = gimple_build (&seq, PLUS_EXPR, TREE_TYPE (index_expr),
1550 : : index_expr, this_low);
1551 : 2 : type = build_nonstandard_integer_type (GET_MODE_PRECISION (DImode), 1);
1552 : 2 : g = gimple_build_cond (GT_EXPR, index_expr,
1553 : 2 : fold_convert (TREE_TYPE (index_expr),
1554 : : TYPE_MAX_VALUE (type)),
1555 : : NULL_TREE, NULL_TREE);
1556 : 2 : gimple_seq_add_stmt (&seq, g);
1557 : 2 : gimple_seq_set_location (seq, loc);
1558 : 2 : gsi_insert_seq_after (&gsi, seq, GSI_NEW_STMT);
1559 : 2 : edge e1 = split_block (m_case_bb, g);
1560 : 2 : e1->flags = EDGE_FALSE_VALUE;
1561 : 2 : e1->probability = profile_probability::likely ();
1562 : 2 : edge e2 = make_edge (e1->src, default_bb, EDGE_TRUE_VALUE);
1563 : 2 : e2->probability = e1->probability.invert ();
1564 : 2 : gsi = gsi_start_bb (e1->dest);
1565 : 2 : seq = NULL;
1566 : 2 : index_expr = gimple_convert (&seq, type, index_expr);
1567 : 2 : gimple_seq_set_location (seq, loc);
1568 : 2 : gsi_insert_seq_after (&gsi, seq, GSI_NEW_STMT);
1569 : : }
1570 : :
1571 : : /* For jump table we just emit a new gswitch statement that will
1572 : : be latter lowered to jump table. */
1573 : 8890 : auto_vec <tree> labels;
1574 : 17780 : labels.create (m_cases.length ());
1575 : :
1576 : 8890 : basic_block case_bb = gsi_bb (gsi);
1577 : 8890 : make_edge (case_bb, default_bb, 0);
1578 : 98322 : for (unsigned i = 0; i < m_cases.length (); i++)
1579 : : {
1580 : 89432 : tree lab = unshare_expr (m_cases[i]->m_case_label_expr);
1581 : 89432 : if (bitint)
1582 : : {
1583 : 13 : CASE_LOW (lab)
1584 : 13 : = fold_convert (TREE_TYPE (index_expr),
1585 : : const_binop (MINUS_EXPR,
1586 : : TREE_TYPE (CASE_LOW (lab)),
1587 : : CASE_LOW (lab), low));
1588 : 13 : if (CASE_HIGH (lab))
1589 : 0 : CASE_HIGH (lab)
1590 : 0 : = fold_convert (TREE_TYPE (index_expr),
1591 : : const_binop (MINUS_EXPR,
1592 : : TREE_TYPE (CASE_HIGH (lab)),
1593 : : CASE_HIGH (lab), low));
1594 : : }
1595 : 89432 : labels.quick_push (lab);
1596 : 89432 : make_edge (case_bb, m_cases[i]->m_case_bb, 0);
1597 : : }
1598 : :
1599 : 8890 : gswitch *s = gimple_build_switch (index_expr,
1600 : : unshare_expr (default_label_expr), labels);
1601 : 8890 : gimple_set_location (s, loc);
1602 : 8890 : gsi_insert_after (&gsi, s, GSI_NEW_STMT);
1603 : :
1604 : : /* Set up even probabilities for all cases. */
1605 : 98322 : for (unsigned i = 0; i < m_cases.length (); i++)
1606 : : {
1607 : 89432 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1608 : 89432 : edge case_edge = find_edge (case_bb, sc->m_case_bb);
1609 : 89432 : unsigned HOST_WIDE_INT case_range
1610 : 89432 : = sc->get_range (sc->get_low (), sc->get_high ());
1611 : 89432 : nondefault_range += case_range;
1612 : :
1613 : : /* case_edge->aux is number of values in a jump-table that are covered
1614 : : by the case_edge. */
1615 : 89432 : case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + case_range);
1616 : : }
1617 : :
1618 : 8890 : edge default_edge = gimple_switch_default_edge (cfun, s);
1619 : 8890 : default_edge->probability = profile_probability::never ();
1620 : :
1621 : 98322 : for (unsigned i = 0; i < m_cases.length (); i++)
1622 : : {
1623 : 89432 : simple_cluster *sc = static_cast<simple_cluster *> (m_cases[i]);
1624 : 89432 : edge case_edge = find_edge (case_bb, sc->m_case_bb);
1625 : 89432 : case_edge->probability
1626 : 89432 : = profile_probability::always ().apply_scale ((intptr_t)case_edge->aux,
1627 : : range);
1628 : : }
1629 : :
1630 : : /* Number of non-default values is probability of default edge. */
1631 : 8890 : default_edge->probability
1632 : 8890 : += profile_probability::always ().apply_scale (nondefault_range,
1633 : 8890 : range).invert ();
1634 : :
1635 : 8890 : switch_decision_tree::reset_out_edges_aux (s);
1636 : 8890 : }
1637 : :
1638 : : /* Find jump tables of given CLUSTERS, where all members of the vector
1639 : : are of type simple_cluster. New clusters are returned. */
1640 : :
1641 : : vec<cluster *>
1642 : 73828 : jump_table_cluster::find_jump_tables (vec<cluster *> &clusters)
1643 : : {
1644 : 73828 : if (!is_enabled ())
1645 : 15241 : return clusters.copy ();
1646 : :
1647 : 58587 : unsigned l = clusters.length ();
1648 : :
1649 : 58587 : auto_vec<min_cluster_item> min;
1650 : 58587 : min.reserve (l + 1);
1651 : :
1652 : 58587 : min.quick_push (min_cluster_item (0, 0, 0));
1653 : :
1654 : 58587 : unsigned HOST_WIDE_INT max_ratio
1655 : 58587 : = (optimize_insn_for_size_p ()
1656 : 58587 : ? param_jump_table_max_growth_ratio_for_size
1657 : 58587 : : param_jump_table_max_growth_ratio_for_speed);
1658 : :
1659 : 273566 : for (unsigned i = 1; i <= l; i++)
1660 : : {
1661 : : /* Set minimal # of clusters with i-th item to infinite. */
1662 : 214979 : min.quick_push (min_cluster_item (INT_MAX, INT_MAX, INT_MAX));
1663 : :
1664 : : /* Pre-calculate number of comparisons for the clusters. */
1665 : 214979 : HOST_WIDE_INT comparison_count = 0;
1666 : 7054039 : for (unsigned k = 0; k <= i - 1; k++)
1667 : : {
1668 : 6839060 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[k]);
1669 : 13479109 : comparison_count += sc->get_comparison_count ();
1670 : : }
1671 : :
1672 : 7054039 : for (unsigned j = 0; j < i; j++)
1673 : : {
1674 : 6839060 : unsigned HOST_WIDE_INT s = min[j].m_non_jt_cases;
1675 : 13677756 : if (i - j < case_values_threshold ())
1676 : 546869 : s += i - j;
1677 : :
1678 : : /* Prefer clusters with smaller number of numbers covered. */
1679 : 6839060 : if ((min[j].m_count + 1 < min[i].m_count
1680 : 1883917 : || (min[j].m_count + 1 == min[i].m_count
1681 : 953 : && s < min[i].m_non_jt_cases))
1682 : 6839097 : && can_be_handled (clusters, j, i - 1, max_ratio,
1683 : : comparison_count))
1684 : 215005 : min[i] = min_cluster_item (min[j].m_count + 1, j, s);
1685 : :
1686 : 6839060 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[j]);
1687 : 13479109 : comparison_count -= sc->get_comparison_count ();
1688 : : }
1689 : :
1690 : 214979 : gcc_checking_assert (comparison_count == 0);
1691 : 214979 : gcc_checking_assert (min[i].m_count != INT_MAX);
1692 : : }
1693 : :
1694 : : /* No result. */
1695 : 58587 : if (min[l].m_count == l)
1696 : 8497 : return clusters.copy ();
1697 : :
1698 : 50090 : vec<cluster *> output;
1699 : 50090 : output.create (4);
1700 : :
1701 : : /* Find and build the clusters. */
1702 : 50090 : for (unsigned int end = l;;)
1703 : : {
1704 : 56575 : int start = min[end].m_start;
1705 : :
1706 : : /* Do not allow clusters with small number of cases. */
1707 : 56575 : if (is_beneficial (clusters, start, end - 1))
1708 : 9618 : output.safe_push (new jump_table_cluster (clusters, start, end - 1));
1709 : : else
1710 : 146570 : for (int i = end - 1; i >= start; i--)
1711 : 99613 : output.safe_push (clusters[i]);
1712 : :
1713 : 56575 : end = start;
1714 : :
1715 : 56575 : if (start <= 0)
1716 : : break;
1717 : : }
1718 : :
1719 : 50090 : output.reverse ();
1720 : 50090 : return output;
1721 : : }
1722 : :
1723 : : /* Return true when cluster starting at START and ending at END (inclusive)
1724 : : can build a jump-table. */
1725 : :
1726 : : bool
1727 : 4955180 : jump_table_cluster::can_be_handled (const vec<cluster *> &clusters,
1728 : : unsigned start, unsigned end,
1729 : : unsigned HOST_WIDE_INT max_ratio,
1730 : : unsigned HOST_WIDE_INT comparison_count)
1731 : : {
1732 : : /* If the switch is relatively small such that the cost of one
1733 : : indirect jump on the target are higher than the cost of a
1734 : : decision tree, go with the decision tree.
1735 : :
1736 : : If range of values is much bigger than number of values,
1737 : : or if it is too large to represent in a HOST_WIDE_INT,
1738 : : make a sequence of conditional branches instead of a dispatch.
1739 : :
1740 : : The definition of "much bigger" depends on whether we are
1741 : : optimizing for size or for speed.
1742 : :
1743 : : For algorithm correctness, jump table for a single case must return
1744 : : true. We bail out in is_beneficial if it's called just for
1745 : : a single case. */
1746 : 4955180 : if (start == end)
1747 : : return true;
1748 : :
1749 : 9752222 : unsigned HOST_WIDE_INT range = get_range (clusters[start]->get_low (),
1750 : 4876111 : clusters[end]->get_high ());
1751 : : /* Check overflow. */
1752 : 4876111 : if (range == 0)
1753 : : return false;
1754 : :
1755 : 4872591 : if (range > HOST_WIDE_INT_M1U / 100)
1756 : : return false;
1757 : :
1758 : 662434 : unsigned HOST_WIDE_INT lhs = 100 * range;
1759 : 662434 : if (lhs < range)
1760 : : return false;
1761 : :
1762 : 662434 : return lhs <= max_ratio * comparison_count;
1763 : : }
1764 : :
1765 : : /* Return true if cluster starting at START and ending at END (inclusive)
1766 : : is profitable transformation. */
1767 : :
1768 : : bool
1769 : 56575 : jump_table_cluster::is_beneficial (const vec<cluster *> &,
1770 : : unsigned start, unsigned end)
1771 : : {
1772 : : /* Single case bail out. */
1773 : 56575 : if (start == end)
1774 : : return false;
1775 : :
1776 : 101596 : return end - start + 1 >= case_values_threshold ();
1777 : : }
1778 : :
1779 : : /* Find bit tests of given CLUSTERS, where all members of the vector
1780 : : are of type simple_cluster. MAX_C is the approx max number of cases per
1781 : : label. New clusters are returned. */
1782 : :
1783 : : vec<cluster *>
1784 : 74180 : bit_test_cluster::find_bit_tests (vec<cluster *> &clusters, int max_c)
1785 : : {
1786 : 74180 : if (!is_enabled () || max_c == 1)
1787 : 36599 : return clusters.copy ();
1788 : :
1789 : : /* Dynamic programming algorithm.
1790 : :
1791 : : In: List of simple clusters
1792 : : Out: List of simple clusters and bit test clusters such that each bit test
1793 : : cluster can_be_handled() and is_beneficial()
1794 : :
1795 : : Tries to merge consecutive clusters into bigger (bit test) ones. Tries to
1796 : : end up with as few clusters as possible. */
1797 : :
1798 : 37581 : unsigned l = clusters.length ();
1799 : :
1800 : 37580 : if (l == 0)
1801 : 1 : return clusters.copy ();
1802 : 37580 : gcc_checking_assert (l <= INT_MAX);
1803 : :
1804 : 37580 : auto_vec<min_cluster_item> min;
1805 : 37580 : min.reserve (l + 1);
1806 : :
1807 : 37580 : int bits_in_word = GET_MODE_BITSIZE (word_mode);
1808 : :
1809 : : /* First phase: Compute the minimum number of clusters for each prefix of the
1810 : : input list incrementally
1811 : :
1812 : : min[i] = (count, j, _) means that the prefix ending with the (i-1)-th
1813 : : element can be made to contain as few as count clusters and that in such
1814 : : clustering the last cluster is made up of input clusters [j, i-1]
1815 : : (inclusive). */
1816 : 37580 : min.quick_push (min_cluster_item (0, 0, INT_MAX));
1817 : 37580 : min.quick_push (min_cluster_item (1, 0, INT_MAX));
1818 : 142039 : for (int i = 2; i <= (int) l; i++)
1819 : : {
1820 : 104459 : auto_vec<unsigned, m_max_case_bit_tests> unique_labels;
1821 : :
1822 : : /* Since each cluster contains at least one case number and one bit test
1823 : : cluster can cover at most bits_in_word case numbers, we don't need to
1824 : : look farther than bits_in_word clusters back. */
1825 : 443220 : for (int j = i - 1; j >= 0 && j >= i - bits_in_word; j--)
1826 : : {
1827 : : /* Consider creating a bit test cluster from input clusters [j, i-1]
1828 : : (inclusive) */
1829 : :
1830 : 382176 : simple_cluster *sc = static_cast<simple_cluster *> (clusters[j]);
1831 : 382176 : unsigned label = sc->m_case_bb->index;
1832 : 382176 : if (!unique_labels.contains (label))
1833 : : {
1834 : 288994 : if (unique_labels.length () >= m_max_case_bit_tests)
1835 : : /* is_beneficial() will be false for this and the following
1836 : : iterations. */
1837 : : break;
1838 : 245579 : unique_labels.quick_push (label);
1839 : : }
1840 : :
1841 : 338761 : unsigned new_count = min[j].m_count + 1;
1842 : :
1843 : 338761 : if (j == i - 1)
1844 : : {
1845 : 104459 : min.quick_push (min_cluster_item (new_count, j, INT_MAX));
1846 : 104459 : continue;
1847 : : }
1848 : :
1849 : 234302 : unsigned HOST_WIDE_INT range
1850 : 234302 : = get_range (clusters[j]->get_low (), clusters[i-1]->get_high ());
1851 : 234302 : if (new_count < min[i].m_count
1852 : 205326 : && can_be_handled (range, unique_labels.length ())
1853 : 407644 : && is_beneficial (i - j, unique_labels.length ()))
1854 : 10419 : min[i] = min_cluster_item (new_count, j, INT_MAX);
1855 : : }
1856 : 104459 : }
1857 : :
1858 : 37580 : if (min[l].m_count == l)
1859 : : /* No bit test clustering opportunities. */
1860 : 32517 : return clusters.copy ();
1861 : :
1862 : 5063 : vec<cluster *> output;
1863 : 5063 : output.create (4);
1864 : :
1865 : : /* Second phase: Find and build the bit test clusters by traversing min
1866 : : array backwards. */
1867 : 5063 : for (unsigned end = l;;)
1868 : : {
1869 : 20090 : unsigned start = min[end].m_start;
1870 : 20090 : gcc_checking_assert (start < end);
1871 : :
1872 : : /* This cluster will be made out of input clusters [start, end - 1]. */
1873 : :
1874 : 20090 : if (start == end - 1)
1875 : : /* Let the cluster be a simple cluster. */
1876 : 14035 : output.safe_push (clusters[start]);
1877 : : else
1878 : : {
1879 : 6055 : bool entire = start == 0 && end == l;
1880 : 6055 : output.safe_push (new bit_test_cluster (clusters, start, end - 1,
1881 : 6055 : entire));
1882 : : }
1883 : :
1884 : 20090 : end = start;
1885 : :
1886 : 20090 : if (start <= 0)
1887 : : break;
1888 : : }
1889 : :
1890 : 5063 : output.reverse ();
1891 : 5063 : return output;
1892 : 37580 : }
1893 : :
1894 : : /* Return true when RANGE of case values with UNIQ labels
1895 : : can build a bit test. */
1896 : :
1897 : : bool
1898 : 234192 : bit_test_cluster::can_be_handled (unsigned HOST_WIDE_INT range,
1899 : : unsigned int uniq)
1900 : : {
1901 : : /* Check overflow. */
1902 : 234192 : if (range == 0)
1903 : : return false;
1904 : :
1905 : 463904 : if (range > GET_MODE_BITSIZE (word_mode))
1906 : : return false;
1907 : :
1908 : 198677 : return uniq <= m_max_case_bit_tests;
1909 : : }
1910 : :
1911 : : /* Return true when COUNT of cases of UNIQ labels is beneficial for bit test
1912 : : transformation. */
1913 : :
1914 : : bool
1915 : 187994 : bit_test_cluster::is_beneficial (unsigned count, unsigned uniq)
1916 : : {
1917 : : /* NOTE: When modifying this, keep in mind the value of
1918 : : m_max_case_bit_tests. */
1919 : 187994 : return (((uniq == 1 && count >= 3)
1920 : 179425 : || (uniq == 2 && count >= 5)
1921 : 366238 : || (uniq == 3 && count >= 6)));
1922 : : }
1923 : :
1924 : : /* Comparison function for qsort to order bit tests by decreasing
1925 : : probability of execution. */
1926 : :
1927 : : int
1928 : 18098 : case_bit_test::cmp (const void *p1, const void *p2)
1929 : : {
1930 : 18098 : const case_bit_test *const d1 = (const case_bit_test *) p1;
1931 : 18098 : const case_bit_test *const d2 = (const case_bit_test *) p2;
1932 : :
1933 : 18098 : if (d2->bits != d1->bits)
1934 : 16436 : return d2->bits - d1->bits;
1935 : :
1936 : : /* Stabilize the sort. */
1937 : 1662 : return (LABEL_DECL_UID (CASE_LABEL (d2->label))
1938 : 1662 : - LABEL_DECL_UID (CASE_LABEL (d1->label)));
1939 : : }
1940 : :
1941 : : /* Expand a switch statement by a short sequence of bit-wise
1942 : : comparisons. "switch(x)" is effectively converted into
1943 : : "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
1944 : : integer constants.
1945 : :
1946 : : INDEX_EXPR is the value being switched on.
1947 : :
1948 : : MINVAL is the lowest case value of in the case nodes,
1949 : : and RANGE is highest value minus MINVAL. MINVAL and RANGE
1950 : : are not guaranteed to be of the same type as INDEX_EXPR
1951 : : (the gimplifier doesn't change the type of case label values,
1952 : : and MINVAL and RANGE are derived from those values).
1953 : : MAXVAL is MINVAL + RANGE.
1954 : :
1955 : : There *MUST* be max_case_bit_tests or less unique case
1956 : : node targets. */
1957 : :
1958 : : void
1959 : 5018 : bit_test_cluster::emit (tree index_expr, tree index_type,
1960 : : tree, basic_block default_bb, location_t loc)
1961 : : {
1962 : 30108 : case_bit_test test[m_max_case_bit_tests] = { {} };
1963 : 5018 : unsigned int i, j, k;
1964 : 5018 : unsigned int count;
1965 : :
1966 : 5018 : tree unsigned_index_type = range_check_type (index_type);
1967 : :
1968 : 5018 : gimple_stmt_iterator gsi;
1969 : 5018 : gassign *shift_stmt;
1970 : :
1971 : 5018 : tree idx, tmp, csui;
1972 : 5018 : tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
1973 : 5018 : tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
1974 : 5018 : tree word_mode_one = fold_convert (word_type_node, integer_one_node);
1975 : 5018 : int prec = TYPE_PRECISION (word_type_node);
1976 : 5018 : wide_int wone = wi::one (prec);
1977 : :
1978 : 5018 : tree minval = get_low ();
1979 : 5018 : tree maxval = get_high ();
1980 : :
1981 : : /* Go through all case labels, and collect the case labels, profile
1982 : : counts, and other information we need to build the branch tests. */
1983 : 5018 : count = 0;
1984 : 28105 : for (i = 0; i < m_cases.length (); i++)
1985 : : {
1986 : 23087 : unsigned int lo, hi;
1987 : 23087 : simple_cluster *n = static_cast<simple_cluster *> (m_cases[i]);
1988 : 32463 : for (k = 0; k < count; k++)
1989 : 24089 : if (n->m_case_bb == test[k].target_bb)
1990 : : break;
1991 : :
1992 : 23087 : if (k == count)
1993 : : {
1994 : 8374 : gcc_checking_assert (count < m_max_case_bit_tests);
1995 : 8374 : test[k].mask = wi::zero (prec);
1996 : 8374 : test[k].target_bb = n->m_case_bb;
1997 : 8374 : test[k].label = n->m_case_label_expr;
1998 : 8374 : test[k].bits = 0;
1999 : 8374 : test[k].prob = profile_probability::never ();
2000 : 8374 : count++;
2001 : : }
2002 : :
2003 : 23087 : test[k].bits += n->get_range (n->get_low (), n->get_high ());
2004 : 23087 : test[k].prob += n->m_prob;
2005 : :
2006 : 23087 : lo = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_low (), minval));
2007 : 23087 : if (n->get_high () == NULL_TREE)
2008 : : hi = lo;
2009 : : else
2010 : 23087 : hi = tree_to_uhwi (int_const_binop (MINUS_EXPR, n->get_high (),
2011 : : minval));
2012 : :
2013 : 54809 : for (j = lo; j <= hi; j++)
2014 : 31722 : test[k].mask |= wi::lshift (wone, j);
2015 : : }
2016 : :
2017 : 5018 : qsort (test, count, sizeof (*test), case_bit_test::cmp);
2018 : :
2019 : : /* If every possible relative value of the index expression is a valid shift
2020 : : amount, then we can merge the entry test in the bit test. */
2021 : 5018 : bool entry_test_needed;
2022 : 5018 : int_range_max r;
2023 : 10036 : if (TREE_CODE (index_expr) == SSA_NAME
2024 : 10036 : && get_range_query (cfun)->range_of_expr (r, index_expr)
2025 : 5018 : && !r.undefined_p ()
2026 : 5017 : && !r.varying_p ()
2027 : 11407 : && wi::leu_p (r.upper_bound () - r.lower_bound (), prec - 1))
2028 : : {
2029 : 61 : wide_int min = r.lower_bound ();
2030 : 61 : wide_int max = r.upper_bound ();
2031 : 61 : tree index_type = TREE_TYPE (index_expr);
2032 : 61 : minval = fold_convert (index_type, minval);
2033 : 61 : wide_int iminval = wi::to_wide (minval);
2034 : 61 : if (wi::lt_p (min, iminval, TYPE_SIGN (index_type)))
2035 : : {
2036 : 56 : minval = wide_int_to_tree (index_type, min);
2037 : 179 : for (i = 0; i < count; i++)
2038 : 123 : test[i].mask = wi::lshift (test[i].mask, iminval - min);
2039 : : }
2040 : 5 : else if (wi::gt_p (min, iminval, TYPE_SIGN (index_type)))
2041 : : {
2042 : 0 : minval = wide_int_to_tree (index_type, min);
2043 : 0 : for (i = 0; i < count; i++)
2044 : 0 : test[i].mask = wi::lrshift (test[i].mask, min - iminval);
2045 : : }
2046 : 61 : maxval = wide_int_to_tree (index_type, max);
2047 : 61 : entry_test_needed = false;
2048 : 61 : }
2049 : : else
2050 : : entry_test_needed = true;
2051 : :
2052 : : /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
2053 : : the minval subtractions, but it might make the mask constants more
2054 : : expensive. So, compare the costs. */
2055 : 5018 : if (compare_tree_int (minval, 0) > 0 && compare_tree_int (maxval, prec) < 0)
2056 : : {
2057 : 2231 : int cost_diff;
2058 : 2231 : HOST_WIDE_INT m = tree_to_uhwi (minval);
2059 : 2231 : rtx reg = gen_raw_REG (word_mode, 10000);
2060 : 2231 : bool speed_p = optimize_insn_for_speed_p ();
2061 : 2231 : cost_diff = set_src_cost (gen_rtx_PLUS (word_mode, reg,
2062 : : GEN_INT (-m)),
2063 : : word_mode, speed_p);
2064 : 4812 : for (i = 0; i < count; i++)
2065 : : {
2066 : 2581 : rtx r = immed_wide_int_const (test[i].mask, word_mode);
2067 : 2581 : cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
2068 : : word_mode, speed_p);
2069 : 2581 : r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
2070 : 2581 : cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
2071 : : word_mode, speed_p);
2072 : : }
2073 : 2231 : if (cost_diff > 0)
2074 : : {
2075 : 4084 : for (i = 0; i < count; i++)
2076 : 2186 : test[i].mask = wi::lshift (test[i].mask, m);
2077 : 1898 : minval = build_zero_cst (TREE_TYPE (minval));
2078 : : }
2079 : : }
2080 : :
2081 : : /* Now build the test-and-branch code. */
2082 : :
2083 : 5018 : gsi = gsi_last_bb (m_case_bb);
2084 : :
2085 : : /* idx = (unsigned)x - minval. */
2086 : 5018 : idx = fold_convert_loc (loc, unsigned_index_type, index_expr);
2087 : 5018 : idx = fold_build2_loc (loc, MINUS_EXPR, unsigned_index_type, idx,
2088 : : fold_convert_loc (loc, unsigned_index_type, minval));
2089 : 5018 : idx = force_gimple_operand_gsi (&gsi, idx,
2090 : : /*simple=*/true, NULL_TREE,
2091 : : /*before=*/true, GSI_SAME_STMT);
2092 : :
2093 : 5018 : profile_probability subtree_prob = m_subtree_prob;
2094 : 5018 : profile_probability default_prob = m_default_prob;
2095 : 5018 : if (!default_prob.initialized_p ())
2096 : 2509 : default_prob = m_subtree_prob.invert ();
2097 : :
2098 : 5018 : if (m_handles_entire_switch && entry_test_needed)
2099 : : {
2100 : 2468 : tree range = int_const_binop (MINUS_EXPR, maxval, minval);
2101 : : /* if (idx > range) goto default */
2102 : 2468 : range
2103 : 2468 : = force_gimple_operand_gsi (&gsi,
2104 : : fold_convert (unsigned_index_type, range),
2105 : : /*simple=*/true, NULL_TREE,
2106 : : /*before=*/true, GSI_SAME_STMT);
2107 : 2468 : tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
2108 : 2468 : default_prob = default_prob / 2;
2109 : 2468 : basic_block new_bb
2110 : 2468 : = hoist_edge_and_branch_if_true (&gsi, tmp, default_bb,
2111 : : default_prob, loc);
2112 : 4936 : gsi = gsi_last_bb (new_bb);
2113 : : }
2114 : :
2115 : 5018 : tmp = fold_build2_loc (loc, LSHIFT_EXPR, word_type_node, word_mode_one,
2116 : : fold_convert_loc (loc, word_type_node, idx));
2117 : :
2118 : : /* csui = (1 << (word_mode) idx) */
2119 : 5018 : if (count > 1)
2120 : : {
2121 : 1798 : csui = make_ssa_name (word_type_node);
2122 : 1798 : tmp = force_gimple_operand_gsi (&gsi, tmp,
2123 : : /*simple=*/false, NULL_TREE,
2124 : : /*before=*/true, GSI_SAME_STMT);
2125 : 1798 : shift_stmt = gimple_build_assign (csui, tmp);
2126 : 1798 : gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
2127 : 1798 : update_stmt (shift_stmt);
2128 : : }
2129 : : else
2130 : : csui = tmp;
2131 : :
2132 : : /* for each unique set of cases:
2133 : : if (const & csui) goto target */
2134 : 13392 : for (k = 0; k < count; k++)
2135 : : {
2136 : 8374 : profile_probability prob = test[k].prob / (subtree_prob + default_prob);
2137 : 8374 : subtree_prob -= test[k].prob;
2138 : 8374 : tmp = wide_int_to_tree (word_type_node, test[k].mask);
2139 : 8374 : tmp = fold_build2_loc (loc, BIT_AND_EXPR, word_type_node, csui, tmp);
2140 : 8374 : tmp = fold_build2_loc (loc, NE_EXPR, boolean_type_node,
2141 : : tmp, word_mode_zero);
2142 : 8374 : tmp = force_gimple_operand_gsi (&gsi, tmp,
2143 : : /*simple=*/true, NULL_TREE,
2144 : : /*before=*/true, GSI_SAME_STMT);
2145 : 8374 : basic_block new_bb
2146 : 8374 : = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_bb,
2147 : : prob, loc);
2148 : 16748 : gsi = gsi_last_bb (new_bb);
2149 : : }
2150 : :
2151 : : /* We should have removed all edges now. */
2152 : 5018 : gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
2153 : :
2154 : : /* If nothing matched, go to the default label. */
2155 : 5018 : edge e = make_edge (gsi_bb (gsi), default_bb, EDGE_FALLTHRU);
2156 : 5018 : e->probability = profile_probability::always ();
2157 : 20072 : }
2158 : :
2159 : : /* Split the basic block at the statement pointed to by GSIP, and insert
2160 : : a branch to the target basic block of E_TRUE conditional on tree
2161 : : expression COND.
2162 : :
2163 : : It is assumed that there is already an edge from the to-be-split
2164 : : basic block to E_TRUE->dest block. This edge is removed, and the
2165 : : profile information on the edge is re-used for the new conditional
2166 : : jump.
2167 : :
2168 : : The CFG is updated. The dominator tree will not be valid after
2169 : : this transformation, but the immediate dominators are updated if
2170 : : UPDATE_DOMINATORS is true.
2171 : :
2172 : : Returns the newly created basic block. */
2173 : :
2174 : : basic_block
2175 : 10842 : bit_test_cluster::hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
2176 : : tree cond, basic_block case_bb,
2177 : : profile_probability prob,
2178 : : location_t loc)
2179 : : {
2180 : 10842 : tree tmp;
2181 : 10842 : gcond *cond_stmt;
2182 : 10842 : edge e_false;
2183 : 10842 : basic_block new_bb, split_bb = gsi_bb (*gsip);
2184 : :
2185 : 10842 : edge e_true = make_edge (split_bb, case_bb, EDGE_TRUE_VALUE);
2186 : 10842 : e_true->probability = prob;
2187 : 10842 : gcc_assert (e_true->src == split_bb);
2188 : :
2189 : 10842 : tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
2190 : : /*before=*/true, GSI_SAME_STMT);
2191 : 10842 : cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
2192 : 10842 : gimple_set_location (cond_stmt, loc);
2193 : 10842 : gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
2194 : :
2195 : 10842 : e_false = split_block (split_bb, cond_stmt);
2196 : 10842 : new_bb = e_false->dest;
2197 : 10842 : redirect_edge_pred (e_true, split_bb);
2198 : :
2199 : 10842 : e_false->flags &= ~EDGE_FALLTHRU;
2200 : 10842 : e_false->flags |= EDGE_FALSE_VALUE;
2201 : 10842 : e_false->probability = e_true->probability.invert ();
2202 : 10842 : new_bb->count = e_false->count ();
2203 : :
2204 : 10842 : return new_bb;
2205 : : }
2206 : :
2207 : : /* Compute the number of case labels that correspond to each outgoing edge of
2208 : : switch statement. Record this information in the aux field of the edge.
2209 : : Return the approx max number of cases per edge. */
2210 : :
2211 : : int
2212 : 47102 : switch_decision_tree::compute_cases_per_edge ()
2213 : : {
2214 : 47102 : int max_c = 0;
2215 : 47102 : reset_out_edges_aux (m_switch);
2216 : 47102 : int ncases = gimple_switch_num_labels (m_switch);
2217 : 319425 : for (int i = ncases - 1; i >= 1; --i)
2218 : : {
2219 : 272323 : edge case_edge = gimple_switch_edge (cfun, m_switch, i);
2220 : 272323 : case_edge->aux = (void *) ((intptr_t) (case_edge->aux) + 1);
2221 : : /* For a range case add one extra. That's enough for the bit
2222 : : cluster heuristic. */
2223 : 272323 : if ((intptr_t)case_edge->aux > max_c)
2224 : 151334 : max_c = (intptr_t)case_edge->aux +
2225 : 75667 : !!CASE_HIGH (gimple_switch_label (m_switch, i));
2226 : : }
2227 : 47102 : return max_c;
2228 : : }
2229 : :
2230 : : /* Analyze switch statement and return true when the statement is expanded
2231 : : as decision tree. */
2232 : :
2233 : : bool
2234 : 47102 : switch_decision_tree::analyze_switch_statement ()
2235 : : {
2236 : 47102 : unsigned l = gimple_switch_num_labels (m_switch);
2237 : 47102 : basic_block bb = gimple_bb (m_switch);
2238 : 47102 : auto_vec<cluster *> clusters;
2239 : 47102 : clusters.create (l - 1);
2240 : :
2241 : 47102 : basic_block default_bb = gimple_switch_default_bb (cfun, m_switch);
2242 : 47102 : m_case_bbs.reserve (l);
2243 : 47102 : m_case_bbs.quick_push (default_bb);
2244 : :
2245 : 47102 : int max_c = compute_cases_per_edge ();
2246 : :
2247 : 319425 : for (unsigned i = 1; i < l; i++)
2248 : : {
2249 : 272323 : tree elt = gimple_switch_label (m_switch, i);
2250 : 272323 : tree lab = CASE_LABEL (elt);
2251 : 272323 : basic_block case_bb = label_to_block (cfun, lab);
2252 : 272323 : edge case_edge = find_edge (bb, case_bb);
2253 : 272323 : tree low = CASE_LOW (elt);
2254 : 272323 : tree high = CASE_HIGH (elt);
2255 : :
2256 : 272323 : profile_probability p
2257 : 272323 : = case_edge->probability / ((intptr_t) (case_edge->aux));
2258 : 272323 : clusters.quick_push (new simple_cluster (low, high, elt, case_edge->dest,
2259 : 272323 : p));
2260 : 272323 : m_case_bbs.quick_push (case_edge->dest);
2261 : : }
2262 : :
2263 : 47102 : reset_out_edges_aux (m_switch);
2264 : :
2265 : : /* Find bit-test clusters. */
2266 : 47102 : vec<cluster *> output = bit_test_cluster::find_bit_tests (clusters, max_c);
2267 : :
2268 : : /* Find jump table clusters. We are looking for these in the sequences of
2269 : : simple clusters which we didn't manage to convert into bit-test
2270 : : clusters. */
2271 : 47102 : vec<cluster *> output2;
2272 : 47102 : auto_vec<cluster *> tmp;
2273 : 47102 : output2.create (1);
2274 : 47102 : tmp.create (1);
2275 : :
2276 : 301356 : for (unsigned i = 0; i < output.length (); i++)
2277 : : {
2278 : 254254 : cluster *c = output[i];
2279 : 254254 : if (c->get_type () != SIMPLE_CASE)
2280 : : {
2281 : 5018 : if (!tmp.is_empty ())
2282 : : {
2283 : 1939 : vec<cluster *> n = jump_table_cluster::find_jump_tables (tmp);
2284 : 1939 : output2.safe_splice (n);
2285 : 1939 : n.release ();
2286 : 1939 : tmp.truncate (0);
2287 : : }
2288 : 5018 : output2.safe_push (c);
2289 : : }
2290 : : else
2291 : 249236 : tmp.safe_push (c);
2292 : : }
2293 : :
2294 : : /* We still can have a temporary vector to test. */
2295 : 47102 : if (!tmp.is_empty ())
2296 : : {
2297 : 44089 : vec<cluster *> n = jump_table_cluster::find_jump_tables (tmp);
2298 : 44089 : output2.safe_splice (n);
2299 : 44089 : n.release ();
2300 : : }
2301 : :
2302 : 47102 : if (dump_file)
2303 : : {
2304 : 24 : fprintf (dump_file, ";; GIMPLE switch case clusters: ");
2305 : 111 : for (unsigned i = 0; i < output2.length (); i++)
2306 : 87 : output2[i]->dump (dump_file, dump_flags & TDF_DETAILS);
2307 : 24 : fprintf (dump_file, "\n");
2308 : : }
2309 : :
2310 : 47102 : output.release ();
2311 : :
2312 : 47102 : bool expanded = try_switch_expansion (output2);
2313 : 47102 : release_clusters (output2);
2314 : 47102 : return expanded;
2315 : 47102 : }
2316 : :
2317 : : /* Attempt to expand CLUSTERS as a decision tree. Return true when
2318 : : expanded. */
2319 : :
2320 : : bool
2321 : 47102 : switch_decision_tree::try_switch_expansion (vec<cluster *> &clusters)
2322 : : {
2323 : 47102 : tree index_expr = gimple_switch_index (m_switch);
2324 : 47102 : tree index_type = TREE_TYPE (index_expr);
2325 : 47102 : basic_block bb = gimple_bb (m_switch);
2326 : :
2327 : 47102 : if (gimple_switch_num_labels (m_switch) == 1
2328 : 47102 : || range_check_type (index_type) == NULL_TREE)
2329 : 1 : return false;
2330 : :
2331 : : /* Find the default case target label. */
2332 : 47101 : edge default_edge = gimple_switch_default_edge (cfun, m_switch);
2333 : 47101 : m_default_bb = default_edge->dest;
2334 : :
2335 : : /* Do the insertion of a case label into m_case_list. The labels are
2336 : : fed to us in descending order from the sorted vector of case labels used
2337 : : in the tree part of the middle end. So the list we construct is
2338 : : sorted in ascending order. */
2339 : :
2340 : 267914 : for (int i = clusters.length () - 1; i >= 0; i--)
2341 : : {
2342 : 173712 : case_tree_node *r = m_case_list;
2343 : 173712 : m_case_list = m_case_node_pool.allocate ();
2344 : 173712 : m_case_list->m_right = r;
2345 : 173712 : m_case_list->m_c = clusters[i];
2346 : : }
2347 : :
2348 : 47101 : record_phi_operand_mapping ();
2349 : :
2350 : : /* Split basic block that contains the gswitch statement. */
2351 : 47101 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2352 : 47101 : edge e;
2353 : 47101 : if (gsi_end_p (gsi))
2354 : 0 : e = split_block_after_labels (bb);
2355 : : else
2356 : : {
2357 : 47101 : gsi_prev (&gsi);
2358 : 47101 : e = split_block (bb, gsi_stmt (gsi));
2359 : : }
2360 : 47101 : bb = split_edge (e);
2361 : :
2362 : : /* Create new basic blocks for non-case clusters where specific expansion
2363 : : needs to happen. */
2364 : 220813 : for (unsigned i = 0; i < clusters.length (); i++)
2365 : 173712 : if (clusters[i]->get_type () != SIMPLE_CASE)
2366 : : {
2367 : 13908 : clusters[i]->m_case_bb = create_empty_bb (bb);
2368 : 13908 : clusters[i]->m_case_bb->count = bb->count;
2369 : 13908 : clusters[i]->m_case_bb->loop_father = bb->loop_father;
2370 : : }
2371 : :
2372 : : /* Do not do an extra work for a single cluster. */
2373 : 47101 : if (clusters.length () == 1
2374 : 58242 : && clusters[0]->get_type () != SIMPLE_CASE)
2375 : : {
2376 : 10073 : cluster *c = clusters[0];
2377 : 10073 : c->emit (index_expr, index_type,
2378 : : gimple_switch_default_label (m_switch), m_default_bb,
2379 : 10073 : gimple_location (m_switch));
2380 : 10073 : redirect_edge_succ (single_succ_edge (bb), c->m_case_bb);
2381 : : }
2382 : : else
2383 : : {
2384 : 37028 : emit (bb, index_expr, default_edge->probability, index_type);
2385 : :
2386 : : /* Emit cluster-specific switch handling. */
2387 : 200667 : for (unsigned i = 0; i < clusters.length (); i++)
2388 : 163639 : if (clusters[i]->get_type () != SIMPLE_CASE)
2389 : : {
2390 : 3835 : edge e = single_pred_edge (clusters[i]->m_case_bb);
2391 : 3835 : e->dest->count = e->src->count.apply_probability (e->probability);
2392 : 7670 : clusters[i]->emit (index_expr, index_type,
2393 : : gimple_switch_default_label (m_switch),
2394 : 3835 : m_default_bb, gimple_location (m_switch));
2395 : : }
2396 : : }
2397 : :
2398 : 47101 : fix_phi_operands_for_edges ();
2399 : :
2400 : 47101 : return true;
2401 : : }
2402 : :
2403 : : /* Before switch transformation, record all SSA_NAMEs defined in switch BB
2404 : : and used in a label basic block. */
2405 : :
2406 : : void
2407 : 47101 : switch_decision_tree::record_phi_operand_mapping ()
2408 : : {
2409 : 47101 : basic_block switch_bb = gimple_bb (m_switch);
2410 : : /* Record all PHI nodes that have to be fixed after conversion. */
2411 : 366525 : for (unsigned i = 0; i < m_case_bbs.length (); i++)
2412 : : {
2413 : 319424 : gphi_iterator gsi;
2414 : 319424 : basic_block bb = m_case_bbs[i];
2415 : 394909 : for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2416 : : {
2417 : 75485 : gphi *phi = gsi.phi ();
2418 : :
2419 : 214611 : for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
2420 : : {
2421 : 214611 : basic_block phi_src_bb = gimple_phi_arg_edge (phi, i)->src;
2422 : 214611 : if (phi_src_bb == switch_bb)
2423 : : {
2424 : 75485 : tree def = gimple_phi_arg_def (phi, i);
2425 : 75485 : tree result = gimple_phi_result (phi);
2426 : 75485 : m_phi_mapping.put (result, def);
2427 : 75485 : break;
2428 : : }
2429 : : }
2430 : : }
2431 : : }
2432 : 47101 : }
2433 : :
2434 : : /* Append new operands to PHI statements that were introduced due to
2435 : : addition of new edges to case labels. */
2436 : :
2437 : : void
2438 : 47101 : switch_decision_tree::fix_phi_operands_for_edges ()
2439 : : {
2440 : 47101 : gphi_iterator gsi;
2441 : :
2442 : 366525 : for (unsigned i = 0; i < m_case_bbs.length (); i++)
2443 : : {
2444 : 319424 : basic_block bb = m_case_bbs[i];
2445 : 394909 : for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
2446 : : {
2447 : 75485 : gphi *phi = gsi.phi ();
2448 : 520353 : for (unsigned j = 0; j < gimple_phi_num_args (phi); j++)
2449 : : {
2450 : 444868 : tree def = gimple_phi_arg_def (phi, j);
2451 : 444868 : if (def == NULL_TREE)
2452 : : {
2453 : 79823 : edge e = gimple_phi_arg_edge (phi, j);
2454 : 79823 : tree *definition
2455 : 79823 : = m_phi_mapping.get (gimple_phi_result (phi));
2456 : 79823 : gcc_assert (definition);
2457 : 79823 : add_phi_arg (phi, *definition, e, UNKNOWN_LOCATION);
2458 : : }
2459 : : }
2460 : : }
2461 : : }
2462 : 47101 : }
2463 : :
2464 : : /* Generate a decision tree, switching on INDEX_EXPR and jumping to
2465 : : one of the labels in CASE_LIST or to the DEFAULT_LABEL.
2466 : :
2467 : : We generate a binary decision tree to select the appropriate target
2468 : : code. */
2469 : :
2470 : : void
2471 : 37028 : switch_decision_tree::emit (basic_block bb, tree index_expr,
2472 : : profile_probability default_prob, tree index_type)
2473 : : {
2474 : 37028 : balance_case_nodes (&m_case_list, NULL);
2475 : :
2476 : 37028 : if (dump_file)
2477 : 17 : dump_function_to_file (current_function_decl, dump_file, dump_flags);
2478 : 37028 : if (dump_file && (dump_flags & TDF_DETAILS))
2479 : : {
2480 : 0 : int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
2481 : 0 : fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
2482 : 0 : gcc_assert (m_case_list != NULL);
2483 : 0 : dump_case_nodes (dump_file, m_case_list, indent_step, 0);
2484 : : }
2485 : :
2486 : 74056 : bb = emit_case_nodes (bb, index_expr, m_case_list, default_prob, index_type,
2487 : 37028 : gimple_location (m_switch));
2488 : :
2489 : 37028 : if (bb)
2490 : 35943 : emit_jump (bb, m_default_bb);
2491 : :
2492 : : /* Remove all edges and do just an edge that will reach default_bb. */
2493 : 37028 : bb = gimple_bb (m_switch);
2494 : 37028 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2495 : 37028 : gsi_remove (&gsi, true);
2496 : :
2497 : 37028 : delete_basic_block (bb);
2498 : 37028 : }
2499 : :
2500 : : /* Take an ordered list of case nodes
2501 : : and transform them into a near optimal binary tree,
2502 : : on the assumption that any target code selection value is as
2503 : : likely as any other.
2504 : :
2505 : : The transformation is performed by splitting the ordered
2506 : : list into two equal sections plus a pivot. The parts are
2507 : : then attached to the pivot as left and right branches. Each
2508 : : branch is then transformed recursively. */
2509 : :
2510 : : void
2511 : 202906 : switch_decision_tree::balance_case_nodes (case_tree_node **head,
2512 : : case_tree_node *parent)
2513 : : {
2514 : 202906 : case_tree_node *np;
2515 : :
2516 : 202906 : np = *head;
2517 : 202906 : if (np)
2518 : : {
2519 : 132511 : int i = 0;
2520 : 132511 : case_tree_node **npp;
2521 : 132511 : case_tree_node *left;
2522 : 132511 : profile_probability prob = profile_probability::never ();
2523 : :
2524 : : /* Count the number of entries on branch. */
2525 : :
2526 : 2359345 : while (np)
2527 : : {
2528 : 2226834 : i++;
2529 : 2226834 : prob += np->m_c->m_prob;
2530 : 2226834 : np = np->m_right;
2531 : : }
2532 : :
2533 : 132511 : if (i > 2)
2534 : : {
2535 : : /* Split this list if it is long enough for that to help. */
2536 : 82939 : npp = head;
2537 : 82939 : left = *npp;
2538 : 82939 : profile_probability pivot_prob = prob / 2;
2539 : :
2540 : : /* Find the place in the list that bisects the list's total cost
2541 : : by probability. */
2542 : 4144265 : while (1)
2543 : : {
2544 : : /* Skip nodes while their probability does not reach
2545 : : that amount. */
2546 : 2113602 : prob -= (*npp)->m_c->m_prob;
2547 : 2113602 : if ((prob.initialized_p () && prob < pivot_prob)
2548 : 2148250 : || ! (*npp)->m_right)
2549 : : break;
2550 : 2030663 : npp = &(*npp)->m_right;
2551 : : }
2552 : :
2553 : 82939 : np = *npp;
2554 : 82939 : *npp = 0;
2555 : 82939 : *head = np;
2556 : 82939 : np->m_parent = parent;
2557 : 82939 : np->m_left = left == np ? NULL : left;
2558 : :
2559 : : /* Optimize each of the two split parts. */
2560 : 82939 : balance_case_nodes (&np->m_left, np);
2561 : 82939 : balance_case_nodes (&np->m_right, np);
2562 : 82939 : np->m_c->m_subtree_prob = np->m_c->m_prob;
2563 : 82939 : if (np->m_left)
2564 : 81858 : np->m_c->m_subtree_prob += np->m_left->m_c->m_subtree_prob;
2565 : 82939 : if (np->m_right)
2566 : 13625 : np->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
2567 : : }
2568 : : else
2569 : : {
2570 : : /* Else leave this branch as one level,
2571 : : but fill in `parent' fields. */
2572 : 49572 : np = *head;
2573 : 49572 : np->m_parent = parent;
2574 : 49572 : np->m_c->m_subtree_prob = np->m_c->m_prob;
2575 : 80700 : for (; np->m_right; np = np->m_right)
2576 : : {
2577 : 31128 : np->m_right->m_parent = np;
2578 : 31128 : (*head)->m_c->m_subtree_prob += np->m_right->m_c->m_subtree_prob;
2579 : : }
2580 : : }
2581 : : }
2582 : 202906 : }
2583 : :
2584 : : /* Dump ROOT, a list or tree of case nodes, to file. */
2585 : :
2586 : : void
2587 : 0 : switch_decision_tree::dump_case_nodes (FILE *f, case_tree_node *root,
2588 : : int indent_step, int indent_level)
2589 : : {
2590 : 0 : if (root == 0)
2591 : 0 : return;
2592 : 0 : indent_level++;
2593 : :
2594 : 0 : dump_case_nodes (f, root->m_left, indent_step, indent_level);
2595 : :
2596 : 0 : fputs (";; ", f);
2597 : 0 : fprintf (f, "%*s", indent_step * indent_level, "");
2598 : 0 : root->m_c->dump (f);
2599 : 0 : root->m_c->m_prob.dump (f);
2600 : 0 : fputs (" subtree: ", f);
2601 : 0 : root->m_c->m_subtree_prob.dump (f);
2602 : 0 : fputs (")\n", f);
2603 : :
2604 : 0 : dump_case_nodes (f, root->m_right, indent_step, indent_level);
2605 : : }
2606 : :
2607 : :
2608 : : /* Add an unconditional jump to CASE_BB that happens in basic block BB. */
2609 : :
2610 : : void
2611 : 65995 : switch_decision_tree::emit_jump (basic_block bb, basic_block case_bb)
2612 : : {
2613 : 65995 : edge e = single_succ_edge (bb);
2614 : 65995 : redirect_edge_succ (e, case_bb);
2615 : 65995 : }
2616 : :
2617 : : /* Generate code to compare OP0 with OP1 so that the condition codes are
2618 : : set and to jump to LABEL_BB if the condition is true.
2619 : : COMPARISON is the GIMPLE comparison (EQ, NE, GT, etc.).
2620 : : PROB is the probability of jumping to LABEL_BB. */
2621 : :
2622 : : basic_block
2623 : 106607 : switch_decision_tree::emit_cmp_and_jump_insns (basic_block bb, tree op0,
2624 : : tree op1, tree_code comparison,
2625 : : basic_block label_bb,
2626 : : profile_probability prob,
2627 : : location_t loc)
2628 : : {
2629 : : // TODO: it's once called with lhs != index.
2630 : 106607 : op1 = fold_convert (TREE_TYPE (op0), op1);
2631 : :
2632 : 106607 : gcond *cond = gimple_build_cond (comparison, op0, op1, NULL_TREE, NULL_TREE);
2633 : 106607 : gimple_set_location (cond, loc);
2634 : 106607 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2635 : 106607 : gsi_insert_after (&gsi, cond, GSI_NEW_STMT);
2636 : :
2637 : 106607 : gcc_assert (single_succ_p (bb));
2638 : :
2639 : : /* Make a new basic block where false branch will take place. */
2640 : 106607 : edge false_edge = split_block (bb, cond);
2641 : 106607 : false_edge->flags = EDGE_FALSE_VALUE;
2642 : 106607 : false_edge->probability = prob.invert ();
2643 : 106607 : false_edge->dest->count = bb->count.apply_probability (prob.invert ());
2644 : :
2645 : 106607 : edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2646 : 106607 : true_edge->probability = prob;
2647 : :
2648 : 106607 : return false_edge->dest;
2649 : : }
2650 : :
2651 : : /* Generate code to jump to LABEL if OP0 and OP1 are equal.
2652 : : PROB is the probability of jumping to LABEL_BB.
2653 : : BB is a basic block where the new condition will be placed. */
2654 : :
2655 : : basic_block
2656 : 137872 : switch_decision_tree::do_jump_if_equal (basic_block bb, tree op0, tree op1,
2657 : : basic_block label_bb,
2658 : : profile_probability prob,
2659 : : location_t loc)
2660 : : {
2661 : 137872 : op1 = fold_convert (TREE_TYPE (op0), op1);
2662 : :
2663 : 137872 : gcond *cond = gimple_build_cond (EQ_EXPR, op0, op1, NULL_TREE, NULL_TREE);
2664 : 137872 : gimple_set_location (cond, loc);
2665 : 137872 : gimple_stmt_iterator gsi = gsi_last_bb (bb);
2666 : 137872 : gsi_insert_before (&gsi, cond, GSI_SAME_STMT);
2667 : :
2668 : 137872 : gcc_assert (single_succ_p (bb));
2669 : :
2670 : : /* Make a new basic block where false branch will take place. */
2671 : 137872 : edge false_edge = split_block (bb, cond);
2672 : 137872 : false_edge->flags = EDGE_FALSE_VALUE;
2673 : 137872 : false_edge->probability = prob.invert ();
2674 : 137872 : false_edge->dest->count = bb->count.apply_probability (prob.invert ());
2675 : :
2676 : 137872 : edge true_edge = make_edge (bb, label_bb, EDGE_TRUE_VALUE);
2677 : 137872 : true_edge->probability = prob;
2678 : :
2679 : 137872 : return false_edge->dest;
2680 : : }
2681 : :
2682 : : /* Emit step-by-step code to select a case for the value of INDEX.
2683 : : The thus generated decision tree follows the form of the
2684 : : case-node binary tree NODE, whose nodes represent test conditions.
2685 : : DEFAULT_PROB is probability of cases leading to default BB.
2686 : : INDEX_TYPE is the type of the index of the switch. */
2687 : :
2688 : : basic_block
2689 : 65995 : switch_decision_tree::emit_case_nodes (basic_block bb, tree index,
2690 : : case_tree_node *node,
2691 : : profile_probability default_prob,
2692 : : tree index_type, location_t loc)
2693 : : {
2694 : 146835 : profile_probability p;
2695 : :
2696 : : /* If node is null, we are done. */
2697 : 146835 : if (node == NULL)
2698 : : return bb;
2699 : :
2700 : : /* Single value case. */
2701 : 123158 : if (node->m_c->is_single_value_p ())
2702 : : {
2703 : : /* Node is single valued. First see if the index expression matches
2704 : : this node and then check our children, if any. */
2705 : 97391 : p = node->m_c->m_prob / (node->m_c->m_subtree_prob + default_prob);
2706 : 97391 : bb = do_jump_if_equal (bb, index, node->m_c->get_low (),
2707 : : node->m_c->m_case_bb, p, loc);
2708 : : /* Since this case is taken at this point, reduce its weight from
2709 : : subtree_weight. */
2710 : 97391 : node->m_c->m_subtree_prob -= node->m_c->m_prob;
2711 : :
2712 : 97391 : if (node->m_left != NULL && node->m_right != NULL)
2713 : : {
2714 : : /* 1) the node has both children
2715 : :
2716 : : If both children are single-valued cases with no
2717 : : children, finish up all the work. This way, we can save
2718 : : one ordered comparison. */
2719 : :
2720 : 11420 : if (!node->m_left->has_child ()
2721 : 7177 : && node->m_left->m_c->is_single_value_p ()
2722 : 6538 : && !node->m_right->has_child ()
2723 : 6353 : && node->m_right->m_c->is_single_value_p ())
2724 : : {
2725 : 6270 : p = (node->m_right->m_c->m_prob
2726 : 6270 : / (node->m_c->m_subtree_prob + default_prob));
2727 : 6270 : bb = do_jump_if_equal (bb, index, node->m_right->m_c->get_low (),
2728 : : node->m_right->m_c->m_case_bb, p, loc);
2729 : 6270 : node->m_c->m_subtree_prob -= node->m_right->m_c->m_prob;
2730 : :
2731 : 6270 : p = (node->m_left->m_c->m_prob
2732 : 6270 : / (node->m_c->m_subtree_prob + default_prob));
2733 : 6270 : bb = do_jump_if_equal (bb, index, node->m_left->m_c->get_low (),
2734 : : node->m_left->m_c->m_case_bb, p, loc);
2735 : : }
2736 : : else
2737 : : {
2738 : : /* Branch to a label where we will handle it later. */
2739 : 5150 : basic_block test_bb = split_edge (single_succ_edge (bb));
2740 : 5150 : redirect_edge_succ (single_pred_edge (test_bb),
2741 : 5150 : single_succ_edge (bb)->dest);
2742 : :
2743 : 15450 : p = ((node->m_right->m_c->m_subtree_prob + default_prob / 2)
2744 : 5150 : / (node->m_c->m_subtree_prob + default_prob));
2745 : 5150 : test_bb->count = bb->count.apply_probability (p);
2746 : 5150 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2747 : : GT_EXPR, test_bb, p, loc);
2748 : 5150 : default_prob /= 2;
2749 : :
2750 : : /* Handle the left-hand subtree. */
2751 : 5150 : bb = emit_case_nodes (bb, index, node->m_left,
2752 : : default_prob, index_type, loc);
2753 : :
2754 : : /* If the left-hand subtree fell through,
2755 : : don't let it fall into the right-hand subtree. */
2756 : 5150 : if (bb && m_default_bb)
2757 : 4551 : emit_jump (bb, m_default_bb);
2758 : :
2759 : 5150 : bb = emit_case_nodes (test_bb, index, node->m_right,
2760 : : default_prob, index_type, loc);
2761 : : }
2762 : : }
2763 : 85971 : else if (node->m_left == NULL && node->m_right != NULL)
2764 : : {
2765 : : /* 2) the node has only right child. */
2766 : :
2767 : : /* Here we have a right child but no left so we issue a conditional
2768 : : branch to default and process the right child.
2769 : :
2770 : : Omit the conditional branch to default if the right child
2771 : : does not have any children and is single valued; it would
2772 : : cost too much space to save so little time. */
2773 : :
2774 : 29219 : if (node->m_right->has_child ()
2775 : 28715 : || !node->m_right->m_c->is_single_value_p ())
2776 : : {
2777 : 3834 : p = ((default_prob / 2)
2778 : 1278 : / (node->m_c->m_subtree_prob + default_prob));
2779 : 1278 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (),
2780 : : LT_EXPR, m_default_bb, p, loc);
2781 : 1278 : default_prob /= 2;
2782 : :
2783 : 1278 : bb = emit_case_nodes (bb, index, node->m_right, default_prob,
2784 : : index_type, loc);
2785 : : }
2786 : : else
2787 : : {
2788 : : /* We cannot process node->right normally
2789 : : since we haven't ruled out the numbers less than
2790 : : this node's value. So handle node->right explicitly. */
2791 : 27941 : p = (node->m_right->m_c->m_subtree_prob
2792 : 27941 : / (node->m_c->m_subtree_prob + default_prob));
2793 : 27941 : bb = do_jump_if_equal (bb, index, node->m_right->m_c->get_low (),
2794 : : node->m_right->m_c->m_case_bb, p, loc);
2795 : : }
2796 : : }
2797 : 56752 : else if (node->m_left != NULL && node->m_right == NULL)
2798 : : {
2799 : : /* 3) just one subtree, on the left. Similar case as previous. */
2800 : :
2801 : 50595 : if (node->m_left->has_child ()
2802 : 0 : || !node->m_left->m_c->is_single_value_p ())
2803 : : {
2804 : 151785 : p = ((default_prob / 2)
2805 : 50595 : / (node->m_c->m_subtree_prob + default_prob));
2806 : 50595 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2807 : : GT_EXPR, m_default_bb, p, loc);
2808 : 50595 : default_prob /= 2;
2809 : :
2810 : 50595 : bb = emit_case_nodes (bb, index, node->m_left, default_prob,
2811 : : index_type, loc);
2812 : : }
2813 : : else
2814 : : {
2815 : : /* We cannot process node->left normally
2816 : : since we haven't ruled out the numbers less than
2817 : : this node's value. So handle node->left explicitly. */
2818 : 0 : p = (node->m_left->m_c->m_subtree_prob
2819 : 0 : / (node->m_c->m_subtree_prob + default_prob));
2820 : 0 : bb = do_jump_if_equal (bb, index, node->m_left->m_c->get_low (),
2821 : : node->m_left->m_c->m_case_bb, p, loc);
2822 : : }
2823 : : }
2824 : : }
2825 : : else
2826 : : {
2827 : : /* Node is a range. These cases are very similar to those for a single
2828 : : value, except that we do not start by testing whether this node
2829 : : is the one to branch to. */
2830 : 28701 : if (node->has_child () || node->m_c->get_type () != SIMPLE_CASE)
2831 : : {
2832 : 23817 : bool is_bt = node->m_c->get_type () == BIT_TEST;
2833 : 23817 : int parts = is_bt ? 3 : 2;
2834 : :
2835 : : /* Branch to a label where we will handle it later. */
2836 : 23817 : basic_block test_bb = split_edge (single_succ_edge (bb));
2837 : 23817 : redirect_edge_succ (single_pred_edge (test_bb),
2838 : 23817 : single_succ_edge (bb)->dest);
2839 : :
2840 : 23817 : profile_probability right_prob = profile_probability::never ();
2841 : 23817 : if (node->m_right)
2842 : 4114 : right_prob = node->m_right->m_c->m_subtree_prob;
2843 : 71451 : p = ((right_prob + default_prob / parts)
2844 : 23817 : / (node->m_c->m_subtree_prob + default_prob));
2845 : 23817 : test_bb->count = bb->count.apply_probability (p);
2846 : :
2847 : 23817 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_high (),
2848 : : GT_EXPR, test_bb, p, loc);
2849 : :
2850 : 23817 : default_prob /= parts;
2851 : 23817 : node->m_c->m_subtree_prob -= right_prob;
2852 : 23817 : if (is_bt)
2853 : 2509 : node->m_c->m_default_prob = default_prob;
2854 : :
2855 : : /* Value belongs to this node or to the left-hand subtree. */
2856 : 23817 : p = node->m_c->m_prob / (node->m_c->m_subtree_prob + default_prob);
2857 : 23817 : bb = emit_cmp_and_jump_insns (bb, index, node->m_c->get_low (),
2858 : : GE_EXPR, node->m_c->m_case_bb, p, loc);
2859 : :
2860 : : /* Handle the left-hand subtree. */
2861 : 23817 : bb = emit_case_nodes (bb, index, node->m_left, default_prob,
2862 : : index_type, loc);
2863 : :
2864 : : /* If the left-hand subtree fell through,
2865 : : don't let it fall into the right-hand subtree. */
2866 : 23817 : if (bb && m_default_bb)
2867 : 23551 : emit_jump (bb, m_default_bb);
2868 : :
2869 : 23817 : bb = emit_case_nodes (test_bb, index, node->m_right, default_prob,
2870 : : index_type, loc);
2871 : : }
2872 : : else
2873 : : {
2874 : : /* Node has no children so we check low and high bounds to remove
2875 : : redundant tests. Only one of the bounds can exist,
2876 : : since otherwise this node is bounded--a case tested already. */
2877 : 1950 : tree lhs, rhs;
2878 : 1950 : generate_range_test (bb, index, node->m_c->get_low (),
2879 : 1950 : node->m_c->get_high (), &lhs, &rhs);
2880 : 1950 : p = default_prob / (node->m_c->m_subtree_prob + default_prob);
2881 : :
2882 : 1950 : bb = emit_cmp_and_jump_insns (bb, lhs, rhs, GT_EXPR,
2883 : : m_default_bb, p, loc);
2884 : :
2885 : 1950 : emit_jump (bb, node->m_c->m_case_bb);
2886 : 1950 : return NULL;
2887 : : }
2888 : : }
2889 : :
2890 : : return bb;
2891 : : }
2892 : :
2893 : : /* The main function of the pass scans statements for switches and invokes
2894 : : process_switch on them. */
2895 : :
2896 : : namespace {
2897 : :
2898 : : const pass_data pass_data_convert_switch =
2899 : : {
2900 : : GIMPLE_PASS, /* type */
2901 : : "switchconv", /* name */
2902 : : OPTGROUP_NONE, /* optinfo_flags */
2903 : : TV_TREE_SWITCH_CONVERSION, /* tv_id */
2904 : : ( PROP_cfg | PROP_ssa ), /* properties_required */
2905 : : 0, /* properties_provided */
2906 : : 0, /* properties_destroyed */
2907 : : 0, /* todo_flags_start */
2908 : : TODO_update_ssa, /* todo_flags_finish */
2909 : : };
2910 : :
2911 : : class pass_convert_switch : public gimple_opt_pass
2912 : : {
2913 : : public:
2914 : 285081 : pass_convert_switch (gcc::context *ctxt)
2915 : 570162 : : gimple_opt_pass (pass_data_convert_switch, ctxt)
2916 : : {}
2917 : :
2918 : : /* opt_pass methods: */
2919 : 2441318 : bool gate (function *) final override
2920 : : {
2921 : 2441318 : return flag_tree_switch_conversion != 0;
2922 : : }
2923 : : unsigned int execute (function *) final override;
2924 : :
2925 : : }; // class pass_convert_switch
2926 : :
2927 : : unsigned int
2928 : 2340320 : pass_convert_switch::execute (function *fun)
2929 : : {
2930 : 2340320 : basic_block bb;
2931 : 2340320 : bool cfg_altered = false;
2932 : :
2933 : 14201159 : FOR_EACH_BB_FN (bb, fun)
2934 : : {
2935 : 35317344 : if (gswitch *stmt = safe_dyn_cast <gswitch *> (*gsi_last_bb (bb)))
2936 : : {
2937 : 28936 : if (dump_file)
2938 : : {
2939 : 43 : expanded_location loc = expand_location (gimple_location (stmt));
2940 : :
2941 : 43 : fprintf (dump_file, "beginning to process the following "
2942 : : "SWITCH statement (%s:%d) : ------- \n",
2943 : : loc.file, loc.line);
2944 : 43 : print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2945 : 43 : putc ('\n', dump_file);
2946 : : }
2947 : :
2948 : 28936 : switch_conversion sconv;
2949 : 28936 : sconv.expand (stmt);
2950 : 28936 : cfg_altered |= sconv.m_cfg_altered;
2951 : 28936 : if (!sconv.m_reason)
2952 : : {
2953 : 637 : if (dump_file)
2954 : : {
2955 : 39 : fputs ("Switch converted\n", dump_file);
2956 : 39 : fputs ("--------------------------------\n", dump_file);
2957 : : }
2958 : :
2959 : : /* Make no effort to update the post-dominator tree.
2960 : : It is actually not that hard for the transformations
2961 : : we have performed, but it is not supported
2962 : : by iterate_fix_dominators. */
2963 : 637 : free_dominance_info (CDI_POST_DOMINATORS);
2964 : : }
2965 : : else
2966 : : {
2967 : 28299 : if (dump_file)
2968 : : {
2969 : 4 : fputs ("Bailing out - ", dump_file);
2970 : 4 : fputs (sconv.m_reason, dump_file);
2971 : 4 : fputs ("\n--------------------------------\n", dump_file);
2972 : : }
2973 : : }
2974 : 28936 : }
2975 : : }
2976 : :
2977 : 2340320 : return cfg_altered ? TODO_cleanup_cfg : 0;;
2978 : : }
2979 : :
2980 : : } // anon namespace
2981 : :
2982 : : gimple_opt_pass *
2983 : 285081 : make_pass_convert_switch (gcc::context *ctxt)
2984 : : {
2985 : 285081 : return new pass_convert_switch (ctxt);
2986 : : }
2987 : :
2988 : : /* The main function of the pass scans statements for switches and invokes
2989 : : process_switch on them. */
2990 : :
2991 : : namespace {
2992 : :
2993 : : template <bool O0> class pass_lower_switch: public gimple_opt_pass
2994 : : {
2995 : : public:
2996 : 1710486 : pass_lower_switch (gcc::context *ctxt) : gimple_opt_pass (data, ctxt) {}
2997 : :
2998 : : static const pass_data data;
2999 : : opt_pass *
3000 : 285081 : clone () final override
3001 : : {
3002 : 285081 : return new pass_lower_switch<O0> (m_ctxt);
3003 : : }
3004 : :
3005 : : bool
3006 : 2474886 : gate (function *) final override
3007 : : {
3008 : 2474886 : return !O0 || !optimize;
3009 : : }
3010 : :
3011 : : unsigned int execute (function *fun) final override;
3012 : : }; // class pass_lower_switch
3013 : :
3014 : : template <bool O0>
3015 : : const pass_data pass_lower_switch<O0>::data = {
3016 : : GIMPLE_PASS, /* type */
3017 : : O0 ? "switchlower_O0" : "switchlower", /* name */
3018 : : OPTGROUP_NONE, /* optinfo_flags */
3019 : : TV_TREE_SWITCH_LOWERING, /* tv_id */
3020 : : ( PROP_cfg | PROP_ssa ), /* properties_required */
3021 : : 0, /* properties_provided */
3022 : : 0, /* properties_destroyed */
3023 : : 0, /* todo_flags_start */
3024 : : TODO_update_ssa | TODO_cleanup_cfg, /* todo_flags_finish */
3025 : : };
3026 : :
3027 : : template <bool O0>
3028 : : unsigned int
3029 : 1450721 : pass_lower_switch<O0>::execute (function *fun)
3030 : : {
3031 : : basic_block bb;
3032 : 1450721 : bool expanded = false;
3033 : :
3034 : 1450721 : auto_vec<gimple *> switch_statements;
3035 : 1450721 : switch_statements.create (1);
3036 : :
3037 : 15037997 : FOR_EACH_BB_FN (bb, fun)
3038 : : {
3039 : 26802778 : if (gswitch *swtch = safe_dyn_cast <gswitch *> (*gsi_last_bb (bb)))
3040 : : {
3041 : : if (!O0)
3042 : 31888 : group_case_labels_stmt (swtch);
3043 : 47092 : switch_statements.safe_push (swtch);
3044 : : }
3045 : : }
3046 : :
3047 : 1497813 : for (unsigned i = 0; i < switch_statements.length (); i++)
3048 : : {
3049 : 47092 : gimple *stmt = switch_statements[i];
3050 : 47092 : if (dump_file)
3051 : : {
3052 : 24 : expanded_location loc = expand_location (gimple_location (stmt));
3053 : :
3054 : 24 : fprintf (dump_file, "beginning to process the following "
3055 : : "SWITCH statement (%s:%d) : ------- \n",
3056 : : loc.file, loc.line);
3057 : 24 : print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3058 : 24 : putc ('\n', dump_file);
3059 : : }
3060 : :
3061 : 47092 : gswitch *swtch = dyn_cast<gswitch *> (stmt);
3062 : : if (swtch)
3063 : : {
3064 : 47092 : switch_decision_tree dt (swtch);
3065 : 47092 : expanded |= dt.analyze_switch_statement ();
3066 : 47092 : }
3067 : : }
3068 : :
3069 : 1450721 : if (expanded)
3070 : : {
3071 : 34611 : free_dominance_info (CDI_DOMINATORS);
3072 : 34611 : free_dominance_info (CDI_POST_DOMINATORS);
3073 : 34611 : mark_virtual_operands_for_renaming (cfun);
3074 : : }
3075 : :
3076 : 1450721 : return 0;
3077 : 1450721 : }
3078 : :
3079 : : } // anon namespace
3080 : :
3081 : : gimple_opt_pass *
3082 : 285081 : make_pass_lower_switch_O0 (gcc::context *ctxt)
3083 : : {
3084 : 285081 : return new pass_lower_switch<true> (ctxt);
3085 : : }
3086 : : gimple_opt_pass *
3087 : 285081 : make_pass_lower_switch (gcc::context *ctxt)
3088 : : {
3089 : 285081 : return new pass_lower_switch<false> (ctxt);
3090 : : }
|