coretypes.h: Include input.h and as-a.h.
[platform/upstream/gcc.git] / gcc / tree-switch-conversion.c
1 /* Lower GIMPLE_SWITCH expressions to something more efficient than
2    a jump table.
3    Copyright (C) 2006-2015 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 "tm.h"
29 #include "params.h"
30 #include "flags.h"
31 #include "alias.h"
32 #include "symtab.h"
33 #include "tree.h"
34 #include "fold-const.h"
35 #include "varasm.h"
36 #include "stor-layout.h"
37 #include "predict.h"
38 #include "hard-reg-set.h"
39 #include "function.h"
40 #include "dominance.h"
41 #include "cfg.h"
42 #include "cfganal.h"
43 #include "basic-block.h"
44 #include "tree-ssa-alias.h"
45 #include "internal-fn.h"
46 #include "gimple-expr.h"
47 #include "gimple.h"
48 #include "gimplify.h"
49 #include "gimple-iterator.h"
50 #include "gimplify-me.h"
51 #include "gimple-ssa.h"
52 #include "plugin-api.h"
53 #include "ipa-ref.h"
54 #include "cgraph.h"
55 #include "tree-cfg.h"
56 #include "tree-phinodes.h"
57 #include "stringpool.h"
58 #include "tree-ssanames.h"
59 #include "tree-pass.h"
60 #include "gimple-pretty-print.h"
61 #include "cfgloop.h"
62
63 /* ??? For lang_hooks.types.type_for_mode, but is there a word_mode
64    type in the GIMPLE type system that is language-independent?  */
65 #include "langhooks.h"
66
67 /* Need to include expr.h and optabs.h for lshift_cheap_p.  */
68 #include "rtl.h"
69 #include "insn-config.h"
70 #include "expmed.h"
71 #include "dojump.h"
72 #include "explow.h"
73 #include "calls.h"
74 #include "emit-rtl.h"
75 #include "stmt.h"
76 #include "expr.h"
77 #include "insn-codes.h"
78 #include "optabs.h"
79 \f
80 /* Maximum number of case bit tests.
81    FIXME: This should be derived from PARAM_CASE_VALUES_THRESHOLD and
82           targetm.case_values_threshold(), or be its own param.  */
83 #define MAX_CASE_BIT_TESTS  3
84
85 /* Split the basic block at the statement pointed to by GSIP, and insert
86    a branch to the target basic block of E_TRUE conditional on tree
87    expression COND.
88
89    It is assumed that there is already an edge from the to-be-split
90    basic block to E_TRUE->dest block.  This edge is removed, and the
91    profile information on the edge is re-used for the new conditional
92    jump.
93    
94    The CFG is updated.  The dominator tree will not be valid after
95    this transformation, but the immediate dominators are updated if
96    UPDATE_DOMINATORS is true.
97    
98    Returns the newly created basic block.  */
99
100 static basic_block
101 hoist_edge_and_branch_if_true (gimple_stmt_iterator *gsip,
102                                tree cond, edge e_true,
103                                bool update_dominators)
104 {
105   tree tmp;
106   gcond *cond_stmt;
107   edge e_false;
108   basic_block new_bb, split_bb = gsi_bb (*gsip);
109   bool dominated_e_true = false;
110
111   gcc_assert (e_true->src == split_bb);
112
113   if (update_dominators
114       && get_immediate_dominator (CDI_DOMINATORS, e_true->dest) == split_bb)
115     dominated_e_true = true;
116
117   tmp = force_gimple_operand_gsi (gsip, cond, /*simple=*/true, NULL,
118                                   /*before=*/true, GSI_SAME_STMT);
119   cond_stmt = gimple_build_cond_from_tree (tmp, NULL_TREE, NULL_TREE);
120   gsi_insert_before (gsip, cond_stmt, GSI_SAME_STMT);
121
122   e_false = split_block (split_bb, cond_stmt);
123   new_bb = e_false->dest;
124   redirect_edge_pred (e_true, split_bb);
125
126   e_true->flags &= ~EDGE_FALLTHRU;
127   e_true->flags |= EDGE_TRUE_VALUE;
128
129   e_false->flags &= ~EDGE_FALLTHRU;
130   e_false->flags |= EDGE_FALSE_VALUE;
131   e_false->probability = REG_BR_PROB_BASE - e_true->probability;
132   e_false->count = split_bb->count - e_true->count;
133   new_bb->count = e_false->count;
134
135   if (update_dominators)
136     {
137       if (dominated_e_true)
138         set_immediate_dominator (CDI_DOMINATORS, e_true->dest, split_bb);
139       set_immediate_dominator (CDI_DOMINATORS, e_false->dest, split_bb);
140     }
141
142   return new_bb;
143 }
144
145
146 /* Return true if a switch should be expanded as a bit test.
147    RANGE is the difference between highest and lowest case.
148    UNIQ is number of unique case node targets, not counting the default case.
149    COUNT is the number of comparisons needed, not counting the default case.  */
150
151 static bool
152 expand_switch_using_bit_tests_p (tree range,
153                                  unsigned int uniq,
154                                  unsigned int count, bool speed_p)
155 {
156   return (((uniq == 1 && count >= 3)
157            || (uniq == 2 && count >= 5)
158            || (uniq == 3 && count >= 6))
159           && lshift_cheap_p (speed_p)
160           && compare_tree_int (range, GET_MODE_BITSIZE (word_mode)) < 0
161           && compare_tree_int (range, 0) > 0);
162 }
163 \f
164 /* Implement switch statements with bit tests
165
166 A GIMPLE switch statement can be expanded to a short sequence of bit-wise
167 comparisons.  "switch(x)" is converted into "if ((1 << (x-MINVAL)) & CST)"
168 where CST and MINVAL are integer constants.  This is better than a series
169 of compare-and-banch insns in some cases,  e.g. we can implement:
170
171         if ((x==4) || (x==6) || (x==9) || (x==11))
172
173 as a single bit test:
174
175         if ((1<<x) & ((1<<4)|(1<<6)|(1<<9)|(1<<11)))
176
177 This transformation is only applied if the number of case targets is small,
178 if CST constains at least 3 bits, and "1 << x" is cheap.  The bit tests are
179 performed in "word_mode".
180
181 The following example shows the code the transformation generates:
182
183         int bar(int x)
184         {
185                 switch (x)
186                 {
187                 case '0':  case '1':  case '2':  case '3':  case '4':
188                 case '5':  case '6':  case '7':  case '8':  case '9':
189                 case 'A':  case 'B':  case 'C':  case 'D':  case 'E':
190                 case 'F':
191                         return 1;
192                 }
193                 return 0;
194         }
195
196 ==>
197
198         bar (int x)
199         {
200                 tmp1 = x - 48;
201                 if (tmp1 > (70 - 48)) goto L2;
202                 tmp2 = 1 << tmp1;
203                 tmp3 = 0b11111100000001111111111;
204                 if ((tmp2 & tmp3) != 0) goto L1 ; else goto L2;
205         L1:
206                 return 1;
207         L2:
208                 return 0;
209         }
210
211 TODO: There are still some improvements to this transformation that could
212 be implemented:
213
214 * A narrower mode than word_mode could be used if that is cheaper, e.g.
215   for x86_64 where a narrower-mode shift may result in smaller code.
216
217 * The compounded constant could be shifted rather than the one.  The
218   test would be either on the sign bit or on the least significant bit,
219   depending on the direction of the shift.  On some machines, the test
220   for the branch would be free if the bit to test is already set by the
221   shift operation.
222
223 This transformation was contributed by Roger Sayle, see this e-mail:
224    http://gcc.gnu.org/ml/gcc-patches/2003-01/msg01950.html
225 */
226
227 /* A case_bit_test represents a set of case nodes that may be
228    selected from using a bit-wise comparison.  HI and LO hold
229    the integer to be tested against, TARGET_EDGE contains the
230    edge to the basic block to jump to upon success and BITS
231    counts the number of case nodes handled by this test,
232    typically the number of bits set in HI:LO.  The LABEL field
233    is used to quickly identify all cases in this set without
234    looking at label_to_block for every case label.  */
235
236 struct case_bit_test
237 {
238   wide_int mask;
239   edge target_edge;
240   tree label;
241   int bits;
242 };
243
244 /* Comparison function for qsort to order bit tests by decreasing
245    probability of execution.  Our best guess comes from a measured
246    profile.  If the profile counts are equal, break even on the
247    number of case nodes, i.e. the node with the most cases gets
248    tested first.
249
250    TODO: Actually this currently runs before a profile is available.
251    Therefore the case-as-bit-tests transformation should be done
252    later in the pass pipeline, or something along the lines of
253    "Efficient and effective branch reordering using profile data"
254    (Yang et. al., 2002) should be implemented (although, how good
255    is a paper is called "Efficient and effective ..." when the
256    latter is implied by the former, but oh well...).  */
257
258 static int
259 case_bit_test_cmp (const void *p1, const void *p2)
260 {
261   const struct case_bit_test *const d1 = (const struct case_bit_test *) p1;
262   const struct case_bit_test *const d2 = (const struct case_bit_test *) p2;
263
264   if (d2->target_edge->count != d1->target_edge->count)
265     return d2->target_edge->count - d1->target_edge->count;
266   if (d2->bits != d1->bits)
267     return d2->bits - d1->bits;
268
269   /* Stabilize the sort.  */
270   return LABEL_DECL_UID (d2->label) - LABEL_DECL_UID (d1->label);
271 }
272
273 /*  Expand a switch statement by a short sequence of bit-wise
274     comparisons.  "switch(x)" is effectively converted into
275     "if ((1 << (x-MINVAL)) & CST)" where CST and MINVAL are
276     integer constants.
277
278     INDEX_EXPR is the value being switched on.
279
280     MINVAL is the lowest case value of in the case nodes,
281     and RANGE is highest value minus MINVAL.  MINVAL and RANGE
282     are not guaranteed to be of the same type as INDEX_EXPR
283     (the gimplifier doesn't change the type of case label values,
284     and MINVAL and RANGE are derived from those values).
285     MAXVAL is MINVAL + RANGE.
286
287     There *MUST* be MAX_CASE_BIT_TESTS or less unique case
288     node targets.  */
289
290 static void
291 emit_case_bit_tests (gswitch *swtch, tree index_expr,
292                      tree minval, tree range, tree maxval)
293 {
294   struct case_bit_test test[MAX_CASE_BIT_TESTS];
295   unsigned int i, j, k;
296   unsigned int count;
297
298   basic_block switch_bb = gimple_bb (swtch);
299   basic_block default_bb, new_default_bb, new_bb;
300   edge default_edge;
301   bool update_dom = dom_info_available_p (CDI_DOMINATORS);
302
303   vec<basic_block> bbs_to_fix_dom = vNULL;
304
305   tree index_type = TREE_TYPE (index_expr);
306   tree unsigned_index_type = unsigned_type_for (index_type);
307   unsigned int branch_num = gimple_switch_num_labels (swtch);
308
309   gimple_stmt_iterator gsi;
310   gassign *shift_stmt;
311
312   tree idx, tmp, csui;
313   tree word_type_node = lang_hooks.types.type_for_mode (word_mode, 1);
314   tree word_mode_zero = fold_convert (word_type_node, integer_zero_node);
315   tree word_mode_one = fold_convert (word_type_node, integer_one_node);
316   int prec = TYPE_PRECISION (word_type_node);
317   wide_int wone = wi::one (prec);
318
319   memset (&test, 0, sizeof (test));
320
321   /* Get the edge for the default case.  */
322   tmp = gimple_switch_default_label (swtch);
323   default_bb = label_to_block (CASE_LABEL (tmp));
324   default_edge = find_edge (switch_bb, default_bb);
325
326   /* Go through all case labels, and collect the case labels, profile
327      counts, and other information we need to build the branch tests.  */
328   count = 0;
329   for (i = 1; i < branch_num; i++)
330     {
331       unsigned int lo, hi;
332       tree cs = gimple_switch_label (swtch, i);
333       tree label = CASE_LABEL (cs);
334       edge e = find_edge (switch_bb, label_to_block (label));
335       for (k = 0; k < count; k++)
336         if (e == test[k].target_edge)
337           break;
338
339       if (k == count)
340         {
341           gcc_checking_assert (count < MAX_CASE_BIT_TESTS);
342           test[k].mask = wi::zero (prec);
343           test[k].target_edge = e;
344           test[k].label = label;
345           test[k].bits = 1;
346           count++;
347         }
348       else
349         test[k].bits++;
350
351       lo = tree_to_uhwi (int_const_binop (MINUS_EXPR,
352                                           CASE_LOW (cs), minval));
353       if (CASE_HIGH (cs) == NULL_TREE)
354         hi = lo;
355       else
356         hi = tree_to_uhwi (int_const_binop (MINUS_EXPR,
357                                             CASE_HIGH (cs), minval));
358
359       for (j = lo; j <= hi; j++)
360         test[k].mask |= wi::lshift (wone, j);
361     }
362
363   qsort (test, count, sizeof (*test), case_bit_test_cmp);
364
365   /* If all values are in the 0 .. BITS_PER_WORD-1 range, we can get rid of
366      the minval subtractions, but it might make the mask constants more
367      expensive.  So, compare the costs.  */
368   if (compare_tree_int (minval, 0) > 0
369       && compare_tree_int (maxval, GET_MODE_BITSIZE (word_mode)) < 0)
370     {
371       int cost_diff;
372       HOST_WIDE_INT m = tree_to_uhwi (minval);
373       rtx reg = gen_raw_REG (word_mode, 10000);
374       bool speed_p = optimize_bb_for_speed_p (gimple_bb (swtch));
375       cost_diff = set_rtx_cost (gen_rtx_PLUS (word_mode, reg,
376                                               GEN_INT (-m)), speed_p);
377       for (i = 0; i < count; i++)
378         {
379           rtx r = immed_wide_int_const (test[i].mask, word_mode);
380           cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r), speed_p);
381           r = immed_wide_int_const (wi::lshift (test[i].mask, m), word_mode);
382           cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r), speed_p);
383         }
384       if (cost_diff > 0)
385         {
386           for (i = 0; i < count; i++)
387             test[i].mask = wi::lshift (test[i].mask, m);
388           minval = build_zero_cst (TREE_TYPE (minval));
389           range = maxval;
390         }
391     }
392
393   /* We generate two jumps to the default case label.
394      Split the default edge, so that we don't have to do any PHI node
395      updating.  */
396   new_default_bb = split_edge (default_edge);
397
398   if (update_dom)
399     {
400       bbs_to_fix_dom.create (10);
401       bbs_to_fix_dom.quick_push (switch_bb);
402       bbs_to_fix_dom.quick_push (default_bb);
403       bbs_to_fix_dom.quick_push (new_default_bb);
404     }
405
406   /* Now build the test-and-branch code.  */
407
408   gsi = gsi_last_bb (switch_bb);
409
410   /* idx = (unsigned)x - minval.  */
411   idx = fold_convert (unsigned_index_type, index_expr);
412   idx = fold_build2 (MINUS_EXPR, unsigned_index_type, idx,
413                      fold_convert (unsigned_index_type, minval));
414   idx = force_gimple_operand_gsi (&gsi, idx,
415                                   /*simple=*/true, NULL_TREE,
416                                   /*before=*/true, GSI_SAME_STMT);
417
418   /* if (idx > range) goto default */
419   range = force_gimple_operand_gsi (&gsi,
420                                     fold_convert (unsigned_index_type, range),
421                                     /*simple=*/true, NULL_TREE,
422                                     /*before=*/true, GSI_SAME_STMT);
423   tmp = fold_build2 (GT_EXPR, boolean_type_node, idx, range);
424   new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, default_edge, update_dom);
425   if (update_dom)
426     bbs_to_fix_dom.quick_push (new_bb);
427   gcc_assert (gimple_bb (swtch) == new_bb);
428   gsi = gsi_last_bb (new_bb);
429
430   /* Any blocks dominated by the GIMPLE_SWITCH, but that are not successors
431      of NEW_BB, are still immediately dominated by SWITCH_BB.  Make it so.  */
432   if (update_dom)
433     {
434       vec<basic_block> dom_bbs;
435       basic_block dom_son;
436
437       dom_bbs = get_dominated_by (CDI_DOMINATORS, new_bb);
438       FOR_EACH_VEC_ELT (dom_bbs, i, dom_son)
439         {
440           edge e = find_edge (new_bb, dom_son);
441           if (e && single_pred_p (e->dest))
442             continue;
443           set_immediate_dominator (CDI_DOMINATORS, dom_son, switch_bb);
444           bbs_to_fix_dom.safe_push (dom_son);
445         }
446       dom_bbs.release ();
447     }
448
449   /* csui = (1 << (word_mode) idx) */
450   csui = make_ssa_name (word_type_node);
451   tmp = fold_build2 (LSHIFT_EXPR, word_type_node, word_mode_one,
452                      fold_convert (word_type_node, idx));
453   tmp = force_gimple_operand_gsi (&gsi, tmp,
454                                   /*simple=*/false, NULL_TREE,
455                                   /*before=*/true, GSI_SAME_STMT);
456   shift_stmt = gimple_build_assign (csui, tmp);
457   gsi_insert_before (&gsi, shift_stmt, GSI_SAME_STMT);
458   update_stmt (shift_stmt);
459
460   /* for each unique set of cases:
461         if (const & csui) goto target  */
462   for (k = 0; k < count; k++)
463     {
464       tmp = wide_int_to_tree (word_type_node, test[k].mask);
465       tmp = fold_build2 (BIT_AND_EXPR, word_type_node, csui, tmp);
466       tmp = force_gimple_operand_gsi (&gsi, tmp,
467                                       /*simple=*/true, NULL_TREE,
468                                       /*before=*/true, GSI_SAME_STMT);
469       tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, word_mode_zero);
470       new_bb = hoist_edge_and_branch_if_true (&gsi, tmp, test[k].target_edge,
471                                               update_dom);
472       if (update_dom)
473         bbs_to_fix_dom.safe_push (new_bb);
474       gcc_assert (gimple_bb (swtch) == new_bb);
475       gsi = gsi_last_bb (new_bb);
476     }
477
478   /* We should have removed all edges now.  */
479   gcc_assert (EDGE_COUNT (gsi_bb (gsi)->succs) == 0);
480
481   /* If nothing matched, go to the default label.  */
482   make_edge (gsi_bb (gsi), new_default_bb, EDGE_FALLTHRU);
483
484   /* The GIMPLE_SWITCH is now redundant.  */
485   gsi_remove (&gsi, true);
486
487   if (update_dom)
488     {
489       /* Fix up the dominator tree.  */
490       iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
491       bbs_to_fix_dom.release ();
492     }
493 }
494 \f
495 /*
496      Switch initialization conversion
497
498 The following pass changes simple initializations of scalars in a switch
499 statement into initializations from a static array.  Obviously, the values
500 must be constant and known at compile time and a default branch must be
501 provided.  For example, the following code:
502
503         int a,b;
504
505         switch (argc)
506         {
507          case 1:
508          case 2:
509                 a_1 = 8;
510                 b_1 = 6;
511                 break;
512          case 3:
513                 a_2 = 9;
514                 b_2 = 5;
515                 break;
516          case 12:
517                 a_3 = 10;
518                 b_3 = 4;
519                 break;
520          default:
521                 a_4 = 16;
522                 b_4 = 1;
523                 break;
524         }
525         a_5 = PHI <a_1, a_2, a_3, a_4>
526         b_5 = PHI <b_1, b_2, b_3, b_4>
527
528
529 is changed into:
530
531         static const int = CSWTCH01[] = {6, 6, 5, 1, 1, 1, 1, 1, 1, 1, 1, 4};
532         static const int = CSWTCH02[] = {8, 8, 9, 16, 16, 16, 16, 16, 16, 16,
533                                  16, 16, 10};
534
535         if (((unsigned) argc) - 1 < 11)
536           {
537             a_6 = CSWTCH02[argc - 1];
538             b_6 = CSWTCH01[argc - 1];
539           }
540         else
541           {
542             a_7 = 16;
543             b_7 = 1;
544           }
545         a_5 = PHI <a_6, a_7>
546         b_b = PHI <b_6, b_7>
547
548 There are further constraints.  Specifically, the range of values across all
549 case labels must not be bigger than SWITCH_CONVERSION_BRANCH_RATIO (default
550 eight) times the number of the actual switch branches.
551
552 This transformation was contributed by Martin Jambor, see this e-mail:
553    http://gcc.gnu.org/ml/gcc-patches/2008-07/msg00011.html  */
554
555 /* The main structure of the pass.  */
556 struct switch_conv_info
557 {
558   /* The expression used to decide the switch branch.  */
559   tree index_expr;
560
561   /* The following integer constants store the minimum and maximum value
562      covered by the case labels.  */
563   tree range_min;
564   tree range_max;
565
566   /* The difference between the above two numbers.  Stored here because it
567      is used in all the conversion heuristics, as well as for some of the
568      transformation, and it is expensive to re-compute it all the time.  */
569   tree range_size;
570
571   /* Basic block that contains the actual GIMPLE_SWITCH.  */
572   basic_block switch_bb;
573
574   /* Basic block that is the target of the default case.  */
575   basic_block default_bb;
576
577   /* The single successor block of all branches out of the GIMPLE_SWITCH,
578      if such a block exists.  Otherwise NULL.  */
579   basic_block final_bb;
580
581   /* The probability of the default edge in the replaced switch.  */
582   int default_prob;
583
584   /* The count of the default edge in the replaced switch.  */
585   gcov_type default_count;
586
587   /* Combined count of all other (non-default) edges in the replaced switch.  */
588   gcov_type other_count;
589
590   /* Number of phi nodes in the final bb (that we'll be replacing).  */
591   int phi_count;
592
593   /* Array of default values, in the same order as phi nodes.  */
594   tree *default_values;
595
596   /* Constructors of new static arrays.  */
597   vec<constructor_elt, va_gc> **constructors;
598
599   /* Array of ssa names that are initialized with a value from a new static
600      array.  */
601   tree *target_inbound_names;
602
603   /* Array of ssa names that are initialized with the default value if the
604      switch expression is out of range.  */
605   tree *target_outbound_names;
606
607   /* The first load statement that loads a temporary from a new static array.
608    */
609   gimple arr_ref_first;
610
611   /* The last load statement that loads a temporary from a new static array.  */
612   gimple arr_ref_last;
613
614   /* String reason why the case wasn't a good candidate that is written to the
615      dump file, if there is one.  */
616   const char *reason;
617
618   /* Parameters for expand_switch_using_bit_tests.  Should be computed
619      the same way as in expand_case.  */
620   unsigned int uniq;
621   unsigned int count;
622 };
623
624 /* Collect information about GIMPLE_SWITCH statement SWTCH into INFO.  */
625
626 static void
627 collect_switch_conv_info (gswitch *swtch, struct switch_conv_info *info)
628 {
629   unsigned int branch_num = gimple_switch_num_labels (swtch);
630   tree min_case, max_case;
631   unsigned int count, i;
632   edge e, e_default;
633   edge_iterator ei;
634
635   memset (info, 0, sizeof (*info));
636
637   /* The gimplifier has already sorted the cases by CASE_LOW and ensured there
638      is a default label which is the first in the vector.
639      Collect the bits we can deduce from the CFG.  */
640   info->index_expr = gimple_switch_index (swtch);
641   info->switch_bb = gimple_bb (swtch);
642   info->default_bb =
643     label_to_block (CASE_LABEL (gimple_switch_default_label (swtch)));
644   e_default = find_edge (info->switch_bb, info->default_bb);
645   info->default_prob = e_default->probability;
646   info->default_count = e_default->count;
647   FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
648     if (e != e_default)
649       info->other_count += e->count;
650
651   /* See if there is one common successor block for all branch
652      targets.  If it exists, record it in FINAL_BB.
653      Start with the destination of the default case as guess
654      or its destination in case it is a forwarder block.  */
655   if (! single_pred_p (e_default->dest))
656     info->final_bb = e_default->dest;
657   else if (single_succ_p (e_default->dest)
658            && ! single_pred_p (single_succ (e_default->dest)))
659     info->final_bb = single_succ (e_default->dest);
660   /* Require that all switch destinations are either that common
661      FINAL_BB or a forwarder to it.  */
662   if (info->final_bb)
663     FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
664       {
665         if (e->dest == info->final_bb)
666           continue;
667
668         if (single_pred_p (e->dest)
669             && single_succ_p (e->dest)
670             && single_succ (e->dest) == info->final_bb)
671           continue;
672
673         info->final_bb = NULL;
674         break;
675       }
676
677   /* Get upper and lower bounds of case values, and the covered range.  */
678   min_case = gimple_switch_label (swtch, 1);
679   max_case = gimple_switch_label (swtch, branch_num - 1);
680
681   info->range_min = CASE_LOW (min_case);
682   if (CASE_HIGH (max_case) != NULL_TREE)
683     info->range_max = CASE_HIGH (max_case);
684   else
685     info->range_max = CASE_LOW (max_case);
686
687   info->range_size =
688     int_const_binop (MINUS_EXPR, info->range_max, info->range_min);
689
690   /* Get a count of the number of case labels.  Single-valued case labels
691      simply count as one, but a case range counts double, since it may
692      require two compares if it gets lowered as a branching tree.  */
693   count = 0;
694   for (i = 1; i < branch_num; i++)
695     {
696       tree elt = gimple_switch_label (swtch, i);
697       count++;
698       if (CASE_HIGH (elt)
699           && ! tree_int_cst_equal (CASE_LOW (elt), CASE_HIGH (elt)))
700         count++;
701     }
702   info->count = count;
703  
704   /* Get the number of unique non-default targets out of the GIMPLE_SWITCH
705      block.  Assume a CFG cleanup would have already removed degenerate
706      switch statements, this allows us to just use EDGE_COUNT.  */
707   info->uniq = EDGE_COUNT (gimple_bb (swtch)->succs) - 1;
708 }
709
710 /* Checks whether the range given by individual case statements of the SWTCH
711    switch statement isn't too big and whether the number of branches actually
712    satisfies the size of the new array.  */
713
714 static bool
715 check_range (struct switch_conv_info *info)
716 {
717   gcc_assert (info->range_size);
718   if (!tree_fits_uhwi_p (info->range_size))
719     {
720       info->reason = "index range way too large or otherwise unusable";
721       return false;
722     }
723
724   if (tree_to_uhwi (info->range_size)
725       > ((unsigned) info->count * SWITCH_CONVERSION_BRANCH_RATIO))
726     {
727       info->reason = "the maximum range-branch ratio exceeded";
728       return false;
729     }
730
731   return true;
732 }
733
734 /* Checks whether all but the FINAL_BB basic blocks are empty.  */
735
736 static bool
737 check_all_empty_except_final (struct switch_conv_info *info)
738 {
739   edge e;
740   edge_iterator ei;
741
742   FOR_EACH_EDGE (e, ei, info->switch_bb->succs)
743     {
744       if (e->dest == info->final_bb)
745         continue;
746
747       if (!empty_block_p (e->dest))
748         {
749           info->reason = "bad case - a non-final BB not empty";
750           return false;
751         }
752     }
753
754   return true;
755 }
756
757 /* This function checks whether all required values in phi nodes in final_bb
758    are constants.  Required values are those that correspond to a basic block
759    which is a part of the examined switch statement.  It returns true if the
760    phi nodes are OK, otherwise false.  */
761
762 static bool
763 check_final_bb (struct switch_conv_info *info)
764 {
765   gphi_iterator gsi;
766
767   info->phi_count = 0;
768   for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
769     {
770       gphi *phi = gsi.phi ();
771       unsigned int i;
772
773       info->phi_count++;
774
775       for (i = 0; i < gimple_phi_num_args (phi); i++)
776         {
777           basic_block bb = gimple_phi_arg_edge (phi, i)->src;
778
779           if (bb == info->switch_bb
780               || (single_pred_p (bb) && single_pred (bb) == info->switch_bb))
781             {
782               tree reloc, val;
783
784               val = gimple_phi_arg_def (phi, i);
785               if (!is_gimple_ip_invariant (val))
786                 {
787                   info->reason = "non-invariant value from a case";
788                   return false; /* Non-invariant argument.  */
789                 }
790               reloc = initializer_constant_valid_p (val, TREE_TYPE (val));
791               if ((flag_pic && reloc != null_pointer_node)
792                   || (!flag_pic && reloc == NULL_TREE))
793                 {
794                   if (reloc)
795                     info->reason
796                       = "value from a case would need runtime relocations";
797                   else
798                     info->reason
799                       = "value from a case is not a valid initializer";
800                   return false;
801                 }
802             }
803         }
804     }
805
806   return true;
807 }
808
809 /* The following function allocates default_values, target_{in,out}_names and
810    constructors arrays.  The last one is also populated with pointers to
811    vectors that will become constructors of new arrays.  */
812
813 static void
814 create_temp_arrays (struct switch_conv_info *info)
815 {
816   int i;
817
818   info->default_values = XCNEWVEC (tree, info->phi_count * 3);
819   /* ??? Macros do not support multi argument templates in their
820      argument list.  We create a typedef to work around that problem.  */
821   typedef vec<constructor_elt, va_gc> *vec_constructor_elt_gc;
822   info->constructors = XCNEWVEC (vec_constructor_elt_gc, info->phi_count);
823   info->target_inbound_names = info->default_values + info->phi_count;
824   info->target_outbound_names = info->target_inbound_names + info->phi_count;
825   for (i = 0; i < info->phi_count; i++)
826     vec_alloc (info->constructors[i], tree_to_uhwi (info->range_size) + 1);
827 }
828
829 /* Free the arrays created by create_temp_arrays().  The vectors that are
830    created by that function are not freed here, however, because they have
831    already become constructors and must be preserved.  */
832
833 static void
834 free_temp_arrays (struct switch_conv_info *info)
835 {
836   XDELETEVEC (info->constructors);
837   XDELETEVEC (info->default_values);
838 }
839
840 /* Populate the array of default values in the order of phi nodes.
841    DEFAULT_CASE is the CASE_LABEL_EXPR for the default switch branch.  */
842
843 static void
844 gather_default_values (tree default_case, struct switch_conv_info *info)
845 {
846   gphi_iterator gsi;
847   basic_block bb = label_to_block (CASE_LABEL (default_case));
848   edge e;
849   int i = 0;
850
851   gcc_assert (CASE_LOW (default_case) == NULL_TREE);
852
853   if (bb == info->final_bb)
854     e = find_edge (info->switch_bb, bb);
855   else
856     e = single_succ_edge (bb);
857
858   for (gsi = gsi_start_phis (info->final_bb); !gsi_end_p (gsi); gsi_next (&gsi))
859     {
860       gphi *phi = gsi.phi ();
861       tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
862       gcc_assert (val);
863       info->default_values[i++] = val;
864     }
865 }
866
867 /* The following function populates the vectors in the constructors array with
868    future contents of the static arrays.  The vectors are populated in the
869    order of phi nodes.  SWTCH is the switch statement being converted.  */
870
871 static void
872 build_constructors (gswitch *swtch, struct switch_conv_info *info)
873 {
874   unsigned i, branch_num = gimple_switch_num_labels (swtch);
875   tree pos = info->range_min;
876
877   for (i = 1; i < branch_num; i++)
878     {
879       tree cs = gimple_switch_label (swtch, i);
880       basic_block bb = label_to_block (CASE_LABEL (cs));
881       edge e;
882       tree high;
883       gphi_iterator gsi;
884       int j;
885
886       if (bb == info->final_bb)
887         e = find_edge (info->switch_bb, bb);
888       else
889         e = single_succ_edge (bb);
890       gcc_assert (e);
891
892       while (tree_int_cst_lt (pos, CASE_LOW (cs)))
893         {
894           int k;
895           for (k = 0; k < info->phi_count; k++)
896             {
897               constructor_elt elt;
898
899               elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
900               elt.value
901                 = unshare_expr_without_location (info->default_values[k]);
902               info->constructors[k]->quick_push (elt);
903             }
904
905           pos = int_const_binop (PLUS_EXPR, pos,
906                                  build_int_cst (TREE_TYPE (pos), 1));
907         }
908       gcc_assert (tree_int_cst_equal (pos, CASE_LOW (cs)));
909
910       j = 0;
911       if (CASE_HIGH (cs))
912         high = CASE_HIGH (cs);
913       else
914         high = CASE_LOW (cs);
915       for (gsi = gsi_start_phis (info->final_bb);
916            !gsi_end_p (gsi); gsi_next (&gsi))
917         {
918           gphi *phi = gsi.phi ();
919           tree val = PHI_ARG_DEF_FROM_EDGE (phi, e);
920           tree low = CASE_LOW (cs);
921           pos = CASE_LOW (cs);
922
923           do
924             {
925               constructor_elt elt;
926
927               elt.index = int_const_binop (MINUS_EXPR, pos, info->range_min);
928               elt.value = unshare_expr_without_location (val);
929               info->constructors[j]->quick_push (elt);
930
931               pos = int_const_binop (PLUS_EXPR, pos,
932                                      build_int_cst (TREE_TYPE (pos), 1));
933             } while (!tree_int_cst_lt (high, pos)
934                      && tree_int_cst_lt (low, pos));
935           j++;
936         }
937     }
938 }
939
940 /* If all values in the constructor vector are the same, return the value.
941    Otherwise return NULL_TREE.  Not supposed to be called for empty
942    vectors.  */
943
944 static tree
945 constructor_contains_same_values_p (vec<constructor_elt, va_gc> *vec)
946 {
947   unsigned int i;
948   tree prev = NULL_TREE;
949   constructor_elt *elt;
950
951   FOR_EACH_VEC_SAFE_ELT (vec, i, elt)
952     {
953       if (!prev)
954         prev = elt->value;
955       else if (!operand_equal_p (elt->value, prev, OEP_ONLY_CONST))
956         return NULL_TREE;
957     }
958   return prev;
959 }
960
961 /* Return type which should be used for array elements, either TYPE,
962    or for integral type some smaller integral type that can still hold
963    all the constants.  */
964
965 static tree
966 array_value_type (gswitch *swtch, tree type, int num,
967                   struct switch_conv_info *info)
968 {
969   unsigned int i, len = vec_safe_length (info->constructors[num]);
970   constructor_elt *elt;
971   machine_mode mode;
972   int sign = 0;
973   tree smaller_type;
974
975   if (!INTEGRAL_TYPE_P (type))
976     return type;
977
978   mode = GET_CLASS_NARROWEST_MODE (GET_MODE_CLASS (TYPE_MODE (type)));
979   if (GET_MODE_SIZE (TYPE_MODE (type)) <= GET_MODE_SIZE (mode))
980     return type;
981
982   if (len < (optimize_bb_for_size_p (gimple_bb (swtch)) ? 2 : 32))
983     return type;
984
985   FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
986     {
987       wide_int cst;
988
989       if (TREE_CODE (elt->value) != INTEGER_CST)
990         return type;
991
992       cst = elt->value;
993       while (1)
994         {
995           unsigned int prec = GET_MODE_BITSIZE (mode);
996           if (prec > HOST_BITS_PER_WIDE_INT)
997             return type;
998
999           if (sign >= 0 && cst == wi::zext (cst, prec))
1000             {
1001               if (sign == 0 && cst == wi::sext (cst, prec))
1002                 break;
1003               sign = 1;
1004               break;
1005             }
1006           if (sign <= 0 && cst == wi::sext (cst, prec))
1007             {
1008               sign = -1;
1009               break;
1010             }
1011
1012           if (sign == 1)
1013             sign = 0;
1014
1015           mode = GET_MODE_WIDER_MODE (mode);
1016           if (mode == VOIDmode
1017               || GET_MODE_SIZE (mode) >= GET_MODE_SIZE (TYPE_MODE (type)))
1018             return type;
1019         }
1020     }
1021
1022   if (sign == 0)
1023     sign = TYPE_UNSIGNED (type) ? 1 : -1;
1024   smaller_type = lang_hooks.types.type_for_mode (mode, sign >= 0);
1025   if (GET_MODE_SIZE (TYPE_MODE (type))
1026       <= GET_MODE_SIZE (TYPE_MODE (smaller_type)))
1027     return type;
1028
1029   return smaller_type;
1030 }
1031
1032 /* Create an appropriate array type and declaration and assemble a static array
1033    variable.  Also create a load statement that initializes the variable in
1034    question with a value from the static array.  SWTCH is the switch statement
1035    being converted, NUM is the index to arrays of constructors, default values
1036    and target SSA names for this particular array.  ARR_INDEX_TYPE is the type
1037    of the index of the new array, PHI is the phi node of the final BB that
1038    corresponds to the value that will be loaded from the created array.  TIDX
1039    is an ssa name of a temporary variable holding the index for loads from the
1040    new array.  */
1041
1042 static void
1043 build_one_array (gswitch *swtch, int num, tree arr_index_type,
1044                  gphi *phi, tree tidx, struct switch_conv_info *info)
1045 {
1046   tree name, cst;
1047   gimple load;
1048   gimple_stmt_iterator gsi = gsi_for_stmt (swtch);
1049   location_t loc = gimple_location (swtch);
1050
1051   gcc_assert (info->default_values[num]);
1052
1053   name = copy_ssa_name (PHI_RESULT (phi));
1054   info->target_inbound_names[num] = name;
1055
1056   cst = constructor_contains_same_values_p (info->constructors[num]);
1057   if (cst)
1058     load = gimple_build_assign (name, cst);
1059   else
1060     {
1061       tree array_type, ctor, decl, value_type, fetch, default_type;
1062
1063       default_type = TREE_TYPE (info->default_values[num]);
1064       value_type = array_value_type (swtch, default_type, num, info);
1065       array_type = build_array_type (value_type, arr_index_type);
1066       if (default_type != value_type)
1067         {
1068           unsigned int i;
1069           constructor_elt *elt;
1070
1071           FOR_EACH_VEC_SAFE_ELT (info->constructors[num], i, elt)
1072             elt->value = fold_convert (value_type, elt->value);
1073         }
1074       ctor = build_constructor (array_type, info->constructors[num]);
1075       TREE_CONSTANT (ctor) = true;
1076       TREE_STATIC (ctor) = true;
1077
1078       decl = build_decl (loc, VAR_DECL, NULL_TREE, array_type);
1079       TREE_STATIC (decl) = 1;
1080       DECL_INITIAL (decl) = ctor;
1081
1082       DECL_NAME (decl) = create_tmp_var_name ("CSWTCH");
1083       DECL_ARTIFICIAL (decl) = 1;
1084       DECL_IGNORED_P (decl) = 1;
1085       TREE_CONSTANT (decl) = 1;
1086       TREE_READONLY (decl) = 1;
1087       DECL_IGNORED_P (decl) = 1;
1088       varpool_node::finalize_decl (decl);
1089
1090       fetch = build4 (ARRAY_REF, value_type, decl, tidx, NULL_TREE,
1091                       NULL_TREE);
1092       if (default_type != value_type)
1093         {
1094           fetch = fold_convert (default_type, fetch);
1095           fetch = force_gimple_operand_gsi (&gsi, fetch, true, NULL_TREE,
1096                                             true, GSI_SAME_STMT);
1097         }
1098       load = gimple_build_assign (name, fetch);
1099     }
1100
1101   gsi_insert_before (&gsi, load, GSI_SAME_STMT);
1102   update_stmt (load);
1103   info->arr_ref_last = load;
1104 }
1105
1106 /* Builds and initializes static arrays initialized with values gathered from
1107    the SWTCH switch statement.  Also creates statements that load values from
1108    them.  */
1109
1110 static void
1111 build_arrays (gswitch *swtch, struct switch_conv_info *info)
1112 {
1113   tree arr_index_type;
1114   tree tidx, sub, utype;
1115   gimple stmt;
1116   gimple_stmt_iterator gsi;
1117   gphi_iterator gpi;
1118   int i;
1119   location_t loc = gimple_location (swtch);
1120
1121   gsi = gsi_for_stmt (swtch);
1122
1123   /* Make sure we do not generate arithmetics in a subrange.  */
1124   utype = TREE_TYPE (info->index_expr);
1125   if (TREE_TYPE (utype))
1126     utype = lang_hooks.types.type_for_mode (TYPE_MODE (TREE_TYPE (utype)), 1);
1127   else
1128     utype = lang_hooks.types.type_for_mode (TYPE_MODE (utype), 1);
1129
1130   arr_index_type = build_index_type (info->range_size);
1131   tidx = make_ssa_name (utype);
1132   sub = fold_build2_loc (loc, MINUS_EXPR, utype,
1133                          fold_convert_loc (loc, utype, info->index_expr),
1134                          fold_convert_loc (loc, utype, info->range_min));
1135   sub = force_gimple_operand_gsi (&gsi, sub,
1136                                   false, NULL, true, GSI_SAME_STMT);
1137   stmt = gimple_build_assign (tidx, sub);
1138
1139   gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1140   update_stmt (stmt);
1141   info->arr_ref_first = stmt;
1142
1143   for (gpi = gsi_start_phis (info->final_bb), i = 0;
1144        !gsi_end_p (gpi); gsi_next (&gpi), i++)
1145     build_one_array (swtch, i, arr_index_type, gpi.phi (), tidx, info);
1146 }
1147
1148 /* Generates and appropriately inserts loads of default values at the position
1149    given by BSI.  Returns the last inserted statement.  */
1150
1151 static gassign *
1152 gen_def_assigns (gimple_stmt_iterator *gsi, struct switch_conv_info *info)
1153 {
1154   int i;
1155   gassign *assign = NULL;
1156
1157   for (i = 0; i < info->phi_count; i++)
1158     {
1159       tree name = copy_ssa_name (info->target_inbound_names[i]);
1160       info->target_outbound_names[i] = name;
1161       assign = gimple_build_assign (name, info->default_values[i]);
1162       gsi_insert_before (gsi, assign, GSI_SAME_STMT);
1163       update_stmt (assign);
1164     }
1165   return assign;
1166 }
1167
1168 /* Deletes the unused bbs and edges that now contain the switch statement and
1169    its empty branch bbs.  BBD is the now dead BB containing the original switch
1170    statement, FINAL is the last BB of the converted switch statement (in terms
1171    of succession).  */
1172
1173 static void
1174 prune_bbs (basic_block bbd, basic_block final)
1175 {
1176   edge_iterator ei;
1177   edge e;
1178
1179   for (ei = ei_start (bbd->succs); (e = ei_safe_edge (ei)); )
1180     {
1181       basic_block bb;
1182       bb = e->dest;
1183       remove_edge (e);
1184       if (bb != final)
1185         delete_basic_block (bb);
1186     }
1187   delete_basic_block (bbd);
1188 }
1189
1190 /* Add values to phi nodes in final_bb for the two new edges.  E1F is the edge
1191    from the basic block loading values from an array and E2F from the basic
1192    block loading default values.  BBF is the last switch basic block (see the
1193    bbf description in the comment below).  */
1194
1195 static void
1196 fix_phi_nodes (edge e1f, edge e2f, basic_block bbf,
1197                struct switch_conv_info *info)
1198 {
1199   gphi_iterator gsi;
1200   int i;
1201
1202   for (gsi = gsi_start_phis (bbf), i = 0;
1203        !gsi_end_p (gsi); gsi_next (&gsi), i++)
1204     {
1205       gphi *phi = gsi.phi ();
1206       add_phi_arg (phi, info->target_inbound_names[i], e1f, UNKNOWN_LOCATION);
1207       add_phi_arg (phi, info->target_outbound_names[i], e2f, UNKNOWN_LOCATION);
1208     }
1209 }
1210
1211 /* Creates a check whether the switch expression value actually falls into the
1212    range given by all the cases.  If it does not, the temporaries are loaded
1213    with default values instead.  SWTCH is the switch statement being converted.
1214
1215    bb0 is the bb with the switch statement, however, we'll end it with a
1216        condition instead.
1217
1218    bb1 is the bb to be used when the range check went ok.  It is derived from
1219        the switch BB
1220
1221    bb2 is the bb taken when the expression evaluated outside of the range
1222        covered by the created arrays.  It is populated by loads of default
1223        values.
1224
1225    bbF is a fall through for both bb1 and bb2 and contains exactly what
1226        originally followed the switch statement.
1227
1228    bbD contains the switch statement (in the end).  It is unreachable but we
1229        still need to strip off its edges.
1230 */
1231
1232 static void
1233 gen_inbound_check (gswitch *swtch, struct switch_conv_info *info)
1234 {
1235   tree label_decl1 = create_artificial_label (UNKNOWN_LOCATION);
1236   tree label_decl2 = create_artificial_label (UNKNOWN_LOCATION);
1237   tree label_decl3 = create_artificial_label (UNKNOWN_LOCATION);
1238   glabel *label1, *label2, *label3;
1239   tree utype, tidx;
1240   tree bound;
1241
1242   gcond *cond_stmt;
1243
1244   gassign *last_assign;
1245   gimple_stmt_iterator gsi;
1246   basic_block bb0, bb1, bb2, bbf, bbd;
1247   edge e01, e02, e21, e1d, e1f, e2f;
1248   location_t loc = gimple_location (swtch);
1249
1250   gcc_assert (info->default_values);
1251
1252   bb0 = gimple_bb (swtch);
1253
1254   tidx = gimple_assign_lhs (info->arr_ref_first);
1255   utype = TREE_TYPE (tidx);
1256
1257   /* (end of) block 0 */
1258   gsi = gsi_for_stmt (info->arr_ref_first);
1259   gsi_next (&gsi);
1260
1261   bound = fold_convert_loc (loc, utype, info->range_size);
1262   cond_stmt = gimple_build_cond (LE_EXPR, tidx, bound, NULL_TREE, NULL_TREE);
1263   gsi_insert_before (&gsi, cond_stmt, GSI_SAME_STMT);
1264   update_stmt (cond_stmt);
1265
1266   /* block 2 */
1267   label2 = gimple_build_label (label_decl2);
1268   gsi_insert_before (&gsi, label2, GSI_SAME_STMT);
1269   last_assign = gen_def_assigns (&gsi, info);
1270
1271   /* block 1 */
1272   label1 = gimple_build_label (label_decl1);
1273   gsi_insert_before (&gsi, label1, GSI_SAME_STMT);
1274
1275   /* block F */
1276   gsi = gsi_start_bb (info->final_bb);
1277   label3 = gimple_build_label (label_decl3);
1278   gsi_insert_before (&gsi, label3, GSI_SAME_STMT);
1279
1280   /* cfg fix */
1281   e02 = split_block (bb0, cond_stmt);
1282   bb2 = e02->dest;
1283
1284   e21 = split_block (bb2, last_assign);
1285   bb1 = e21->dest;
1286   remove_edge (e21);
1287
1288   e1d = split_block (bb1, info->arr_ref_last);
1289   bbd = e1d->dest;
1290   remove_edge (e1d);
1291
1292   /* flags and profiles of the edge for in-range values */
1293   e01 = make_edge (bb0, bb1, EDGE_TRUE_VALUE);
1294   e01->probability = REG_BR_PROB_BASE - info->default_prob;
1295   e01->count = info->other_count;
1296
1297   /* flags and profiles of the edge taking care of out-of-range values */
1298   e02->flags &= ~EDGE_FALLTHRU;
1299   e02->flags |= EDGE_FALSE_VALUE;
1300   e02->probability = info->default_prob;
1301   e02->count = info->default_count;
1302
1303   bbf = info->final_bb;
1304
1305   e1f = make_edge (bb1, bbf, EDGE_FALLTHRU);
1306   e1f->probability = REG_BR_PROB_BASE;
1307   e1f->count = info->other_count;
1308
1309   e2f = make_edge (bb2, bbf, EDGE_FALLTHRU);
1310   e2f->probability = REG_BR_PROB_BASE;
1311   e2f->count = info->default_count;
1312
1313   /* frequencies of the new BBs */
1314   bb1->frequency = EDGE_FREQUENCY (e01);
1315   bb2->frequency = EDGE_FREQUENCY (e02);
1316   bbf->frequency = EDGE_FREQUENCY (e1f) + EDGE_FREQUENCY (e2f);
1317
1318   /* Tidy blocks that have become unreachable.  */
1319   prune_bbs (bbd, info->final_bb);
1320
1321   /* Fixup the PHI nodes in bbF.  */
1322   fix_phi_nodes (e1f, e2f, bbf, info);
1323
1324   /* Fix the dominator tree, if it is available.  */
1325   if (dom_info_available_p (CDI_DOMINATORS))
1326     {
1327       vec<basic_block> bbs_to_fix_dom;
1328
1329       set_immediate_dominator (CDI_DOMINATORS, bb1, bb0);
1330       set_immediate_dominator (CDI_DOMINATORS, bb2, bb0);
1331       if (! get_immediate_dominator (CDI_DOMINATORS, bbf))
1332         /* If bbD was the immediate dominator ...  */
1333         set_immediate_dominator (CDI_DOMINATORS, bbf, bb0);
1334
1335       bbs_to_fix_dom.create (4);
1336       bbs_to_fix_dom.quick_push (bb0);
1337       bbs_to_fix_dom.quick_push (bb1);
1338       bbs_to_fix_dom.quick_push (bb2);
1339       bbs_to_fix_dom.quick_push (bbf);
1340
1341       iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
1342       bbs_to_fix_dom.release ();
1343     }
1344 }
1345
1346 /* The following function is invoked on every switch statement (the current one
1347    is given in SWTCH) and runs the individual phases of switch conversion on it
1348    one after another until one fails or the conversion is completed.
1349    Returns NULL on success, or a pointer to a string with the reason why the
1350    conversion failed.  */
1351
1352 static const char *
1353 process_switch (gswitch *swtch)
1354 {
1355   struct switch_conv_info info;
1356
1357   /* Group case labels so that we get the right results from the heuristics
1358      that decide on the code generation approach for this switch.  */
1359   group_case_labels_stmt (swtch);
1360
1361   /* If this switch is now a degenerate case with only a default label,
1362      there is nothing left for us to do.   */
1363   if (gimple_switch_num_labels (swtch) < 2)
1364     return "switch is a degenerate case";
1365
1366   collect_switch_conv_info (swtch, &info);
1367
1368   /* No error markers should reach here (they should be filtered out
1369      during gimplification).  */
1370   gcc_checking_assert (TREE_TYPE (info.index_expr) != error_mark_node);
1371
1372   /* A switch on a constant should have been optimized in tree-cfg-cleanup.  */
1373   gcc_checking_assert (! TREE_CONSTANT (info.index_expr));
1374
1375   if (info.uniq <= MAX_CASE_BIT_TESTS)
1376     {
1377       if (expand_switch_using_bit_tests_p (info.range_size,
1378                                            info.uniq, info.count,
1379                                            optimize_bb_for_speed_p
1380                                              (gimple_bb (swtch))))
1381         {
1382           if (dump_file)
1383             fputs ("  expanding as bit test is preferable\n", dump_file);
1384           emit_case_bit_tests (swtch, info.index_expr, info.range_min,
1385                                info.range_size, info.range_max);
1386           loops_state_set (LOOPS_NEED_FIXUP);
1387           return NULL;
1388         }
1389
1390       if (info.uniq <= 2)
1391         /* This will be expanded as a decision tree in stmt.c:expand_case.  */
1392         return "  expanding as jumps is preferable";
1393     }
1394
1395   /* If there is no common successor, we cannot do the transformation.  */
1396   if (! info.final_bb)
1397     return "no common successor to all case label target blocks found";
1398
1399   /* Check the case label values are within reasonable range:  */
1400   if (!check_range (&info))
1401     {
1402       gcc_assert (info.reason);
1403       return info.reason;
1404     }
1405
1406   /* For all the cases, see whether they are empty, the assignments they
1407      represent constant and so on...  */
1408   if (! check_all_empty_except_final (&info))
1409     {
1410       gcc_assert (info.reason);
1411       return info.reason;
1412     }
1413   if (!check_final_bb (&info))
1414     {
1415       gcc_assert (info.reason);
1416       return info.reason;
1417     }
1418
1419   /* At this point all checks have passed and we can proceed with the
1420      transformation.  */
1421
1422   create_temp_arrays (&info);
1423   gather_default_values (gimple_switch_default_label (swtch), &info);
1424   build_constructors (swtch, &info);
1425
1426   build_arrays (swtch, &info); /* Build the static arrays and assignments.   */
1427   gen_inbound_check (swtch, &info);     /* Build the bounds check.  */
1428
1429   /* Cleanup:  */
1430   free_temp_arrays (&info);
1431   return NULL;
1432 }
1433
1434 /* The main function of the pass scans statements for switches and invokes
1435    process_switch on them.  */
1436
1437 namespace {
1438
1439 const pass_data pass_data_convert_switch =
1440 {
1441   GIMPLE_PASS, /* type */
1442   "switchconv", /* name */
1443   OPTGROUP_NONE, /* optinfo_flags */
1444   TV_TREE_SWITCH_CONVERSION, /* tv_id */
1445   ( PROP_cfg | PROP_ssa ), /* properties_required */
1446   0, /* properties_provided */
1447   0, /* properties_destroyed */
1448   0, /* todo_flags_start */
1449   TODO_update_ssa, /* todo_flags_finish */
1450 };
1451
1452 class pass_convert_switch : public gimple_opt_pass
1453 {
1454 public:
1455   pass_convert_switch (gcc::context *ctxt)
1456     : gimple_opt_pass (pass_data_convert_switch, ctxt)
1457   {}
1458
1459   /* opt_pass methods: */
1460   virtual bool gate (function *) { return flag_tree_switch_conversion != 0; }
1461   virtual unsigned int execute (function *);
1462
1463 }; // class pass_convert_switch
1464
1465 unsigned int
1466 pass_convert_switch::execute (function *fun)
1467 {
1468   basic_block bb;
1469
1470   FOR_EACH_BB_FN (bb, fun)
1471   {
1472     const char *failure_reason;
1473     gimple stmt = last_stmt (bb);
1474     if (stmt && gimple_code (stmt) == GIMPLE_SWITCH)
1475       {
1476         if (dump_file)
1477           {
1478             expanded_location loc = expand_location (gimple_location (stmt));
1479
1480             fprintf (dump_file, "beginning to process the following "
1481                      "SWITCH statement (%s:%d) : ------- \n",
1482                      loc.file, loc.line);
1483             print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1484             putc ('\n', dump_file);
1485           }
1486
1487         failure_reason = process_switch (as_a <gswitch *> (stmt));
1488         if (! failure_reason)
1489           {
1490             if (dump_file)
1491               {
1492                 fputs ("Switch converted\n", dump_file);
1493                 fputs ("--------------------------------\n", dump_file);
1494               }
1495
1496             /* Make no effort to update the post-dominator tree.  It is actually not
1497                that hard for the transformations we have performed, but it is not
1498                supported by iterate_fix_dominators.  */
1499             free_dominance_info (CDI_POST_DOMINATORS);
1500           }
1501         else
1502           {
1503             if (dump_file)
1504               {
1505                 fputs ("Bailing out - ", dump_file);
1506                 fputs (failure_reason, dump_file);
1507                 fputs ("\n--------------------------------\n", dump_file);
1508               }
1509           }
1510       }
1511   }
1512
1513   return 0;
1514 }
1515
1516 } // anon namespace
1517
1518 gimple_opt_pass *
1519 make_pass_convert_switch (gcc::context *ctxt)
1520 {
1521   return new pass_convert_switch (ctxt);
1522 }