2014-04-14 Martin Jambor <mjambor@suse.cz>
[official-gcc.git] / gcc / stmt.c
blob5d68edb73f8f7353b290b6c72fea997c38c60ee5
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file handles the generation of rtl code from tree structure
21 above the level of expressions, using subroutines in exp*.c and emit-rtl.c.
22 The functions whose names start with `expand_' are called by the
23 expander to generate RTL instructions for various kinds of constructs. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tm.h"
30 #include "rtl.h"
31 #include "hard-reg-set.h"
32 #include "tree.h"
33 #include "varasm.h"
34 #include "stor-layout.h"
35 #include "tm_p.h"
36 #include "flags.h"
37 #include "except.h"
38 #include "function.h"
39 #include "insn-config.h"
40 #include "expr.h"
41 #include "libfuncs.h"
42 #include "recog.h"
43 #include "machmode.h"
44 #include "diagnostic-core.h"
45 #include "output.h"
46 #include "langhooks.h"
47 #include "predict.h"
48 #include "optabs.h"
49 #include "target.h"
50 #include "pointer-set.h"
51 #include "basic-block.h"
52 #include "tree-ssa-alias.h"
53 #include "internal-fn.h"
54 #include "gimple-expr.h"
55 #include "is-a.h"
56 #include "gimple.h"
57 #include "regs.h"
58 #include "alloc-pool.h"
59 #include "pretty-print.h"
60 #include "params.h"
61 #include "dumpfile.h"
64 /* Functions and data structures for expanding case statements. */
66 /* Case label structure, used to hold info on labels within case
67 statements. We handle "range" labels; for a single-value label
68 as in C, the high and low limits are the same.
70 We start with a vector of case nodes sorted in ascending order, and
71 the default label as the last element in the vector. Before expanding
72 to RTL, we transform this vector into a list linked via the RIGHT
73 fields in the case_node struct. Nodes with higher case values are
74 later in the list.
76 Switch statements can be output in three forms. A branch table is
77 used if there are more than a few labels and the labels are dense
78 within the range between the smallest and largest case value. If a
79 branch table is used, no further manipulations are done with the case
80 node chain.
82 The alternative to the use of a branch table is to generate a series
83 of compare and jump insns. When that is done, we use the LEFT, RIGHT,
84 and PARENT fields to hold a binary tree. Initially the tree is
85 totally unbalanced, with everything on the right. We balance the tree
86 with nodes on the left having lower case values than the parent
87 and nodes on the right having higher values. We then output the tree
88 in order.
90 For very small, suitable switch statements, we can generate a series
91 of simple bit test and branches instead. */
93 struct case_node
95 struct case_node *left; /* Left son in binary tree */
96 struct case_node *right; /* Right son in binary tree; also node chain */
97 struct case_node *parent; /* Parent of node in binary tree */
98 tree low; /* Lowest index value for this label */
99 tree high; /* Highest index value for this label */
100 tree code_label; /* Label to jump to when node matches */
101 int prob; /* Probability of taking this case. */
102 /* Probability of reaching subtree rooted at this node */
103 int subtree_prob;
106 typedef struct case_node case_node;
107 typedef struct case_node *case_node_ptr;
109 extern basic_block label_to_block_fn (struct function *, tree);
111 static bool check_unique_operand_names (tree, tree, tree);
112 static char *resolve_operand_name_1 (char *, tree, tree, tree);
113 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
114 static int node_has_low_bound (case_node_ptr, tree);
115 static int node_has_high_bound (case_node_ptr, tree);
116 static int node_is_bounded (case_node_ptr, tree);
117 static void emit_case_nodes (rtx, case_node_ptr, rtx, int, tree);
119 /* Return the rtx-label that corresponds to a LABEL_DECL,
120 creating it if necessary. */
123 label_rtx (tree label)
125 gcc_assert (TREE_CODE (label) == LABEL_DECL);
127 if (!DECL_RTL_SET_P (label))
129 rtx r = gen_label_rtx ();
130 SET_DECL_RTL (label, r);
131 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
132 LABEL_PRESERVE_P (r) = 1;
135 return DECL_RTL (label);
138 /* As above, but also put it on the forced-reference list of the
139 function that contains it. */
141 force_label_rtx (tree label)
143 rtx ref = label_rtx (label);
144 tree function = decl_function_context (label);
146 gcc_assert (function);
148 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, ref, forced_labels);
149 return ref;
152 /* Add an unconditional jump to LABEL as the next sequential instruction. */
154 void
155 emit_jump (rtx label)
157 do_pending_stack_adjust ();
158 emit_jump_insn (gen_jump (label));
159 emit_barrier ();
162 /* Handle goto statements and the labels that they can go to. */
164 /* Specify the location in the RTL code of a label LABEL,
165 which is a LABEL_DECL tree node.
167 This is used for the kind of label that the user can jump to with a
168 goto statement, and for alternatives of a switch or case statement.
169 RTL labels generated for loops and conditionals don't go through here;
170 they are generated directly at the RTL level, by other functions below.
172 Note that this has nothing to do with defining label *names*.
173 Languages vary in how they do that and what that even means. */
175 void
176 expand_label (tree label)
178 rtx label_r = label_rtx (label);
180 do_pending_stack_adjust ();
181 emit_label (label_r);
182 if (DECL_NAME (label))
183 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
185 if (DECL_NONLOCAL (label))
187 expand_builtin_setjmp_receiver (NULL);
188 nonlocal_goto_handler_labels
189 = gen_rtx_EXPR_LIST (VOIDmode, label_r,
190 nonlocal_goto_handler_labels);
193 if (FORCED_LABEL (label))
194 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, label_r, forced_labels);
196 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
197 maybe_set_first_label_num (label_r);
200 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
201 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
202 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
203 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
204 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
205 constraint allows the use of a register operand. And, *IS_INOUT
206 will be true if the operand is read-write, i.e., if it is used as
207 an input as well as an output. If *CONSTRAINT_P is not in
208 canonical form, it will be made canonical. (Note that `+' will be
209 replaced with `=' as part of this process.)
211 Returns TRUE if all went well; FALSE if an error occurred. */
213 bool
214 parse_output_constraint (const char **constraint_p, int operand_num,
215 int ninputs, int noutputs, bool *allows_mem,
216 bool *allows_reg, bool *is_inout)
218 const char *constraint = *constraint_p;
219 const char *p;
221 /* Assume the constraint doesn't allow the use of either a register
222 or memory. */
223 *allows_mem = false;
224 *allows_reg = false;
226 /* Allow the `=' or `+' to not be at the beginning of the string,
227 since it wasn't explicitly documented that way, and there is a
228 large body of code that puts it last. Swap the character to
229 the front, so as not to uglify any place else. */
230 p = strchr (constraint, '=');
231 if (!p)
232 p = strchr (constraint, '+');
234 /* If the string doesn't contain an `=', issue an error
235 message. */
236 if (!p)
238 error ("output operand constraint lacks %<=%>");
239 return false;
242 /* If the constraint begins with `+', then the operand is both read
243 from and written to. */
244 *is_inout = (*p == '+');
246 /* Canonicalize the output constraint so that it begins with `='. */
247 if (p != constraint || *is_inout)
249 char *buf;
250 size_t c_len = strlen (constraint);
252 if (p != constraint)
253 warning (0, "output constraint %qc for operand %d "
254 "is not at the beginning",
255 *p, operand_num);
257 /* Make a copy of the constraint. */
258 buf = XALLOCAVEC (char, c_len + 1);
259 strcpy (buf, constraint);
260 /* Swap the first character and the `=' or `+'. */
261 buf[p - constraint] = buf[0];
262 /* Make sure the first character is an `='. (Until we do this,
263 it might be a `+'.) */
264 buf[0] = '=';
265 /* Replace the constraint with the canonicalized string. */
266 *constraint_p = ggc_alloc_string (buf, c_len);
267 constraint = *constraint_p;
270 /* Loop through the constraint string. */
271 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
272 switch (*p)
274 case '+':
275 case '=':
276 error ("operand constraint contains incorrectly positioned "
277 "%<+%> or %<=%>");
278 return false;
280 case '%':
281 if (operand_num + 1 == ninputs + noutputs)
283 error ("%<%%%> constraint used with last operand");
284 return false;
286 break;
288 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
289 *allows_mem = true;
290 break;
292 case '?': case '!': case '*': case '&': case '#':
293 case 'E': case 'F': case 'G': case 'H':
294 case 's': case 'i': case 'n':
295 case 'I': case 'J': case 'K': case 'L': case 'M':
296 case 'N': case 'O': case 'P': case ',':
297 break;
299 case '0': case '1': case '2': case '3': case '4':
300 case '5': case '6': case '7': case '8': case '9':
301 case '[':
302 error ("matching constraint not valid in output operand");
303 return false;
305 case '<': case '>':
306 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
307 excepting those that expand_call created. So match memory
308 and hope. */
309 *allows_mem = true;
310 break;
312 case 'g': case 'X':
313 *allows_reg = true;
314 *allows_mem = true;
315 break;
317 case 'p': case 'r':
318 *allows_reg = true;
319 break;
321 default:
322 if (!ISALPHA (*p))
323 break;
324 if (REG_CLASS_FROM_CONSTRAINT (*p, p) != NO_REGS)
325 *allows_reg = true;
326 #ifdef EXTRA_CONSTRAINT_STR
327 else if (EXTRA_ADDRESS_CONSTRAINT (*p, p))
328 *allows_reg = true;
329 else if (EXTRA_MEMORY_CONSTRAINT (*p, p))
330 *allows_mem = true;
331 else
333 /* Otherwise we can't assume anything about the nature of
334 the constraint except that it isn't purely registers.
335 Treat it like "g" and hope for the best. */
336 *allows_reg = true;
337 *allows_mem = true;
339 #endif
340 break;
343 return true;
346 /* Similar, but for input constraints. */
348 bool
349 parse_input_constraint (const char **constraint_p, int input_num,
350 int ninputs, int noutputs, int ninout,
351 const char * const * constraints,
352 bool *allows_mem, bool *allows_reg)
354 const char *constraint = *constraint_p;
355 const char *orig_constraint = constraint;
356 size_t c_len = strlen (constraint);
357 size_t j;
358 bool saw_match = false;
360 /* Assume the constraint doesn't allow the use of either
361 a register or memory. */
362 *allows_mem = false;
363 *allows_reg = false;
365 /* Make sure constraint has neither `=', `+', nor '&'. */
367 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
368 switch (constraint[j])
370 case '+': case '=': case '&':
371 if (constraint == orig_constraint)
373 error ("input operand constraint contains %qc", constraint[j]);
374 return false;
376 break;
378 case '%':
379 if (constraint == orig_constraint
380 && input_num + 1 == ninputs - ninout)
382 error ("%<%%%> constraint used with last operand");
383 return false;
385 break;
387 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
388 *allows_mem = true;
389 break;
391 case '<': case '>':
392 case '?': case '!': case '*': case '#':
393 case 'E': case 'F': case 'G': case 'H':
394 case 's': case 'i': case 'n':
395 case 'I': case 'J': case 'K': case 'L': case 'M':
396 case 'N': case 'O': case 'P': case ',':
397 break;
399 /* Whether or not a numeric constraint allows a register is
400 decided by the matching constraint, and so there is no need
401 to do anything special with them. We must handle them in
402 the default case, so that we don't unnecessarily force
403 operands to memory. */
404 case '0': case '1': case '2': case '3': case '4':
405 case '5': case '6': case '7': case '8': case '9':
407 char *end;
408 unsigned long match;
410 saw_match = true;
412 match = strtoul (constraint + j, &end, 10);
413 if (match >= (unsigned long) noutputs)
415 error ("matching constraint references invalid operand number");
416 return false;
419 /* Try and find the real constraint for this dup. Only do this
420 if the matching constraint is the only alternative. */
421 if (*end == '\0'
422 && (j == 0 || (j == 1 && constraint[0] == '%')))
424 constraint = constraints[match];
425 *constraint_p = constraint;
426 c_len = strlen (constraint);
427 j = 0;
428 /* ??? At the end of the loop, we will skip the first part of
429 the matched constraint. This assumes not only that the
430 other constraint is an output constraint, but also that
431 the '=' or '+' come first. */
432 break;
434 else
435 j = end - constraint;
436 /* Anticipate increment at end of loop. */
437 j--;
439 /* Fall through. */
441 case 'p': case 'r':
442 *allows_reg = true;
443 break;
445 case 'g': case 'X':
446 *allows_reg = true;
447 *allows_mem = true;
448 break;
450 default:
451 if (! ISALPHA (constraint[j]))
453 error ("invalid punctuation %qc in constraint", constraint[j]);
454 return false;
456 if (REG_CLASS_FROM_CONSTRAINT (constraint[j], constraint + j)
457 != NO_REGS)
458 *allows_reg = true;
459 #ifdef EXTRA_CONSTRAINT_STR
460 else if (EXTRA_ADDRESS_CONSTRAINT (constraint[j], constraint + j))
461 *allows_reg = true;
462 else if (EXTRA_MEMORY_CONSTRAINT (constraint[j], constraint + j))
463 *allows_mem = true;
464 else
466 /* Otherwise we can't assume anything about the nature of
467 the constraint except that it isn't purely registers.
468 Treat it like "g" and hope for the best. */
469 *allows_reg = true;
470 *allows_mem = true;
472 #endif
473 break;
476 if (saw_match && !*allows_reg)
477 warning (0, "matching constraint does not allow a register");
479 return true;
482 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
483 can be an asm-declared register. Called via walk_tree. */
485 static tree
486 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
487 void *data)
489 tree decl = *declp;
490 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
492 if (TREE_CODE (decl) == VAR_DECL)
494 if (DECL_HARD_REGISTER (decl)
495 && REG_P (DECL_RTL (decl))
496 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
498 rtx reg = DECL_RTL (decl);
500 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
501 return decl;
503 walk_subtrees = 0;
505 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
506 walk_subtrees = 0;
507 return NULL_TREE;
510 /* If there is an overlap between *REGS and DECL, return the first overlap
511 found. */
512 tree
513 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
515 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
519 /* A subroutine of expand_asm_operands. Check that all operand names
520 are unique. Return true if so. We rely on the fact that these names
521 are identifiers, and so have been canonicalized by get_identifier,
522 so all we need are pointer comparisons. */
524 static bool
525 check_unique_operand_names (tree outputs, tree inputs, tree labels)
527 tree i, j, i_name = NULL_TREE;
529 for (i = outputs; i ; i = TREE_CHAIN (i))
531 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
532 if (! i_name)
533 continue;
535 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
536 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
537 goto failure;
540 for (i = inputs; i ; i = TREE_CHAIN (i))
542 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
543 if (! i_name)
544 continue;
546 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
547 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
548 goto failure;
549 for (j = outputs; j ; j = TREE_CHAIN (j))
550 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
551 goto failure;
554 for (i = labels; i ; i = TREE_CHAIN (i))
556 i_name = TREE_PURPOSE (i);
557 if (! i_name)
558 continue;
560 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
561 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
562 goto failure;
563 for (j = inputs; j ; j = TREE_CHAIN (j))
564 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
565 goto failure;
568 return true;
570 failure:
571 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
572 return false;
575 /* A subroutine of expand_asm_operands. Resolve the names of the operands
576 in *POUTPUTS and *PINPUTS to numbers, and replace the name expansions in
577 STRING and in the constraints to those numbers. */
579 tree
580 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
582 char *buffer;
583 char *p;
584 const char *c;
585 tree t;
587 check_unique_operand_names (outputs, inputs, labels);
589 /* Substitute [<name>] in input constraint strings. There should be no
590 named operands in output constraints. */
591 for (t = inputs; t ; t = TREE_CHAIN (t))
593 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
594 if (strchr (c, '[') != NULL)
596 p = buffer = xstrdup (c);
597 while ((p = strchr (p, '[')) != NULL)
598 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
599 TREE_VALUE (TREE_PURPOSE (t))
600 = build_string (strlen (buffer), buffer);
601 free (buffer);
605 /* Now check for any needed substitutions in the template. */
606 c = TREE_STRING_POINTER (string);
607 while ((c = strchr (c, '%')) != NULL)
609 if (c[1] == '[')
610 break;
611 else if (ISALPHA (c[1]) && c[2] == '[')
612 break;
613 else
615 c += 1 + (c[1] == '%');
616 continue;
620 if (c)
622 /* OK, we need to make a copy so we can perform the substitutions.
623 Assume that we will not need extra space--we get to remove '['
624 and ']', which means we cannot have a problem until we have more
625 than 999 operands. */
626 buffer = xstrdup (TREE_STRING_POINTER (string));
627 p = buffer + (c - TREE_STRING_POINTER (string));
629 while ((p = strchr (p, '%')) != NULL)
631 if (p[1] == '[')
632 p += 1;
633 else if (ISALPHA (p[1]) && p[2] == '[')
634 p += 2;
635 else
637 p += 1 + (p[1] == '%');
638 continue;
641 p = resolve_operand_name_1 (p, outputs, inputs, labels);
644 string = build_string (strlen (buffer), buffer);
645 free (buffer);
648 return string;
651 /* A subroutine of resolve_operand_names. P points to the '[' for a
652 potential named operand of the form [<name>]. In place, replace
653 the name and brackets with a number. Return a pointer to the
654 balance of the string after substitution. */
656 static char *
657 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
659 char *q;
660 int op;
661 tree t;
663 /* Collect the operand name. */
664 q = strchr (++p, ']');
665 if (!q)
667 error ("missing close brace for named operand");
668 return strchr (p, '\0');
670 *q = '\0';
672 /* Resolve the name to a number. */
673 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
675 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
676 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
677 goto found;
679 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
681 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
682 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
683 goto found;
685 for (t = labels; t ; t = TREE_CHAIN (t), op++)
687 tree name = TREE_PURPOSE (t);
688 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
689 goto found;
692 error ("undefined named operand %qs", identifier_to_locale (p));
693 op = 0;
695 found:
696 /* Replace the name with the number. Unfortunately, not all libraries
697 get the return value of sprintf correct, so search for the end of the
698 generated string by hand. */
699 sprintf (--p, "%d", op);
700 p = strchr (p, '\0');
702 /* Verify the no extra buffer space assumption. */
703 gcc_assert (p <= q);
705 /* Shift the rest of the buffer down to fill the gap. */
706 memmove (p, q + 1, strlen (q + 1) + 1);
708 return p;
712 /* Generate RTL to return directly from the current function.
713 (That is, we bypass any return value.) */
715 void
716 expand_naked_return (void)
718 rtx end_label;
720 clear_pending_stack_adjust ();
721 do_pending_stack_adjust ();
723 end_label = naked_return_label;
724 if (end_label == 0)
725 end_label = naked_return_label = gen_label_rtx ();
727 emit_jump (end_label);
730 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
731 is the probability of jumping to LABEL. */
732 static void
733 do_jump_if_equal (enum machine_mode mode, rtx op0, rtx op1, rtx label,
734 int unsignedp, int prob)
736 gcc_assert (prob <= REG_BR_PROB_BASE);
737 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
738 NULL_RTX, NULL_RTX, label, prob);
741 /* Do the insertion of a case label into case_list. The labels are
742 fed to us in descending order from the sorted vector of case labels used
743 in the tree part of the middle end. So the list we construct is
744 sorted in ascending order.
746 LABEL is the case label to be inserted. LOW and HIGH are the bounds
747 against which the index is compared to jump to LABEL and PROB is the
748 estimated probability LABEL is reached from the switch statement. */
750 static struct case_node *
751 add_case_node (struct case_node *head, tree low, tree high,
752 tree label, int prob, alloc_pool case_node_pool)
754 struct case_node *r;
756 gcc_checking_assert (low);
757 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
759 /* Add this label to the chain. */
760 r = (struct case_node *) pool_alloc (case_node_pool);
761 r->low = low;
762 r->high = high;
763 r->code_label = label;
764 r->parent = r->left = NULL;
765 r->prob = prob;
766 r->subtree_prob = prob;
767 r->right = head;
768 return r;
771 /* Dump ROOT, a list or tree of case nodes, to file. */
773 static void
774 dump_case_nodes (FILE *f, struct case_node *root,
775 int indent_step, int indent_level)
777 HOST_WIDE_INT low, high;
779 if (root == 0)
780 return;
781 indent_level++;
783 dump_case_nodes (f, root->left, indent_step, indent_level);
785 low = tree_to_shwi (root->low);
786 high = tree_to_shwi (root->high);
788 fputs (";; ", f);
789 if (high == low)
790 fprintf (f, "%*s" HOST_WIDE_INT_PRINT_DEC,
791 indent_step * indent_level, "", low);
792 else
793 fprintf (f, "%*s" HOST_WIDE_INT_PRINT_DEC " ... " HOST_WIDE_INT_PRINT_DEC,
794 indent_step * indent_level, "", low, high);
795 fputs ("\n", f);
797 dump_case_nodes (f, root->right, indent_step, indent_level);
800 #ifndef HAVE_casesi
801 #define HAVE_casesi 0
802 #endif
804 #ifndef HAVE_tablejump
805 #define HAVE_tablejump 0
806 #endif
808 /* Return the smallest number of different values for which it is best to use a
809 jump-table instead of a tree of conditional branches. */
811 static unsigned int
812 case_values_threshold (void)
814 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
816 if (threshold == 0)
817 threshold = targetm.case_values_threshold ();
819 return threshold;
822 /* Return true if a switch should be expanded as a decision tree.
823 RANGE is the difference between highest and lowest case.
824 UNIQ is number of unique case node targets, not counting the default case.
825 COUNT is the number of comparisons needed, not counting the default case. */
827 static bool
828 expand_switch_as_decision_tree_p (tree range,
829 unsigned int uniq ATTRIBUTE_UNUSED,
830 unsigned int count)
832 int max_ratio;
834 /* If neither casesi or tablejump is available, or flag_jump_tables
835 over-ruled us, we really have no choice. */
836 if (!HAVE_casesi && !HAVE_tablejump)
837 return true;
838 if (!flag_jump_tables)
839 return true;
840 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
841 if (flag_pic)
842 return true;
843 #endif
845 /* If the switch is relatively small such that the cost of one
846 indirect jump on the target are higher than the cost of a
847 decision tree, go with the decision tree.
849 If range of values is much bigger than number of values,
850 or if it is too large to represent in a HOST_WIDE_INT,
851 make a sequence of conditional branches instead of a dispatch.
853 The definition of "much bigger" depends on whether we are
854 optimizing for size or for speed. If the former, the maximum
855 ratio range/count = 3, because this was found to be the optimal
856 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
857 10 is much older, and was probably selected after an extensive
858 benchmarking investigation on numerous platforms. Or maybe it
859 just made sense to someone at some point in the history of GCC,
860 who knows... */
861 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
862 if (count < case_values_threshold ()
863 || ! tree_fits_uhwi_p (range)
864 || compare_tree_int (range, max_ratio * count) > 0)
865 return true;
867 return false;
870 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
871 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
872 DEFAULT_PROB is the estimated probability that it jumps to
873 DEFAULT_LABEL.
875 We generate a binary decision tree to select the appropriate target
876 code. This is done as follows:
878 If the index is a short or char that we do not have
879 an insn to handle comparisons directly, convert it to
880 a full integer now, rather than letting each comparison
881 generate the conversion.
883 Load the index into a register.
885 The list of cases is rearranged into a binary tree,
886 nearly optimal assuming equal probability for each case.
888 The tree is transformed into RTL, eliminating redundant
889 test conditions at the same time.
891 If program flow could reach the end of the decision tree
892 an unconditional jump to the default code is emitted.
894 The above process is unaware of the CFG. The caller has to fix up
895 the CFG itself. This is done in cfgexpand.c. */
897 static void
898 emit_case_decision_tree (tree index_expr, tree index_type,
899 struct case_node *case_list, rtx default_label,
900 int default_prob)
902 rtx index = expand_normal (index_expr);
904 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
905 && ! have_insn_for (COMPARE, GET_MODE (index)))
907 int unsignedp = TYPE_UNSIGNED (index_type);
908 enum machine_mode wider_mode;
909 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
910 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
911 if (have_insn_for (COMPARE, wider_mode))
913 index = convert_to_mode (wider_mode, index, unsignedp);
914 break;
918 do_pending_stack_adjust ();
920 if (MEM_P (index))
922 index = copy_to_reg (index);
923 if (TREE_CODE (index_expr) == SSA_NAME)
924 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
927 balance_case_nodes (&case_list, NULL);
929 if (dump_file && (dump_flags & TDF_DETAILS))
931 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
932 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
933 dump_case_nodes (dump_file, case_list, indent_step, 0);
936 emit_case_nodes (index, case_list, default_label, default_prob, index_type);
937 if (default_label)
938 emit_jump (default_label);
941 /* Return the sum of probabilities of outgoing edges of basic block BB. */
943 static int
944 get_outgoing_edge_probs (basic_block bb)
946 edge e;
947 edge_iterator ei;
948 int prob_sum = 0;
949 if (!bb)
950 return 0;
951 FOR_EACH_EDGE (e, ei, bb->succs)
952 prob_sum += e->probability;
953 return prob_sum;
956 /* Computes the conditional probability of jumping to a target if the branch
957 instruction is executed.
958 TARGET_PROB is the estimated probability of jumping to a target relative
959 to some basic block BB.
960 BASE_PROB is the probability of reaching the branch instruction relative
961 to the same basic block BB. */
963 static inline int
964 conditional_probability (int target_prob, int base_prob)
966 if (base_prob > 0)
968 gcc_assert (target_prob >= 0);
969 gcc_assert (target_prob <= base_prob);
970 return GCOV_COMPUTE_SCALE (target_prob, base_prob);
972 return -1;
975 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
976 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
977 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
978 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
980 First, a jump insn is emitted. First we try "casesi". If that
981 fails, try "tablejump". A target *must* have one of them (or both).
983 Then, a table with the target labels is emitted.
985 The process is unaware of the CFG. The caller has to fix up
986 the CFG itself. This is done in cfgexpand.c. */
988 static void
989 emit_case_dispatch_table (tree index_expr, tree index_type,
990 struct case_node *case_list, rtx default_label,
991 tree minval, tree maxval, tree range,
992 basic_block stmt_bb)
994 int i, ncases;
995 struct case_node *n;
996 rtx *labelvec;
997 rtx fallback_label = label_rtx (case_list->code_label);
998 rtx table_label = gen_label_rtx ();
999 bool has_gaps = false;
1000 edge default_edge = stmt_bb ? EDGE_SUCC (stmt_bb, 0) : NULL;
1001 int default_prob = default_edge ? default_edge->probability : 0;
1002 int base = get_outgoing_edge_probs (stmt_bb);
1003 bool try_with_tablejump = false;
1005 int new_default_prob = conditional_probability (default_prob,
1006 base);
1008 if (! try_casesi (index_type, index_expr, minval, range,
1009 table_label, default_label, fallback_label,
1010 new_default_prob))
1012 /* Index jumptables from zero for suitable values of minval to avoid
1013 a subtraction. For the rationale see:
1014 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
1015 if (optimize_insn_for_speed_p ()
1016 && compare_tree_int (minval, 0) > 0
1017 && compare_tree_int (minval, 3) < 0)
1019 minval = build_int_cst (index_type, 0);
1020 range = maxval;
1021 has_gaps = true;
1023 try_with_tablejump = true;
1026 /* Get table of labels to jump to, in order of case index. */
1028 ncases = tree_to_shwi (range) + 1;
1029 labelvec = XALLOCAVEC (rtx, ncases);
1030 memset (labelvec, 0, ncases * sizeof (rtx));
1032 for (n = case_list; n; n = n->right)
1034 /* Compute the low and high bounds relative to the minimum
1035 value since that should fit in a HOST_WIDE_INT while the
1036 actual values may not. */
1037 HOST_WIDE_INT i_low
1038 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1039 n->low, minval));
1040 HOST_WIDE_INT i_high
1041 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1042 n->high, minval));
1043 HOST_WIDE_INT i;
1045 for (i = i_low; i <= i_high; i ++)
1046 labelvec[i]
1047 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1050 /* Fill in the gaps with the default. We may have gaps at
1051 the beginning if we tried to avoid the minval subtraction,
1052 so substitute some label even if the default label was
1053 deemed unreachable. */
1054 if (!default_label)
1055 default_label = fallback_label;
1056 for (i = 0; i < ncases; i++)
1057 if (labelvec[i] == 0)
1059 has_gaps = true;
1060 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1063 if (has_gaps)
1065 /* There is at least one entry in the jump table that jumps
1066 to default label. The default label can either be reached
1067 through the indirect jump or the direct conditional jump
1068 before that. Split the probability of reaching the
1069 default label among these two jumps. */
1070 new_default_prob = conditional_probability (default_prob/2,
1071 base);
1072 default_prob /= 2;
1073 base -= default_prob;
1075 else
1077 base -= default_prob;
1078 default_prob = 0;
1081 if (default_edge)
1082 default_edge->probability = default_prob;
1084 /* We have altered the probability of the default edge. So the probabilities
1085 of all other edges need to be adjusted so that it sums up to
1086 REG_BR_PROB_BASE. */
1087 if (base)
1089 edge e;
1090 edge_iterator ei;
1091 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
1092 e->probability = GCOV_COMPUTE_SCALE (e->probability, base);
1095 if (try_with_tablejump)
1097 bool ok = try_tablejump (index_type, index_expr, minval, range,
1098 table_label, default_label, new_default_prob);
1099 gcc_assert (ok);
1101 /* Output the table. */
1102 emit_label (table_label);
1104 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1105 emit_jump_table_data (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1106 gen_rtx_LABEL_REF (Pmode,
1107 table_label),
1108 gen_rtvec_v (ncases, labelvec),
1109 const0_rtx, const0_rtx));
1110 else
1111 emit_jump_table_data (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1112 gen_rtvec_v (ncases, labelvec)));
1114 /* Record no drop-through after the table. */
1115 emit_barrier ();
1118 /* Reset the aux field of all outgoing edges of basic block BB. */
1120 static inline void
1121 reset_out_edges_aux (basic_block bb)
1123 edge e;
1124 edge_iterator ei;
1125 FOR_EACH_EDGE (e, ei, bb->succs)
1126 e->aux = (void *)0;
1129 /* Compute the number of case labels that correspond to each outgoing edge of
1130 STMT. Record this information in the aux field of the edge. */
1132 static inline void
1133 compute_cases_per_edge (gimple stmt)
1135 basic_block bb = gimple_bb (stmt);
1136 reset_out_edges_aux (bb);
1137 int ncases = gimple_switch_num_labels (stmt);
1138 for (int i = ncases - 1; i >= 1; --i)
1140 tree elt = gimple_switch_label (stmt, i);
1141 tree lab = CASE_LABEL (elt);
1142 basic_block case_bb = label_to_block_fn (cfun, lab);
1143 edge case_edge = find_edge (bb, case_bb);
1144 case_edge->aux = (void *)((intptr_t)(case_edge->aux) + 1);
1148 /* Terminate a case (Pascal/Ada) or switch (C) statement
1149 in which ORIG_INDEX is the expression to be tested.
1150 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
1151 type as given in the source before any compiler conversions.
1152 Generate the code to test it and jump to the right place. */
1154 void
1155 expand_case (gimple stmt)
1157 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
1158 rtx default_label = NULL_RTX;
1159 unsigned int count, uniq;
1160 int i;
1161 int ncases = gimple_switch_num_labels (stmt);
1162 tree index_expr = gimple_switch_index (stmt);
1163 tree index_type = TREE_TYPE (index_expr);
1164 tree elt;
1165 basic_block bb = gimple_bb (stmt);
1167 /* A list of case labels; it is first built as a list and it may then
1168 be rearranged into a nearly balanced binary tree. */
1169 struct case_node *case_list = 0;
1171 /* A pool for case nodes. */
1172 alloc_pool case_node_pool;
1174 /* An ERROR_MARK occurs for various reasons including invalid data type.
1175 ??? Can this still happen, with GIMPLE and all? */
1176 if (index_type == error_mark_node)
1177 return;
1179 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
1180 expressions being INTEGER_CST. */
1181 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
1183 case_node_pool = create_alloc_pool ("struct case_node pool",
1184 sizeof (struct case_node),
1185 100);
1187 do_pending_stack_adjust ();
1189 /* Find the default case target label. */
1190 default_label = label_rtx (CASE_LABEL (gimple_switch_default_label (stmt)));
1191 edge default_edge = EDGE_SUCC (bb, 0);
1192 int default_prob = default_edge->probability;
1194 /* Get upper and lower bounds of case values. */
1195 elt = gimple_switch_label (stmt, 1);
1196 minval = fold_convert (index_type, CASE_LOW (elt));
1197 elt = gimple_switch_label (stmt, ncases - 1);
1198 if (CASE_HIGH (elt))
1199 maxval = fold_convert (index_type, CASE_HIGH (elt));
1200 else
1201 maxval = fold_convert (index_type, CASE_LOW (elt));
1203 /* Compute span of values. */
1204 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
1206 /* Listify the labels queue and gather some numbers to decide
1207 how to expand this switch(). */
1208 uniq = 0;
1209 count = 0;
1210 struct pointer_set_t *seen_labels = pointer_set_create ();
1211 compute_cases_per_edge (stmt);
1213 for (i = ncases - 1; i >= 1; --i)
1215 elt = gimple_switch_label (stmt, i);
1216 tree low = CASE_LOW (elt);
1217 gcc_assert (low);
1218 tree high = CASE_HIGH (elt);
1219 gcc_assert (! high || tree_int_cst_lt (low, high));
1220 tree lab = CASE_LABEL (elt);
1222 /* Count the elements.
1223 A range counts double, since it requires two compares. */
1224 count++;
1225 if (high)
1226 count++;
1228 /* If we have not seen this label yet, then increase the
1229 number of unique case node targets seen. */
1230 if (!pointer_set_insert (seen_labels, lab))
1231 uniq++;
1233 /* The bounds on the case range, LOW and HIGH, have to be converted
1234 to case's index type TYPE. Note that the original type of the
1235 case index in the source code is usually "lost" during
1236 gimplification due to type promotion, but the case labels retain the
1237 original type. Make sure to drop overflow flags. */
1238 low = fold_convert (index_type, low);
1239 if (TREE_OVERFLOW (low))
1240 low = build_int_cst_wide (index_type,
1241 TREE_INT_CST_LOW (low),
1242 TREE_INT_CST_HIGH (low));
1244 /* The canonical from of a case label in GIMPLE is that a simple case
1245 has an empty CASE_HIGH. For the casesi and tablejump expanders,
1246 the back ends want simple cases to have high == low. */
1247 if (! high)
1248 high = low;
1249 high = fold_convert (index_type, high);
1250 if (TREE_OVERFLOW (high))
1251 high = build_int_cst_wide (index_type,
1252 TREE_INT_CST_LOW (high),
1253 TREE_INT_CST_HIGH (high));
1255 basic_block case_bb = label_to_block_fn (cfun, lab);
1256 edge case_edge = find_edge (bb, case_bb);
1257 case_list = add_case_node (
1258 case_list, low, high, lab,
1259 case_edge->probability / (intptr_t)(case_edge->aux),
1260 case_node_pool);
1262 pointer_set_destroy (seen_labels);
1263 reset_out_edges_aux (bb);
1265 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
1266 destination, such as one with a default case only.
1267 It also removes cases that are out of range for the switch
1268 type, so we should never get a zero here. */
1269 gcc_assert (count > 0);
1271 rtx before_case = get_last_insn ();
1273 /* Decide how to expand this switch.
1274 The two options at this point are a dispatch table (casesi or
1275 tablejump) or a decision tree. */
1277 if (expand_switch_as_decision_tree_p (range, uniq, count))
1278 emit_case_decision_tree (index_expr, index_type,
1279 case_list, default_label,
1280 default_prob);
1281 else
1282 emit_case_dispatch_table (index_expr, index_type,
1283 case_list, default_label,
1284 minval, maxval, range, bb);
1286 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1288 free_temp_slots ();
1289 free_alloc_pool (case_node_pool);
1292 /* Expand the dispatch to a short decrement chain if there are few cases
1293 to dispatch to. Likewise if neither casesi nor tablejump is available,
1294 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
1295 tablejump. The index mode is always the mode of integer_type_node.
1296 Trap if no case matches the index.
1298 DISPATCH_INDEX is the index expression to switch on. It should be a
1299 memory or register operand.
1301 DISPATCH_TABLE is a set of case labels. The set should be sorted in
1302 ascending order, be contiguous, starting with value 0, and contain only
1303 single-valued case labels. */
1305 void
1306 expand_sjlj_dispatch_table (rtx dispatch_index,
1307 vec<tree> dispatch_table)
1309 tree index_type = integer_type_node;
1310 enum machine_mode index_mode = TYPE_MODE (index_type);
1312 int ncases = dispatch_table.length ();
1314 do_pending_stack_adjust ();
1315 rtx before_case = get_last_insn ();
1317 /* Expand as a decrement-chain if there are 5 or fewer dispatch
1318 labels. This covers more than 98% of the cases in libjava,
1319 and seems to be a reasonable compromise between the "old way"
1320 of expanding as a decision tree or dispatch table vs. the "new
1321 way" with decrement chain or dispatch table. */
1322 if (dispatch_table.length () <= 5
1323 || (!HAVE_casesi && !HAVE_tablejump)
1324 || !flag_jump_tables)
1326 /* Expand the dispatch as a decrement chain:
1328 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
1332 if (index == 0) do_0; else index--;
1333 if (index == 0) do_1; else index--;
1335 if (index == 0) do_N; else index--;
1337 This is more efficient than a dispatch table on most machines.
1338 The last "index--" is redundant but the code is trivially dead
1339 and will be cleaned up by later passes. */
1340 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
1341 rtx zero = CONST0_RTX (index_mode);
1342 for (int i = 0; i < ncases; i++)
1344 tree elt = dispatch_table[i];
1345 rtx lab = label_rtx (CASE_LABEL (elt));
1346 do_jump_if_equal (index_mode, index, zero, lab, 0, -1);
1347 force_expand_binop (index_mode, sub_optab,
1348 index, CONST1_RTX (index_mode),
1349 index, 0, OPTAB_DIRECT);
1352 else
1354 /* Similar to expand_case, but much simpler. */
1355 struct case_node *case_list = 0;
1356 alloc_pool case_node_pool = create_alloc_pool ("struct sjlj_case pool",
1357 sizeof (struct case_node),
1358 ncases);
1359 tree index_expr = make_tree (index_type, dispatch_index);
1360 tree minval = build_int_cst (index_type, 0);
1361 tree maxval = CASE_LOW (dispatch_table.last ());
1362 tree range = maxval;
1363 rtx default_label = gen_label_rtx ();
1365 for (int i = ncases - 1; i >= 0; --i)
1367 tree elt = dispatch_table[i];
1368 tree low = CASE_LOW (elt);
1369 tree lab = CASE_LABEL (elt);
1370 case_list = add_case_node (case_list, low, low, lab, 0, case_node_pool);
1373 emit_case_dispatch_table (index_expr, index_type,
1374 case_list, default_label,
1375 minval, maxval, range,
1376 BLOCK_FOR_INSN (before_case));
1377 emit_label (default_label);
1378 free_alloc_pool (case_node_pool);
1381 /* Dispatching something not handled? Trap! */
1382 expand_builtin_trap ();
1384 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1386 free_temp_slots ();
1390 /* Take an ordered list of case nodes
1391 and transform them into a near optimal binary tree,
1392 on the assumption that any target code selection value is as
1393 likely as any other.
1395 The transformation is performed by splitting the ordered
1396 list into two equal sections plus a pivot. The parts are
1397 then attached to the pivot as left and right branches. Each
1398 branch is then transformed recursively. */
1400 static void
1401 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
1403 case_node_ptr np;
1405 np = *head;
1406 if (np)
1408 int i = 0;
1409 int ranges = 0;
1410 case_node_ptr *npp;
1411 case_node_ptr left;
1413 /* Count the number of entries on branch. Also count the ranges. */
1415 while (np)
1417 if (!tree_int_cst_equal (np->low, np->high))
1418 ranges++;
1420 i++;
1421 np = np->right;
1424 if (i > 2)
1426 /* Split this list if it is long enough for that to help. */
1427 npp = head;
1428 left = *npp;
1430 /* If there are just three nodes, split at the middle one. */
1431 if (i == 3)
1432 npp = &(*npp)->right;
1433 else
1435 /* Find the place in the list that bisects the list's total cost,
1436 where ranges count as 2.
1437 Here I gets half the total cost. */
1438 i = (i + ranges + 1) / 2;
1439 while (1)
1441 /* Skip nodes while their cost does not reach that amount. */
1442 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
1443 i--;
1444 i--;
1445 if (i <= 0)
1446 break;
1447 npp = &(*npp)->right;
1450 *head = np = *npp;
1451 *npp = 0;
1452 np->parent = parent;
1453 np->left = left;
1455 /* Optimize each of the two split parts. */
1456 balance_case_nodes (&np->left, np);
1457 balance_case_nodes (&np->right, np);
1458 np->subtree_prob = np->prob;
1459 np->subtree_prob += np->left->subtree_prob;
1460 np->subtree_prob += np->right->subtree_prob;
1462 else
1464 /* Else leave this branch as one level,
1465 but fill in `parent' fields. */
1466 np = *head;
1467 np->parent = parent;
1468 np->subtree_prob = np->prob;
1469 for (; np->right; np = np->right)
1471 np->right->parent = np;
1472 (*head)->subtree_prob += np->right->subtree_prob;
1478 /* Search the parent sections of the case node tree
1479 to see if a test for the lower bound of NODE would be redundant.
1480 INDEX_TYPE is the type of the index expression.
1482 The instructions to generate the case decision tree are
1483 output in the same order as nodes are processed so it is
1484 known that if a parent node checks the range of the current
1485 node minus one that the current node is bounded at its lower
1486 span. Thus the test would be redundant. */
1488 static int
1489 node_has_low_bound (case_node_ptr node, tree index_type)
1491 tree low_minus_one;
1492 case_node_ptr pnode;
1494 /* If the lower bound of this node is the lowest value in the index type,
1495 we need not test it. */
1497 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
1498 return 1;
1500 /* If this node has a left branch, the value at the left must be less
1501 than that at this node, so it cannot be bounded at the bottom and
1502 we need not bother testing any further. */
1504 if (node->left)
1505 return 0;
1507 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
1508 node->low,
1509 build_int_cst (TREE_TYPE (node->low), 1));
1511 /* If the subtraction above overflowed, we can't verify anything.
1512 Otherwise, look for a parent that tests our value - 1. */
1514 if (! tree_int_cst_lt (low_minus_one, node->low))
1515 return 0;
1517 for (pnode = node->parent; pnode; pnode = pnode->parent)
1518 if (tree_int_cst_equal (low_minus_one, pnode->high))
1519 return 1;
1521 return 0;
1524 /* Search the parent sections of the case node tree
1525 to see if a test for the upper bound of NODE would be redundant.
1526 INDEX_TYPE is the type of the index expression.
1528 The instructions to generate the case decision tree are
1529 output in the same order as nodes are processed so it is
1530 known that if a parent node checks the range of the current
1531 node plus one that the current node is bounded at its upper
1532 span. Thus the test would be redundant. */
1534 static int
1535 node_has_high_bound (case_node_ptr node, tree index_type)
1537 tree high_plus_one;
1538 case_node_ptr pnode;
1540 /* If there is no upper bound, obviously no test is needed. */
1542 if (TYPE_MAX_VALUE (index_type) == NULL)
1543 return 1;
1545 /* If the upper bound of this node is the highest value in the type
1546 of the index expression, we need not test against it. */
1548 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
1549 return 1;
1551 /* If this node has a right branch, the value at the right must be greater
1552 than that at this node, so it cannot be bounded at the top and
1553 we need not bother testing any further. */
1555 if (node->right)
1556 return 0;
1558 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
1559 node->high,
1560 build_int_cst (TREE_TYPE (node->high), 1));
1562 /* If the addition above overflowed, we can't verify anything.
1563 Otherwise, look for a parent that tests our value + 1. */
1565 if (! tree_int_cst_lt (node->high, high_plus_one))
1566 return 0;
1568 for (pnode = node->parent; pnode; pnode = pnode->parent)
1569 if (tree_int_cst_equal (high_plus_one, pnode->low))
1570 return 1;
1572 return 0;
1575 /* Search the parent sections of the
1576 case node tree to see if both tests for the upper and lower
1577 bounds of NODE would be redundant. */
1579 static int
1580 node_is_bounded (case_node_ptr node, tree index_type)
1582 return (node_has_low_bound (node, index_type)
1583 && node_has_high_bound (node, index_type));
1587 /* Emit step-by-step code to select a case for the value of INDEX.
1588 The thus generated decision tree follows the form of the
1589 case-node binary tree NODE, whose nodes represent test conditions.
1590 INDEX_TYPE is the type of the index of the switch.
1592 Care is taken to prune redundant tests from the decision tree
1593 by detecting any boundary conditions already checked by
1594 emitted rtx. (See node_has_high_bound, node_has_low_bound
1595 and node_is_bounded, above.)
1597 Where the test conditions can be shown to be redundant we emit
1598 an unconditional jump to the target code. As a further
1599 optimization, the subordinates of a tree node are examined to
1600 check for bounded nodes. In this case conditional and/or
1601 unconditional jumps as a result of the boundary check for the
1602 current node are arranged to target the subordinates associated
1603 code for out of bound conditions on the current node.
1605 We can assume that when control reaches the code generated here,
1606 the index value has already been compared with the parents
1607 of this node, and determined to be on the same side of each parent
1608 as this node is. Thus, if this node tests for the value 51,
1609 and a parent tested for 52, we don't need to consider
1610 the possibility of a value greater than 51. If another parent
1611 tests for the value 50, then this node need not test anything. */
1613 static void
1614 emit_case_nodes (rtx index, case_node_ptr node, rtx default_label,
1615 int default_prob, tree index_type)
1617 /* If INDEX has an unsigned type, we must make unsigned branches. */
1618 int unsignedp = TYPE_UNSIGNED (index_type);
1619 int probability;
1620 int prob = node->prob, subtree_prob = node->subtree_prob;
1621 enum machine_mode mode = GET_MODE (index);
1622 enum machine_mode imode = TYPE_MODE (index_type);
1624 /* Handle indices detected as constant during RTL expansion. */
1625 if (mode == VOIDmode)
1626 mode = imode;
1628 /* See if our parents have already tested everything for us.
1629 If they have, emit an unconditional jump for this node. */
1630 if (node_is_bounded (node, index_type))
1631 emit_jump (label_rtx (node->code_label));
1633 else if (tree_int_cst_equal (node->low, node->high))
1635 probability = conditional_probability (prob, subtree_prob + default_prob);
1636 /* Node is single valued. First see if the index expression matches
1637 this node and then check our children, if any. */
1638 do_jump_if_equal (mode, index,
1639 convert_modes (mode, imode,
1640 expand_normal (node->low),
1641 unsignedp),
1642 label_rtx (node->code_label), unsignedp, probability);
1643 /* Since this case is taken at this point, reduce its weight from
1644 subtree_weight. */
1645 subtree_prob -= prob;
1646 if (node->right != 0 && node->left != 0)
1648 /* This node has children on both sides.
1649 Dispatch to one side or the other
1650 by comparing the index value with this node's value.
1651 If one subtree is bounded, check that one first,
1652 so we can avoid real branches in the tree. */
1654 if (node_is_bounded (node->right, index_type))
1656 probability = conditional_probability (
1657 node->right->prob,
1658 subtree_prob + default_prob);
1659 emit_cmp_and_jump_insns (index,
1660 convert_modes
1661 (mode, imode,
1662 expand_normal (node->high),
1663 unsignedp),
1664 GT, NULL_RTX, mode, unsignedp,
1665 label_rtx (node->right->code_label),
1666 probability);
1667 emit_case_nodes (index, node->left, default_label, default_prob,
1668 index_type);
1671 else if (node_is_bounded (node->left, index_type))
1673 probability = conditional_probability (
1674 node->left->prob,
1675 subtree_prob + default_prob);
1676 emit_cmp_and_jump_insns (index,
1677 convert_modes
1678 (mode, imode,
1679 expand_normal (node->high),
1680 unsignedp),
1681 LT, NULL_RTX, mode, unsignedp,
1682 label_rtx (node->left->code_label),
1683 probability);
1684 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1687 /* If both children are single-valued cases with no
1688 children, finish up all the work. This way, we can save
1689 one ordered comparison. */
1690 else if (tree_int_cst_equal (node->right->low, node->right->high)
1691 && node->right->left == 0
1692 && node->right->right == 0
1693 && tree_int_cst_equal (node->left->low, node->left->high)
1694 && node->left->left == 0
1695 && node->left->right == 0)
1697 /* Neither node is bounded. First distinguish the two sides;
1698 then emit the code for one side at a time. */
1700 /* See if the value matches what the right hand side
1701 wants. */
1702 probability = conditional_probability (
1703 node->right->prob,
1704 subtree_prob + default_prob);
1705 do_jump_if_equal (mode, index,
1706 convert_modes (mode, imode,
1707 expand_normal (node->right->low),
1708 unsignedp),
1709 label_rtx (node->right->code_label),
1710 unsignedp, probability);
1712 /* See if the value matches what the left hand side
1713 wants. */
1714 probability = conditional_probability (
1715 node->left->prob,
1716 subtree_prob + default_prob);
1717 do_jump_if_equal (mode, index,
1718 convert_modes (mode, imode,
1719 expand_normal (node->left->low),
1720 unsignedp),
1721 label_rtx (node->left->code_label),
1722 unsignedp, probability);
1725 else
1727 /* Neither node is bounded. First distinguish the two sides;
1728 then emit the code for one side at a time. */
1730 tree test_label
1731 = build_decl (curr_insn_location (),
1732 LABEL_DECL, NULL_TREE, NULL_TREE);
1734 /* The default label could be reached either through the right
1735 subtree or the left subtree. Divide the probability
1736 equally. */
1737 probability = conditional_probability (
1738 node->right->subtree_prob + default_prob/2,
1739 subtree_prob + default_prob);
1740 /* See if the value is on the right. */
1741 emit_cmp_and_jump_insns (index,
1742 convert_modes
1743 (mode, imode,
1744 expand_normal (node->high),
1745 unsignedp),
1746 GT, NULL_RTX, mode, unsignedp,
1747 label_rtx (test_label),
1748 probability);
1749 default_prob /= 2;
1751 /* Value must be on the left.
1752 Handle the left-hand subtree. */
1753 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1754 /* If left-hand subtree does nothing,
1755 go to default. */
1756 if (default_label)
1757 emit_jump (default_label);
1759 /* Code branches here for the right-hand subtree. */
1760 expand_label (test_label);
1761 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1765 else if (node->right != 0 && node->left == 0)
1767 /* Here we have a right child but no left so we issue a conditional
1768 branch to default and process the right child.
1770 Omit the conditional branch to default if the right child
1771 does not have any children and is single valued; it would
1772 cost too much space to save so little time. */
1774 if (node->right->right || node->right->left
1775 || !tree_int_cst_equal (node->right->low, node->right->high))
1777 if (!node_has_low_bound (node, index_type))
1779 probability = conditional_probability (
1780 default_prob/2,
1781 subtree_prob + default_prob);
1782 emit_cmp_and_jump_insns (index,
1783 convert_modes
1784 (mode, imode,
1785 expand_normal (node->high),
1786 unsignedp),
1787 LT, NULL_RTX, mode, unsignedp,
1788 default_label,
1789 probability);
1790 default_prob /= 2;
1793 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1795 else
1797 probability = conditional_probability (
1798 node->right->subtree_prob,
1799 subtree_prob + default_prob);
1800 /* We cannot process node->right normally
1801 since we haven't ruled out the numbers less than
1802 this node's value. So handle node->right explicitly. */
1803 do_jump_if_equal (mode, index,
1804 convert_modes
1805 (mode, imode,
1806 expand_normal (node->right->low),
1807 unsignedp),
1808 label_rtx (node->right->code_label), unsignedp, probability);
1812 else if (node->right == 0 && node->left != 0)
1814 /* Just one subtree, on the left. */
1815 if (node->left->left || node->left->right
1816 || !tree_int_cst_equal (node->left->low, node->left->high))
1818 if (!node_has_high_bound (node, index_type))
1820 probability = conditional_probability (
1821 default_prob/2,
1822 subtree_prob + default_prob);
1823 emit_cmp_and_jump_insns (index,
1824 convert_modes
1825 (mode, imode,
1826 expand_normal (node->high),
1827 unsignedp),
1828 GT, NULL_RTX, mode, unsignedp,
1829 default_label,
1830 probability);
1831 default_prob /= 2;
1834 emit_case_nodes (index, node->left, default_label,
1835 default_prob, index_type);
1837 else
1839 probability = conditional_probability (
1840 node->left->subtree_prob,
1841 subtree_prob + default_prob);
1842 /* We cannot process node->left normally
1843 since we haven't ruled out the numbers less than
1844 this node's value. So handle node->left explicitly. */
1845 do_jump_if_equal (mode, index,
1846 convert_modes
1847 (mode, imode,
1848 expand_normal (node->left->low),
1849 unsignedp),
1850 label_rtx (node->left->code_label), unsignedp, probability);
1854 else
1856 /* Node is a range. These cases are very similar to those for a single
1857 value, except that we do not start by testing whether this node
1858 is the one to branch to. */
1860 if (node->right != 0 && node->left != 0)
1862 /* Node has subtrees on both sides.
1863 If the right-hand subtree is bounded,
1864 test for it first, since we can go straight there.
1865 Otherwise, we need to make a branch in the control structure,
1866 then handle the two subtrees. */
1867 tree test_label = 0;
1869 if (node_is_bounded (node->right, index_type))
1871 /* Right hand node is fully bounded so we can eliminate any
1872 testing and branch directly to the target code. */
1873 probability = conditional_probability (
1874 node->right->subtree_prob,
1875 subtree_prob + default_prob);
1876 emit_cmp_and_jump_insns (index,
1877 convert_modes
1878 (mode, imode,
1879 expand_normal (node->high),
1880 unsignedp),
1881 GT, NULL_RTX, mode, unsignedp,
1882 label_rtx (node->right->code_label),
1883 probability);
1885 else
1887 /* Right hand node requires testing.
1888 Branch to a label where we will handle it later. */
1890 test_label = build_decl (curr_insn_location (),
1891 LABEL_DECL, NULL_TREE, NULL_TREE);
1892 probability = conditional_probability (
1893 node->right->subtree_prob + default_prob/2,
1894 subtree_prob + default_prob);
1895 emit_cmp_and_jump_insns (index,
1896 convert_modes
1897 (mode, imode,
1898 expand_normal (node->high),
1899 unsignedp),
1900 GT, NULL_RTX, mode, unsignedp,
1901 label_rtx (test_label),
1902 probability);
1903 default_prob /= 2;
1906 /* Value belongs to this node or to the left-hand subtree. */
1908 probability = conditional_probability (
1909 prob,
1910 subtree_prob + default_prob);
1911 emit_cmp_and_jump_insns (index,
1912 convert_modes
1913 (mode, imode,
1914 expand_normal (node->low),
1915 unsignedp),
1916 GE, NULL_RTX, mode, unsignedp,
1917 label_rtx (node->code_label),
1918 probability);
1920 /* Handle the left-hand subtree. */
1921 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1923 /* If right node had to be handled later, do that now. */
1925 if (test_label)
1927 /* If the left-hand subtree fell through,
1928 don't let it fall into the right-hand subtree. */
1929 if (default_label)
1930 emit_jump (default_label);
1932 expand_label (test_label);
1933 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1937 else if (node->right != 0 && node->left == 0)
1939 /* Deal with values to the left of this node,
1940 if they are possible. */
1941 if (!node_has_low_bound (node, index_type))
1943 probability = conditional_probability (
1944 default_prob/2,
1945 subtree_prob + default_prob);
1946 emit_cmp_and_jump_insns (index,
1947 convert_modes
1948 (mode, imode,
1949 expand_normal (node->low),
1950 unsignedp),
1951 LT, NULL_RTX, mode, unsignedp,
1952 default_label,
1953 probability);
1954 default_prob /= 2;
1957 /* Value belongs to this node or to the right-hand subtree. */
1959 probability = conditional_probability (
1960 prob,
1961 subtree_prob + default_prob);
1962 emit_cmp_and_jump_insns (index,
1963 convert_modes
1964 (mode, imode,
1965 expand_normal (node->high),
1966 unsignedp),
1967 LE, NULL_RTX, mode, unsignedp,
1968 label_rtx (node->code_label),
1969 probability);
1971 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1974 else if (node->right == 0 && node->left != 0)
1976 /* Deal with values to the right of this node,
1977 if they are possible. */
1978 if (!node_has_high_bound (node, index_type))
1980 probability = conditional_probability (
1981 default_prob/2,
1982 subtree_prob + default_prob);
1983 emit_cmp_and_jump_insns (index,
1984 convert_modes
1985 (mode, imode,
1986 expand_normal (node->high),
1987 unsignedp),
1988 GT, NULL_RTX, mode, unsignedp,
1989 default_label,
1990 probability);
1991 default_prob /= 2;
1994 /* Value belongs to this node or to the left-hand subtree. */
1996 probability = conditional_probability (
1997 prob,
1998 subtree_prob + default_prob);
1999 emit_cmp_and_jump_insns (index,
2000 convert_modes
2001 (mode, imode,
2002 expand_normal (node->low),
2003 unsignedp),
2004 GE, NULL_RTX, mode, unsignedp,
2005 label_rtx (node->code_label),
2006 probability);
2008 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2011 else
2013 /* Node has no children so we check low and high bounds to remove
2014 redundant tests. Only one of the bounds can exist,
2015 since otherwise this node is bounded--a case tested already. */
2016 int high_bound = node_has_high_bound (node, index_type);
2017 int low_bound = node_has_low_bound (node, index_type);
2019 if (!high_bound && low_bound)
2021 probability = conditional_probability (
2022 default_prob,
2023 subtree_prob + default_prob);
2024 emit_cmp_and_jump_insns (index,
2025 convert_modes
2026 (mode, imode,
2027 expand_normal (node->high),
2028 unsignedp),
2029 GT, NULL_RTX, mode, unsignedp,
2030 default_label,
2031 probability);
2034 else if (!low_bound && high_bound)
2036 probability = conditional_probability (
2037 default_prob,
2038 subtree_prob + default_prob);
2039 emit_cmp_and_jump_insns (index,
2040 convert_modes
2041 (mode, imode,
2042 expand_normal (node->low),
2043 unsignedp),
2044 LT, NULL_RTX, mode, unsignedp,
2045 default_label,
2046 probability);
2048 else if (!low_bound && !high_bound)
2050 /* Widen LOW and HIGH to the same width as INDEX. */
2051 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2052 tree low = build1 (CONVERT_EXPR, type, node->low);
2053 tree high = build1 (CONVERT_EXPR, type, node->high);
2054 rtx low_rtx, new_index, new_bound;
2056 /* Instead of doing two branches, emit one unsigned branch for
2057 (index-low) > (high-low). */
2058 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2059 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2060 NULL_RTX, unsignedp,
2061 OPTAB_WIDEN);
2062 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2063 high, low),
2064 NULL_RTX, mode, EXPAND_NORMAL);
2066 probability = conditional_probability (
2067 default_prob,
2068 subtree_prob + default_prob);
2069 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2070 mode, 1, default_label, probability);
2073 emit_jump (label_rtx (node->code_label));