* config/msp430/msp430.c (msp430_asm_integer): Support addition
[official-gcc.git] / gcc / stmt.c
blob58bdaa0cb9f51b98af685d00d357383c7f85773a
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987-2015 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 "hash-set.h"
33 #include "vec.h"
34 #include "input.h"
35 #include "alias.h"
36 #include "symtab.h"
37 #include "inchash.h"
38 #include "tree.h"
39 #include "fold-const.h"
40 #include "varasm.h"
41 #include "stor-layout.h"
42 #include "tm_p.h"
43 #include "flags.h"
44 #include "except.h"
45 #include "function.h"
46 #include "insn-config.h"
47 #include "hashtab.h"
48 #include "statistics.h"
49 #include "expmed.h"
50 #include "dojump.h"
51 #include "explow.h"
52 #include "calls.h"
53 #include "emit-rtl.h"
54 #include "stmt.h"
55 #include "expr.h"
56 #include "libfuncs.h"
57 #include "recog.h"
58 #include "diagnostic-core.h"
59 #include "output.h"
60 #include "langhooks.h"
61 #include "predict.h"
62 #include "insn-codes.h"
63 #include "optabs.h"
64 #include "target.h"
65 #include "cfganal.h"
66 #include "basic-block.h"
67 #include "tree-ssa-alias.h"
68 #include "internal-fn.h"
69 #include "gimple-expr.h"
70 #include "is-a.h"
71 #include "gimple.h"
72 #include "regs.h"
73 #include "alloc-pool.h"
74 #include "pretty-print.h"
75 #include "params.h"
76 #include "dumpfile.h"
77 #include "builtins.h"
80 /* Functions and data structures for expanding case statements. */
82 /* Case label structure, used to hold info on labels within case
83 statements. We handle "range" labels; for a single-value label
84 as in C, the high and low limits are the same.
86 We start with a vector of case nodes sorted in ascending order, and
87 the default label as the last element in the vector. Before expanding
88 to RTL, we transform this vector into a list linked via the RIGHT
89 fields in the case_node struct. Nodes with higher case values are
90 later in the list.
92 Switch statements can be output in three forms. A branch table is
93 used if there are more than a few labels and the labels are dense
94 within the range between the smallest and largest case value. If a
95 branch table is used, no further manipulations are done with the case
96 node chain.
98 The alternative to the use of a branch table is to generate a series
99 of compare and jump insns. When that is done, we use the LEFT, RIGHT,
100 and PARENT fields to hold a binary tree. Initially the tree is
101 totally unbalanced, with everything on the right. We balance the tree
102 with nodes on the left having lower case values than the parent
103 and nodes on the right having higher values. We then output the tree
104 in order.
106 For very small, suitable switch statements, we can generate a series
107 of simple bit test and branches instead. */
109 struct case_node
111 struct case_node *left; /* Left son in binary tree */
112 struct case_node *right; /* Right son in binary tree; also node chain */
113 struct case_node *parent; /* Parent of node in binary tree */
114 tree low; /* Lowest index value for this label */
115 tree high; /* Highest index value for this label */
116 tree code_label; /* Label to jump to when node matches */
117 int prob; /* Probability of taking this case. */
118 /* Probability of reaching subtree rooted at this node */
119 int subtree_prob;
122 typedef struct case_node case_node;
123 typedef struct case_node *case_node_ptr;
125 extern basic_block label_to_block_fn (struct function *, tree);
127 static bool check_unique_operand_names (tree, tree, tree);
128 static char *resolve_operand_name_1 (char *, tree, tree, tree);
129 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
130 static int node_has_low_bound (case_node_ptr, tree);
131 static int node_has_high_bound (case_node_ptr, tree);
132 static int node_is_bounded (case_node_ptr, tree);
133 static void emit_case_nodes (rtx, case_node_ptr, rtx_code_label *, int, tree);
135 /* Return the rtx-label that corresponds to a LABEL_DECL,
136 creating it if necessary. */
138 rtx_insn *
139 label_rtx (tree label)
141 gcc_assert (TREE_CODE (label) == LABEL_DECL);
143 if (!DECL_RTL_SET_P (label))
145 rtx_code_label *r = gen_label_rtx ();
146 SET_DECL_RTL (label, r);
147 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
148 LABEL_PRESERVE_P (r) = 1;
151 return as_a <rtx_insn *> (DECL_RTL (label));
154 /* As above, but also put it on the forced-reference list of the
155 function that contains it. */
156 rtx_insn *
157 force_label_rtx (tree label)
159 rtx_insn *ref = label_rtx (label);
160 tree function = decl_function_context (label);
162 gcc_assert (function);
164 forced_labels = gen_rtx_INSN_LIST (VOIDmode, ref, forced_labels);
165 return ref;
168 /* As label_rtx, but ensures (in check build), that returned value is
169 an existing label (i.e. rtx with code CODE_LABEL). */
170 rtx_code_label *
171 jump_target_rtx (tree label)
173 return as_a <rtx_code_label *> (label_rtx (label));
176 /* Add an unconditional jump to LABEL as the next sequential instruction. */
178 void
179 emit_jump (rtx label)
181 do_pending_stack_adjust ();
182 emit_jump_insn (gen_jump (label));
183 emit_barrier ();
186 /* Handle goto statements and the labels that they can go to. */
188 /* Specify the location in the RTL code of a label LABEL,
189 which is a LABEL_DECL tree node.
191 This is used for the kind of label that the user can jump to with a
192 goto statement, and for alternatives of a switch or case statement.
193 RTL labels generated for loops and conditionals don't go through here;
194 they are generated directly at the RTL level, by other functions below.
196 Note that this has nothing to do with defining label *names*.
197 Languages vary in how they do that and what that even means. */
199 void
200 expand_label (tree label)
202 rtx_code_label *label_r = jump_target_rtx (label);
204 do_pending_stack_adjust ();
205 emit_label (label_r);
206 if (DECL_NAME (label))
207 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
209 if (DECL_NONLOCAL (label))
211 expand_builtin_setjmp_receiver (NULL);
212 nonlocal_goto_handler_labels
213 = gen_rtx_INSN_LIST (VOIDmode, label_r,
214 nonlocal_goto_handler_labels);
217 if (FORCED_LABEL (label))
218 forced_labels = gen_rtx_INSN_LIST (VOIDmode, label_r, forced_labels);
220 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
221 maybe_set_first_label_num (label_r);
224 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
225 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
226 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
227 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
228 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
229 constraint allows the use of a register operand. And, *IS_INOUT
230 will be true if the operand is read-write, i.e., if it is used as
231 an input as well as an output. If *CONSTRAINT_P is not in
232 canonical form, it will be made canonical. (Note that `+' will be
233 replaced with `=' as part of this process.)
235 Returns TRUE if all went well; FALSE if an error occurred. */
237 bool
238 parse_output_constraint (const char **constraint_p, int operand_num,
239 int ninputs, int noutputs, bool *allows_mem,
240 bool *allows_reg, bool *is_inout)
242 const char *constraint = *constraint_p;
243 const char *p;
245 /* Assume the constraint doesn't allow the use of either a register
246 or memory. */
247 *allows_mem = false;
248 *allows_reg = false;
250 /* Allow the `=' or `+' to not be at the beginning of the string,
251 since it wasn't explicitly documented that way, and there is a
252 large body of code that puts it last. Swap the character to
253 the front, so as not to uglify any place else. */
254 p = strchr (constraint, '=');
255 if (!p)
256 p = strchr (constraint, '+');
258 /* If the string doesn't contain an `=', issue an error
259 message. */
260 if (!p)
262 error ("output operand constraint lacks %<=%>");
263 return false;
266 /* If the constraint begins with `+', then the operand is both read
267 from and written to. */
268 *is_inout = (*p == '+');
270 /* Canonicalize the output constraint so that it begins with `='. */
271 if (p != constraint || *is_inout)
273 char *buf;
274 size_t c_len = strlen (constraint);
276 if (p != constraint)
277 warning (0, "output constraint %qc for operand %d "
278 "is not at the beginning",
279 *p, operand_num);
281 /* Make a copy of the constraint. */
282 buf = XALLOCAVEC (char, c_len + 1);
283 strcpy (buf, constraint);
284 /* Swap the first character and the `=' or `+'. */
285 buf[p - constraint] = buf[0];
286 /* Make sure the first character is an `='. (Until we do this,
287 it might be a `+'.) */
288 buf[0] = '=';
289 /* Replace the constraint with the canonicalized string. */
290 *constraint_p = ggc_alloc_string (buf, c_len);
291 constraint = *constraint_p;
294 /* Loop through the constraint string. */
295 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
296 switch (*p)
298 case '+':
299 case '=':
300 error ("operand constraint contains incorrectly positioned "
301 "%<+%> or %<=%>");
302 return false;
304 case '%':
305 if (operand_num + 1 == ninputs + noutputs)
307 error ("%<%%%> constraint used with last operand");
308 return false;
310 break;
312 case '?': case '!': case '*': case '&': case '#':
313 case '$': case '^':
314 case 'E': case 'F': case 'G': case 'H':
315 case 's': case 'i': case 'n':
316 case 'I': case 'J': case 'K': case 'L': case 'M':
317 case 'N': case 'O': case 'P': case ',':
318 break;
320 case '0': case '1': case '2': case '3': case '4':
321 case '5': case '6': case '7': case '8': case '9':
322 case '[':
323 error ("matching constraint not valid in output operand");
324 return false;
326 case '<': case '>':
327 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
328 excepting those that expand_call created. So match memory
329 and hope. */
330 *allows_mem = true;
331 break;
333 case 'g': case 'X':
334 *allows_reg = true;
335 *allows_mem = true;
336 break;
338 default:
339 if (!ISALPHA (*p))
340 break;
341 enum constraint_num cn = lookup_constraint (p);
342 if (reg_class_for_constraint (cn) != NO_REGS
343 || insn_extra_address_constraint (cn))
344 *allows_reg = true;
345 else if (insn_extra_memory_constraint (cn))
346 *allows_mem = true;
347 else
348 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
349 break;
352 return true;
355 /* Similar, but for input constraints. */
357 bool
358 parse_input_constraint (const char **constraint_p, int input_num,
359 int ninputs, int noutputs, int ninout,
360 const char * const * constraints,
361 bool *allows_mem, bool *allows_reg)
363 const char *constraint = *constraint_p;
364 const char *orig_constraint = constraint;
365 size_t c_len = strlen (constraint);
366 size_t j;
367 bool saw_match = false;
369 /* Assume the constraint doesn't allow the use of either
370 a register or memory. */
371 *allows_mem = false;
372 *allows_reg = false;
374 /* Make sure constraint has neither `=', `+', nor '&'. */
376 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
377 switch (constraint[j])
379 case '+': case '=': case '&':
380 if (constraint == orig_constraint)
382 error ("input operand constraint contains %qc", constraint[j]);
383 return false;
385 break;
387 case '%':
388 if (constraint == orig_constraint
389 && input_num + 1 == ninputs - ninout)
391 error ("%<%%%> constraint used with last operand");
392 return false;
394 break;
396 case '<': case '>':
397 case '?': case '!': case '*': case '#':
398 case '$': case '^':
399 case 'E': case 'F': case 'G': case 'H':
400 case 's': case 'i': case 'n':
401 case 'I': case 'J': case 'K': case 'L': case 'M':
402 case 'N': case 'O': case 'P': case ',':
403 break;
405 /* Whether or not a numeric constraint allows a register is
406 decided by the matching constraint, and so there is no need
407 to do anything special with them. We must handle them in
408 the default case, so that we don't unnecessarily force
409 operands to memory. */
410 case '0': case '1': case '2': case '3': case '4':
411 case '5': case '6': case '7': case '8': case '9':
413 char *end;
414 unsigned long match;
416 saw_match = true;
418 match = strtoul (constraint + j, &end, 10);
419 if (match >= (unsigned long) noutputs)
421 error ("matching constraint references invalid operand number");
422 return false;
425 /* Try and find the real constraint for this dup. Only do this
426 if the matching constraint is the only alternative. */
427 if (*end == '\0'
428 && (j == 0 || (j == 1 && constraint[0] == '%')))
430 constraint = constraints[match];
431 *constraint_p = constraint;
432 c_len = strlen (constraint);
433 j = 0;
434 /* ??? At the end of the loop, we will skip the first part of
435 the matched constraint. This assumes not only that the
436 other constraint is an output constraint, but also that
437 the '=' or '+' come first. */
438 break;
440 else
441 j = end - constraint;
442 /* Anticipate increment at end of loop. */
443 j--;
445 /* Fall through. */
447 case 'g': case 'X':
448 *allows_reg = true;
449 *allows_mem = true;
450 break;
452 default:
453 if (! ISALPHA (constraint[j]))
455 error ("invalid punctuation %qc in constraint", constraint[j]);
456 return false;
458 enum constraint_num cn = lookup_constraint (constraint + j);
459 if (reg_class_for_constraint (cn) != NO_REGS
460 || insn_extra_address_constraint (cn))
461 *allows_reg = true;
462 else if (insn_extra_memory_constraint (cn))
463 *allows_mem = true;
464 else
465 insn_extra_constraint_allows_reg_mem (cn, allows_reg, allows_mem);
466 break;
469 if (saw_match && !*allows_reg)
470 warning (0, "matching constraint does not allow a register");
472 return true;
475 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
476 can be an asm-declared register. Called via walk_tree. */
478 static tree
479 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
480 void *data)
482 tree decl = *declp;
483 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
485 if (TREE_CODE (decl) == VAR_DECL)
487 if (DECL_HARD_REGISTER (decl)
488 && REG_P (DECL_RTL (decl))
489 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
491 rtx reg = DECL_RTL (decl);
493 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
494 return decl;
496 walk_subtrees = 0;
498 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
499 walk_subtrees = 0;
500 return NULL_TREE;
503 /* If there is an overlap between *REGS and DECL, return the first overlap
504 found. */
505 tree
506 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
508 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
512 /* A subroutine of expand_asm_operands. Check that all operand names
513 are unique. Return true if so. We rely on the fact that these names
514 are identifiers, and so have been canonicalized by get_identifier,
515 so all we need are pointer comparisons. */
517 static bool
518 check_unique_operand_names (tree outputs, tree inputs, tree labels)
520 tree i, j, i_name = NULL_TREE;
522 for (i = outputs; i ; i = TREE_CHAIN (i))
524 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
525 if (! i_name)
526 continue;
528 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
529 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
530 goto failure;
533 for (i = inputs; i ; i = TREE_CHAIN (i))
535 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
536 if (! i_name)
537 continue;
539 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
540 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
541 goto failure;
542 for (j = outputs; j ; j = TREE_CHAIN (j))
543 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
544 goto failure;
547 for (i = labels; i ; i = TREE_CHAIN (i))
549 i_name = TREE_PURPOSE (i);
550 if (! i_name)
551 continue;
553 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
554 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
555 goto failure;
556 for (j = inputs; j ; j = TREE_CHAIN (j))
557 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
558 goto failure;
561 return true;
563 failure:
564 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
565 return false;
568 /* Resolve the names of the operands in *POUTPUTS and *PINPUTS to numbers,
569 and replace the name expansions in STRING and in the constraints to
570 those numbers. This is generally done in the front end while creating
571 the ASM_EXPR generic tree that eventually becomes the GIMPLE_ASM. */
573 tree
574 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
576 char *buffer;
577 char *p;
578 const char *c;
579 tree t;
581 check_unique_operand_names (outputs, inputs, labels);
583 /* Substitute [<name>] in input constraint strings. There should be no
584 named operands in output constraints. */
585 for (t = inputs; t ; t = TREE_CHAIN (t))
587 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
588 if (strchr (c, '[') != NULL)
590 p = buffer = xstrdup (c);
591 while ((p = strchr (p, '[')) != NULL)
592 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
593 TREE_VALUE (TREE_PURPOSE (t))
594 = build_string (strlen (buffer), buffer);
595 free (buffer);
599 /* Now check for any needed substitutions in the template. */
600 c = TREE_STRING_POINTER (string);
601 while ((c = strchr (c, '%')) != NULL)
603 if (c[1] == '[')
604 break;
605 else if (ISALPHA (c[1]) && c[2] == '[')
606 break;
607 else
609 c += 1 + (c[1] == '%');
610 continue;
614 if (c)
616 /* OK, we need to make a copy so we can perform the substitutions.
617 Assume that we will not need extra space--we get to remove '['
618 and ']', which means we cannot have a problem until we have more
619 than 999 operands. */
620 buffer = xstrdup (TREE_STRING_POINTER (string));
621 p = buffer + (c - TREE_STRING_POINTER (string));
623 while ((p = strchr (p, '%')) != NULL)
625 if (p[1] == '[')
626 p += 1;
627 else if (ISALPHA (p[1]) && p[2] == '[')
628 p += 2;
629 else
631 p += 1 + (p[1] == '%');
632 continue;
635 p = resolve_operand_name_1 (p, outputs, inputs, labels);
638 string = build_string (strlen (buffer), buffer);
639 free (buffer);
642 return string;
645 /* A subroutine of resolve_operand_names. P points to the '[' for a
646 potential named operand of the form [<name>]. In place, replace
647 the name and brackets with a number. Return a pointer to the
648 balance of the string after substitution. */
650 static char *
651 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
653 char *q;
654 int op;
655 tree t;
657 /* Collect the operand name. */
658 q = strchr (++p, ']');
659 if (!q)
661 error ("missing close brace for named operand");
662 return strchr (p, '\0');
664 *q = '\0';
666 /* Resolve the name to a number. */
667 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
669 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
670 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
671 goto found;
673 for (t = inputs; 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 = labels; t ; t = TREE_CHAIN (t), op++)
681 tree name = TREE_PURPOSE (t);
682 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
683 goto found;
686 error ("undefined named operand %qs", identifier_to_locale (p));
687 op = 0;
689 found:
690 /* Replace the name with the number. Unfortunately, not all libraries
691 get the return value of sprintf correct, so search for the end of the
692 generated string by hand. */
693 sprintf (--p, "%d", op);
694 p = strchr (p, '\0');
696 /* Verify the no extra buffer space assumption. */
697 gcc_assert (p <= q);
699 /* Shift the rest of the buffer down to fill the gap. */
700 memmove (p, q + 1, strlen (q + 1) + 1);
702 return p;
706 /* Generate RTL to return directly from the current function.
707 (That is, we bypass any return value.) */
709 void
710 expand_naked_return (void)
712 rtx_code_label *end_label;
714 clear_pending_stack_adjust ();
715 do_pending_stack_adjust ();
717 end_label = naked_return_label;
718 if (end_label == 0)
719 end_label = naked_return_label = gen_label_rtx ();
721 emit_jump (end_label);
724 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
725 is the probability of jumping to LABEL. */
726 static void
727 do_jump_if_equal (machine_mode mode, rtx op0, rtx op1, rtx_code_label *label,
728 int unsignedp, int prob)
730 gcc_assert (prob <= REG_BR_PROB_BASE);
731 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
732 NULL_RTX, NULL, label, prob);
735 /* Do the insertion of a case label into case_list. The labels are
736 fed to us in descending order from the sorted vector of case labels used
737 in the tree part of the middle end. So the list we construct is
738 sorted in ascending order.
740 LABEL is the case label to be inserted. LOW and HIGH are the bounds
741 against which the index is compared to jump to LABEL and PROB is the
742 estimated probability LABEL is reached from the switch statement. */
744 static struct case_node *
745 add_case_node (struct case_node *head, tree low, tree high,
746 tree label, int prob, pool_allocator<case_node> &case_node_pool)
748 struct case_node *r;
750 gcc_checking_assert (low);
751 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
753 /* Add this label to the chain. */
754 r = case_node_pool.allocate ();
755 r->low = low;
756 r->high = high;
757 r->code_label = label;
758 r->parent = r->left = NULL;
759 r->prob = prob;
760 r->subtree_prob = prob;
761 r->right = head;
762 return r;
765 /* Dump ROOT, a list or tree of case nodes, to file. */
767 static void
768 dump_case_nodes (FILE *f, struct case_node *root,
769 int indent_step, int indent_level)
771 if (root == 0)
772 return;
773 indent_level++;
775 dump_case_nodes (f, root->left, indent_step, indent_level);
777 fputs (";; ", f);
778 fprintf (f, "%*s", indent_step * indent_level, "");
779 print_dec (root->low, f, TYPE_SIGN (TREE_TYPE (root->low)));
780 if (!tree_int_cst_equal (root->low, root->high))
782 fprintf (f, " ... ");
783 print_dec (root->high, f, TYPE_SIGN (TREE_TYPE (root->high)));
785 fputs ("\n", f);
787 dump_case_nodes (f, root->right, indent_step, indent_level);
790 #ifndef HAVE_casesi
791 #define HAVE_casesi 0
792 #endif
794 /* Return the smallest number of different values for which it is best to use a
795 jump-table instead of a tree of conditional branches. */
797 static unsigned int
798 case_values_threshold (void)
800 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
802 if (threshold == 0)
803 threshold = targetm.case_values_threshold ();
805 return threshold;
808 /* Return true if a switch should be expanded as a decision tree.
809 RANGE is the difference between highest and lowest case.
810 UNIQ is number of unique case node targets, not counting the default case.
811 COUNT is the number of comparisons needed, not counting the default case. */
813 static bool
814 expand_switch_as_decision_tree_p (tree range,
815 unsigned int uniq ATTRIBUTE_UNUSED,
816 unsigned int count)
818 int max_ratio;
820 /* If neither casesi or tablejump is available, or flag_jump_tables
821 over-ruled us, we really have no choice. */
822 if (!HAVE_casesi && !HAVE_tablejump)
823 return true;
824 if (!flag_jump_tables)
825 return true;
826 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
827 if (flag_pic)
828 return true;
829 #endif
831 /* If the switch is relatively small such that the cost of one
832 indirect jump on the target are higher than the cost of a
833 decision tree, go with the decision tree.
835 If range of values is much bigger than number of values,
836 or if it is too large to represent in a HOST_WIDE_INT,
837 make a sequence of conditional branches instead of a dispatch.
839 The definition of "much bigger" depends on whether we are
840 optimizing for size or for speed. If the former, the maximum
841 ratio range/count = 3, because this was found to be the optimal
842 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
843 10 is much older, and was probably selected after an extensive
844 benchmarking investigation on numerous platforms. Or maybe it
845 just made sense to someone at some point in the history of GCC,
846 who knows... */
847 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
848 if (count < case_values_threshold ()
849 || ! tree_fits_uhwi_p (range)
850 || compare_tree_int (range, max_ratio * count) > 0)
851 return true;
853 return false;
856 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
857 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
858 DEFAULT_PROB is the estimated probability that it jumps to
859 DEFAULT_LABEL.
861 We generate a binary decision tree to select the appropriate target
862 code. This is done as follows:
864 If the index is a short or char that we do not have
865 an insn to handle comparisons directly, convert it to
866 a full integer now, rather than letting each comparison
867 generate the conversion.
869 Load the index into a register.
871 The list of cases is rearranged into a binary tree,
872 nearly optimal assuming equal probability for each case.
874 The tree is transformed into RTL, eliminating redundant
875 test conditions at the same time.
877 If program flow could reach the end of the decision tree
878 an unconditional jump to the default code is emitted.
880 The above process is unaware of the CFG. The caller has to fix up
881 the CFG itself. This is done in cfgexpand.c. */
883 static void
884 emit_case_decision_tree (tree index_expr, tree index_type,
885 case_node_ptr case_list, rtx_code_label *default_label,
886 int default_prob)
888 rtx index = expand_normal (index_expr);
890 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
891 && ! have_insn_for (COMPARE, GET_MODE (index)))
893 int unsignedp = TYPE_UNSIGNED (index_type);
894 machine_mode wider_mode;
895 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
896 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
897 if (have_insn_for (COMPARE, wider_mode))
899 index = convert_to_mode (wider_mode, index, unsignedp);
900 break;
904 do_pending_stack_adjust ();
906 if (MEM_P (index))
908 index = copy_to_reg (index);
909 if (TREE_CODE (index_expr) == SSA_NAME)
910 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
913 balance_case_nodes (&case_list, NULL);
915 if (dump_file && (dump_flags & TDF_DETAILS))
917 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
918 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
919 dump_case_nodes (dump_file, case_list, indent_step, 0);
922 emit_case_nodes (index, case_list, default_label, default_prob, index_type);
923 if (default_label)
924 emit_jump (default_label);
927 /* Return the sum of probabilities of outgoing edges of basic block BB. */
929 static int
930 get_outgoing_edge_probs (basic_block bb)
932 edge e;
933 edge_iterator ei;
934 int prob_sum = 0;
935 if (!bb)
936 return 0;
937 FOR_EACH_EDGE (e, ei, bb->succs)
938 prob_sum += e->probability;
939 return prob_sum;
942 /* Computes the conditional probability of jumping to a target if the branch
943 instruction is executed.
944 TARGET_PROB is the estimated probability of jumping to a target relative
945 to some basic block BB.
946 BASE_PROB is the probability of reaching the branch instruction relative
947 to the same basic block BB. */
949 static inline int
950 conditional_probability (int target_prob, int base_prob)
952 if (base_prob > 0)
954 gcc_assert (target_prob >= 0);
955 gcc_assert (target_prob <= base_prob);
956 return GCOV_COMPUTE_SCALE (target_prob, base_prob);
958 return -1;
961 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
962 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
963 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
964 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
966 First, a jump insn is emitted. First we try "casesi". If that
967 fails, try "tablejump". A target *must* have one of them (or both).
969 Then, a table with the target labels is emitted.
971 The process is unaware of the CFG. The caller has to fix up
972 the CFG itself. This is done in cfgexpand.c. */
974 static void
975 emit_case_dispatch_table (tree index_expr, tree index_type,
976 struct case_node *case_list, rtx default_label,
977 tree minval, tree maxval, tree range,
978 basic_block stmt_bb)
980 int i, ncases;
981 struct case_node *n;
982 rtx *labelvec;
983 rtx fallback_label = label_rtx (case_list->code_label);
984 rtx_code_label *table_label = gen_label_rtx ();
985 bool has_gaps = false;
986 edge default_edge = stmt_bb ? EDGE_SUCC (stmt_bb, 0) : NULL;
987 int default_prob = default_edge ? default_edge->probability : 0;
988 int base = get_outgoing_edge_probs (stmt_bb);
989 bool try_with_tablejump = false;
991 int new_default_prob = conditional_probability (default_prob,
992 base);
994 if (! try_casesi (index_type, index_expr, minval, range,
995 table_label, default_label, fallback_label,
996 new_default_prob))
998 /* Index jumptables from zero for suitable values of minval to avoid
999 a subtraction. For the rationale see:
1000 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
1001 if (optimize_insn_for_speed_p ()
1002 && compare_tree_int (minval, 0) > 0
1003 && compare_tree_int (minval, 3) < 0)
1005 minval = build_int_cst (index_type, 0);
1006 range = maxval;
1007 has_gaps = true;
1009 try_with_tablejump = true;
1012 /* Get table of labels to jump to, in order of case index. */
1014 ncases = tree_to_shwi (range) + 1;
1015 labelvec = XALLOCAVEC (rtx, ncases);
1016 memset (labelvec, 0, ncases * sizeof (rtx));
1018 for (n = case_list; n; n = n->right)
1020 /* Compute the low and high bounds relative to the minimum
1021 value since that should fit in a HOST_WIDE_INT while the
1022 actual values may not. */
1023 HOST_WIDE_INT i_low
1024 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1025 n->low, minval));
1026 HOST_WIDE_INT i_high
1027 = tree_to_uhwi (fold_build2 (MINUS_EXPR, index_type,
1028 n->high, minval));
1029 HOST_WIDE_INT i;
1031 for (i = i_low; i <= i_high; i ++)
1032 labelvec[i]
1033 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1036 /* Fill in the gaps with the default. We may have gaps at
1037 the beginning if we tried to avoid the minval subtraction,
1038 so substitute some label even if the default label was
1039 deemed unreachable. */
1040 if (!default_label)
1041 default_label = fallback_label;
1042 for (i = 0; i < ncases; i++)
1043 if (labelvec[i] == 0)
1045 has_gaps = true;
1046 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1049 if (has_gaps)
1051 /* There is at least one entry in the jump table that jumps
1052 to default label. The default label can either be reached
1053 through the indirect jump or the direct conditional jump
1054 before that. Split the probability of reaching the
1055 default label among these two jumps. */
1056 new_default_prob = conditional_probability (default_prob/2,
1057 base);
1058 default_prob /= 2;
1059 base -= default_prob;
1061 else
1063 base -= default_prob;
1064 default_prob = 0;
1067 if (default_edge)
1068 default_edge->probability = default_prob;
1070 /* We have altered the probability of the default edge. So the probabilities
1071 of all other edges need to be adjusted so that it sums up to
1072 REG_BR_PROB_BASE. */
1073 if (base)
1075 edge e;
1076 edge_iterator ei;
1077 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
1078 e->probability = GCOV_COMPUTE_SCALE (e->probability, base);
1081 if (try_with_tablejump)
1083 bool ok = try_tablejump (index_type, index_expr, minval, range,
1084 table_label, default_label, new_default_prob);
1085 gcc_assert (ok);
1087 /* Output the table. */
1088 emit_label (table_label);
1090 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1091 emit_jump_table_data (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1092 gen_rtx_LABEL_REF (Pmode,
1093 table_label),
1094 gen_rtvec_v (ncases, labelvec),
1095 const0_rtx, const0_rtx));
1096 else
1097 emit_jump_table_data (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1098 gen_rtvec_v (ncases, labelvec)));
1100 /* Record no drop-through after the table. */
1101 emit_barrier ();
1104 /* Reset the aux field of all outgoing edges of basic block BB. */
1106 static inline void
1107 reset_out_edges_aux (basic_block bb)
1109 edge e;
1110 edge_iterator ei;
1111 FOR_EACH_EDGE (e, ei, bb->succs)
1112 e->aux = (void *)0;
1115 /* Compute the number of case labels that correspond to each outgoing edge of
1116 STMT. Record this information in the aux field of the edge. */
1118 static inline void
1119 compute_cases_per_edge (gswitch *stmt)
1121 basic_block bb = gimple_bb (stmt);
1122 reset_out_edges_aux (bb);
1123 int ncases = gimple_switch_num_labels (stmt);
1124 for (int i = ncases - 1; i >= 1; --i)
1126 tree elt = gimple_switch_label (stmt, i);
1127 tree lab = CASE_LABEL (elt);
1128 basic_block case_bb = label_to_block_fn (cfun, lab);
1129 edge case_edge = find_edge (bb, case_bb);
1130 case_edge->aux = (void *)((intptr_t)(case_edge->aux) + 1);
1134 /* Terminate a case (Pascal/Ada) or switch (C) statement
1135 in which ORIG_INDEX is the expression to be tested.
1136 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
1137 type as given in the source before any compiler conversions.
1138 Generate the code to test it and jump to the right place. */
1140 void
1141 expand_case (gswitch *stmt)
1143 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
1144 rtx_code_label *default_label = NULL;
1145 unsigned int count, uniq;
1146 int i;
1147 int ncases = gimple_switch_num_labels (stmt);
1148 tree index_expr = gimple_switch_index (stmt);
1149 tree index_type = TREE_TYPE (index_expr);
1150 tree elt;
1151 basic_block bb = gimple_bb (stmt);
1153 /* A list of case labels; it is first built as a list and it may then
1154 be rearranged into a nearly balanced binary tree. */
1155 struct case_node *case_list = 0;
1157 /* A pool for case nodes. */
1158 pool_allocator<case_node> case_node_pool ("struct case_node pool", 100);
1160 /* An ERROR_MARK occurs for various reasons including invalid data type.
1161 ??? Can this still happen, with GIMPLE and all? */
1162 if (index_type == error_mark_node)
1163 return;
1165 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
1166 expressions being INTEGER_CST. */
1167 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
1170 do_pending_stack_adjust ();
1172 /* Find the default case target label. */
1173 default_label = jump_target_rtx
1174 (CASE_LABEL (gimple_switch_default_label (stmt)));
1175 edge default_edge = EDGE_SUCC (bb, 0);
1176 int default_prob = default_edge->probability;
1178 /* Get upper and lower bounds of case values. */
1179 elt = gimple_switch_label (stmt, 1);
1180 minval = fold_convert (index_type, CASE_LOW (elt));
1181 elt = gimple_switch_label (stmt, ncases - 1);
1182 if (CASE_HIGH (elt))
1183 maxval = fold_convert (index_type, CASE_HIGH (elt));
1184 else
1185 maxval = fold_convert (index_type, CASE_LOW (elt));
1187 /* Compute span of values. */
1188 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
1190 /* Listify the labels queue and gather some numbers to decide
1191 how to expand this switch(). */
1192 uniq = 0;
1193 count = 0;
1194 hash_set<tree> seen_labels;
1195 compute_cases_per_edge (stmt);
1197 for (i = ncases - 1; i >= 1; --i)
1199 elt = gimple_switch_label (stmt, i);
1200 tree low = CASE_LOW (elt);
1201 gcc_assert (low);
1202 tree high = CASE_HIGH (elt);
1203 gcc_assert (! high || tree_int_cst_lt (low, high));
1204 tree lab = CASE_LABEL (elt);
1206 /* Count the elements.
1207 A range counts double, since it requires two compares. */
1208 count++;
1209 if (high)
1210 count++;
1212 /* If we have not seen this label yet, then increase the
1213 number of unique case node targets seen. */
1214 if (!seen_labels.add (lab))
1215 uniq++;
1217 /* The bounds on the case range, LOW and HIGH, have to be converted
1218 to case's index type TYPE. Note that the original type of the
1219 case index in the source code is usually "lost" during
1220 gimplification due to type promotion, but the case labels retain the
1221 original type. Make sure to drop overflow flags. */
1222 low = fold_convert (index_type, low);
1223 if (TREE_OVERFLOW (low))
1224 low = wide_int_to_tree (index_type, low);
1226 /* The canonical from of a case label in GIMPLE is that a simple case
1227 has an empty CASE_HIGH. For the casesi and tablejump expanders,
1228 the back ends want simple cases to have high == low. */
1229 if (! high)
1230 high = low;
1231 high = fold_convert (index_type, high);
1232 if (TREE_OVERFLOW (high))
1233 high = wide_int_to_tree (index_type, high);
1235 basic_block case_bb = label_to_block_fn (cfun, lab);
1236 edge case_edge = find_edge (bb, case_bb);
1237 case_list = add_case_node (
1238 case_list, low, high, lab,
1239 case_edge->probability / (intptr_t)(case_edge->aux),
1240 case_node_pool);
1242 reset_out_edges_aux (bb);
1244 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
1245 destination, such as one with a default case only.
1246 It also removes cases that are out of range for the switch
1247 type, so we should never get a zero here. */
1248 gcc_assert (count > 0);
1250 rtx_insn *before_case = get_last_insn ();
1252 /* Decide how to expand this switch.
1253 The two options at this point are a dispatch table (casesi or
1254 tablejump) or a decision tree. */
1256 if (expand_switch_as_decision_tree_p (range, uniq, count))
1257 emit_case_decision_tree (index_expr, index_type,
1258 case_list, default_label,
1259 default_prob);
1260 else
1261 emit_case_dispatch_table (index_expr, index_type,
1262 case_list, default_label,
1263 minval, maxval, range, bb);
1265 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1267 free_temp_slots ();
1270 /* Expand the dispatch to a short decrement chain if there are few cases
1271 to dispatch to. Likewise if neither casesi nor tablejump is available,
1272 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
1273 tablejump. The index mode is always the mode of integer_type_node.
1274 Trap if no case matches the index.
1276 DISPATCH_INDEX is the index expression to switch on. It should be a
1277 memory or register operand.
1279 DISPATCH_TABLE is a set of case labels. The set should be sorted in
1280 ascending order, be contiguous, starting with value 0, and contain only
1281 single-valued case labels. */
1283 void
1284 expand_sjlj_dispatch_table (rtx dispatch_index,
1285 vec<tree> dispatch_table)
1287 tree index_type = integer_type_node;
1288 machine_mode index_mode = TYPE_MODE (index_type);
1290 int ncases = dispatch_table.length ();
1292 do_pending_stack_adjust ();
1293 rtx_insn *before_case = get_last_insn ();
1295 /* Expand as a decrement-chain if there are 5 or fewer dispatch
1296 labels. This covers more than 98% of the cases in libjava,
1297 and seems to be a reasonable compromise between the "old way"
1298 of expanding as a decision tree or dispatch table vs. the "new
1299 way" with decrement chain or dispatch table. */
1300 if (dispatch_table.length () <= 5
1301 || (!HAVE_casesi && !HAVE_tablejump)
1302 || !flag_jump_tables)
1304 /* Expand the dispatch as a decrement chain:
1306 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
1310 if (index == 0) do_0; else index--;
1311 if (index == 0) do_1; else index--;
1313 if (index == 0) do_N; else index--;
1315 This is more efficient than a dispatch table on most machines.
1316 The last "index--" is redundant but the code is trivially dead
1317 and will be cleaned up by later passes. */
1318 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
1319 rtx zero = CONST0_RTX (index_mode);
1320 for (int i = 0; i < ncases; i++)
1322 tree elt = dispatch_table[i];
1323 rtx_code_label *lab = jump_target_rtx (CASE_LABEL (elt));
1324 do_jump_if_equal (index_mode, index, zero, lab, 0, -1);
1325 force_expand_binop (index_mode, sub_optab,
1326 index, CONST1_RTX (index_mode),
1327 index, 0, OPTAB_DIRECT);
1330 else
1332 /* Similar to expand_case, but much simpler. */
1333 struct case_node *case_list = 0;
1334 pool_allocator<case_node> case_node_pool ("struct sjlj_case pool",
1335 ncases);
1336 tree index_expr = make_tree (index_type, dispatch_index);
1337 tree minval = build_int_cst (index_type, 0);
1338 tree maxval = CASE_LOW (dispatch_table.last ());
1339 tree range = maxval;
1340 rtx_code_label *default_label = gen_label_rtx ();
1342 for (int i = ncases - 1; i >= 0; --i)
1344 tree elt = dispatch_table[i];
1345 tree low = CASE_LOW (elt);
1346 tree lab = CASE_LABEL (elt);
1347 case_list = add_case_node (case_list, low, low, lab, 0, case_node_pool);
1350 emit_case_dispatch_table (index_expr, index_type,
1351 case_list, default_label,
1352 minval, maxval, range,
1353 BLOCK_FOR_INSN (before_case));
1354 emit_label (default_label);
1357 /* Dispatching something not handled? Trap! */
1358 expand_builtin_trap ();
1360 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
1362 free_temp_slots ();
1366 /* Take an ordered list of case nodes
1367 and transform them into a near optimal binary tree,
1368 on the assumption that any target code selection value is as
1369 likely as any other.
1371 The transformation is performed by splitting the ordered
1372 list into two equal sections plus a pivot. The parts are
1373 then attached to the pivot as left and right branches. Each
1374 branch is then transformed recursively. */
1376 static void
1377 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
1379 case_node_ptr np;
1381 np = *head;
1382 if (np)
1384 int i = 0;
1385 int ranges = 0;
1386 case_node_ptr *npp;
1387 case_node_ptr left;
1389 /* Count the number of entries on branch. Also count the ranges. */
1391 while (np)
1393 if (!tree_int_cst_equal (np->low, np->high))
1394 ranges++;
1396 i++;
1397 np = np->right;
1400 if (i > 2)
1402 /* Split this list if it is long enough for that to help. */
1403 npp = head;
1404 left = *npp;
1406 /* If there are just three nodes, split at the middle one. */
1407 if (i == 3)
1408 npp = &(*npp)->right;
1409 else
1411 /* Find the place in the list that bisects the list's total cost,
1412 where ranges count as 2.
1413 Here I gets half the total cost. */
1414 i = (i + ranges + 1) / 2;
1415 while (1)
1417 /* Skip nodes while their cost does not reach that amount. */
1418 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
1419 i--;
1420 i--;
1421 if (i <= 0)
1422 break;
1423 npp = &(*npp)->right;
1426 *head = np = *npp;
1427 *npp = 0;
1428 np->parent = parent;
1429 np->left = left;
1431 /* Optimize each of the two split parts. */
1432 balance_case_nodes (&np->left, np);
1433 balance_case_nodes (&np->right, np);
1434 np->subtree_prob = np->prob;
1435 np->subtree_prob += np->left->subtree_prob;
1436 np->subtree_prob += np->right->subtree_prob;
1438 else
1440 /* Else leave this branch as one level,
1441 but fill in `parent' fields. */
1442 np = *head;
1443 np->parent = parent;
1444 np->subtree_prob = np->prob;
1445 for (; np->right; np = np->right)
1447 np->right->parent = np;
1448 (*head)->subtree_prob += np->right->subtree_prob;
1454 /* Search the parent sections of the case node tree
1455 to see if a test for the lower bound of NODE would be redundant.
1456 INDEX_TYPE is the type of the index expression.
1458 The instructions to generate the case decision tree are
1459 output in the same order as nodes are processed so it is
1460 known that if a parent node checks the range of the current
1461 node minus one that the current node is bounded at its lower
1462 span. Thus the test would be redundant. */
1464 static int
1465 node_has_low_bound (case_node_ptr node, tree index_type)
1467 tree low_minus_one;
1468 case_node_ptr pnode;
1470 /* If the lower bound of this node is the lowest value in the index type,
1471 we need not test it. */
1473 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
1474 return 1;
1476 /* If this node has a left branch, the value at the left must be less
1477 than that at this node, so it cannot be bounded at the bottom and
1478 we need not bother testing any further. */
1480 if (node->left)
1481 return 0;
1483 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
1484 node->low,
1485 build_int_cst (TREE_TYPE (node->low), 1));
1487 /* If the subtraction above overflowed, we can't verify anything.
1488 Otherwise, look for a parent that tests our value - 1. */
1490 if (! tree_int_cst_lt (low_minus_one, node->low))
1491 return 0;
1493 for (pnode = node->parent; pnode; pnode = pnode->parent)
1494 if (tree_int_cst_equal (low_minus_one, pnode->high))
1495 return 1;
1497 return 0;
1500 /* Search the parent sections of the case node tree
1501 to see if a test for the upper bound of NODE would be redundant.
1502 INDEX_TYPE is the type of the index expression.
1504 The instructions to generate the case decision tree are
1505 output in the same order as nodes are processed so it is
1506 known that if a parent node checks the range of the current
1507 node plus one that the current node is bounded at its upper
1508 span. Thus the test would be redundant. */
1510 static int
1511 node_has_high_bound (case_node_ptr node, tree index_type)
1513 tree high_plus_one;
1514 case_node_ptr pnode;
1516 /* If there is no upper bound, obviously no test is needed. */
1518 if (TYPE_MAX_VALUE (index_type) == NULL)
1519 return 1;
1521 /* If the upper bound of this node is the highest value in the type
1522 of the index expression, we need not test against it. */
1524 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
1525 return 1;
1527 /* If this node has a right branch, the value at the right must be greater
1528 than that at this node, so it cannot be bounded at the top and
1529 we need not bother testing any further. */
1531 if (node->right)
1532 return 0;
1534 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
1535 node->high,
1536 build_int_cst (TREE_TYPE (node->high), 1));
1538 /* If the addition above overflowed, we can't verify anything.
1539 Otherwise, look for a parent that tests our value + 1. */
1541 if (! tree_int_cst_lt (node->high, high_plus_one))
1542 return 0;
1544 for (pnode = node->parent; pnode; pnode = pnode->parent)
1545 if (tree_int_cst_equal (high_plus_one, pnode->low))
1546 return 1;
1548 return 0;
1551 /* Search the parent sections of the
1552 case node tree to see if both tests for the upper and lower
1553 bounds of NODE would be redundant. */
1555 static int
1556 node_is_bounded (case_node_ptr node, tree index_type)
1558 return (node_has_low_bound (node, index_type)
1559 && node_has_high_bound (node, index_type));
1563 /* Emit step-by-step code to select a case for the value of INDEX.
1564 The thus generated decision tree follows the form of the
1565 case-node binary tree NODE, whose nodes represent test conditions.
1566 INDEX_TYPE is the type of the index of the switch.
1568 Care is taken to prune redundant tests from the decision tree
1569 by detecting any boundary conditions already checked by
1570 emitted rtx. (See node_has_high_bound, node_has_low_bound
1571 and node_is_bounded, above.)
1573 Where the test conditions can be shown to be redundant we emit
1574 an unconditional jump to the target code. As a further
1575 optimization, the subordinates of a tree node are examined to
1576 check for bounded nodes. In this case conditional and/or
1577 unconditional jumps as a result of the boundary check for the
1578 current node are arranged to target the subordinates associated
1579 code for out of bound conditions on the current node.
1581 We can assume that when control reaches the code generated here,
1582 the index value has already been compared with the parents
1583 of this node, and determined to be on the same side of each parent
1584 as this node is. Thus, if this node tests for the value 51,
1585 and a parent tested for 52, we don't need to consider
1586 the possibility of a value greater than 51. If another parent
1587 tests for the value 50, then this node need not test anything. */
1589 static void
1590 emit_case_nodes (rtx index, case_node_ptr node, rtx_code_label *default_label,
1591 int default_prob, tree index_type)
1593 /* If INDEX has an unsigned type, we must make unsigned branches. */
1594 int unsignedp = TYPE_UNSIGNED (index_type);
1595 int probability;
1596 int prob = node->prob, subtree_prob = node->subtree_prob;
1597 machine_mode mode = GET_MODE (index);
1598 machine_mode imode = TYPE_MODE (index_type);
1600 /* Handle indices detected as constant during RTL expansion. */
1601 if (mode == VOIDmode)
1602 mode = imode;
1604 /* See if our parents have already tested everything for us.
1605 If they have, emit an unconditional jump for this node. */
1606 if (node_is_bounded (node, index_type))
1607 emit_jump (label_rtx (node->code_label));
1609 else if (tree_int_cst_equal (node->low, node->high))
1611 probability = conditional_probability (prob, subtree_prob + default_prob);
1612 /* Node is single valued. First see if the index expression matches
1613 this node and then check our children, if any. */
1614 do_jump_if_equal (mode, index,
1615 convert_modes (mode, imode,
1616 expand_normal (node->low),
1617 unsignedp),
1618 jump_target_rtx (node->code_label),
1619 unsignedp, probability);
1620 /* Since this case is taken at this point, reduce its weight from
1621 subtree_weight. */
1622 subtree_prob -= prob;
1623 if (node->right != 0 && node->left != 0)
1625 /* This node has children on both sides.
1626 Dispatch to one side or the other
1627 by comparing the index value with this node's value.
1628 If one subtree is bounded, check that one first,
1629 so we can avoid real branches in the tree. */
1631 if (node_is_bounded (node->right, index_type))
1633 probability = conditional_probability (
1634 node->right->prob,
1635 subtree_prob + default_prob);
1636 emit_cmp_and_jump_insns (index,
1637 convert_modes
1638 (mode, imode,
1639 expand_normal (node->high),
1640 unsignedp),
1641 GT, NULL_RTX, mode, unsignedp,
1642 label_rtx (node->right->code_label),
1643 probability);
1644 emit_case_nodes (index, node->left, default_label, default_prob,
1645 index_type);
1648 else if (node_is_bounded (node->left, index_type))
1650 probability = conditional_probability (
1651 node->left->prob,
1652 subtree_prob + default_prob);
1653 emit_cmp_and_jump_insns (index,
1654 convert_modes
1655 (mode, imode,
1656 expand_normal (node->high),
1657 unsignedp),
1658 LT, NULL_RTX, mode, unsignedp,
1659 label_rtx (node->left->code_label),
1660 probability);
1661 emit_case_nodes (index, node->right, default_label, default_prob,
1662 index_type);
1665 /* If both children are single-valued cases with no
1666 children, finish up all the work. This way, we can save
1667 one ordered comparison. */
1668 else if (tree_int_cst_equal (node->right->low, node->right->high)
1669 && node->right->left == 0
1670 && node->right->right == 0
1671 && tree_int_cst_equal (node->left->low, node->left->high)
1672 && node->left->left == 0
1673 && node->left->right == 0)
1675 /* Neither node is bounded. First distinguish the two sides;
1676 then emit the code for one side at a time. */
1678 /* See if the value matches what the right hand side
1679 wants. */
1680 probability = conditional_probability (
1681 node->right->prob,
1682 subtree_prob + default_prob);
1683 do_jump_if_equal (mode, index,
1684 convert_modes (mode, imode,
1685 expand_normal (node->right->low),
1686 unsignedp),
1687 jump_target_rtx (node->right->code_label),
1688 unsignedp, probability);
1690 /* See if the value matches what the left hand side
1691 wants. */
1692 probability = conditional_probability (
1693 node->left->prob,
1694 subtree_prob + default_prob);
1695 do_jump_if_equal (mode, index,
1696 convert_modes (mode, imode,
1697 expand_normal (node->left->low),
1698 unsignedp),
1699 jump_target_rtx (node->left->code_label),
1700 unsignedp, probability);
1703 else
1705 /* Neither node is bounded. First distinguish the two sides;
1706 then emit the code for one side at a time. */
1708 tree test_label
1709 = build_decl (curr_insn_location (),
1710 LABEL_DECL, NULL_TREE, void_type_node);
1712 /* The default label could be reached either through the right
1713 subtree or the left subtree. Divide the probability
1714 equally. */
1715 probability = conditional_probability (
1716 node->right->subtree_prob + default_prob/2,
1717 subtree_prob + default_prob);
1718 /* See if the value is on the right. */
1719 emit_cmp_and_jump_insns (index,
1720 convert_modes
1721 (mode, imode,
1722 expand_normal (node->high),
1723 unsignedp),
1724 GT, NULL_RTX, mode, unsignedp,
1725 label_rtx (test_label),
1726 probability);
1727 default_prob /= 2;
1729 /* Value must be on the left.
1730 Handle the left-hand subtree. */
1731 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1732 /* If left-hand subtree does nothing,
1733 go to default. */
1734 if (default_label)
1735 emit_jump (default_label);
1737 /* Code branches here for the right-hand subtree. */
1738 expand_label (test_label);
1739 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1743 else if (node->right != 0 && node->left == 0)
1745 /* Here we have a right child but no left so we issue a conditional
1746 branch to default and process the right child.
1748 Omit the conditional branch to default if the right child
1749 does not have any children and is single valued; it would
1750 cost too much space to save so little time. */
1752 if (node->right->right || node->right->left
1753 || !tree_int_cst_equal (node->right->low, node->right->high))
1755 if (!node_has_low_bound (node, index_type))
1757 probability = conditional_probability (
1758 default_prob/2,
1759 subtree_prob + default_prob);
1760 emit_cmp_and_jump_insns (index,
1761 convert_modes
1762 (mode, imode,
1763 expand_normal (node->high),
1764 unsignedp),
1765 LT, NULL_RTX, mode, unsignedp,
1766 default_label,
1767 probability);
1768 default_prob /= 2;
1771 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1773 else
1775 probability = conditional_probability (
1776 node->right->subtree_prob,
1777 subtree_prob + default_prob);
1778 /* We cannot process node->right normally
1779 since we haven't ruled out the numbers less than
1780 this node's value. So handle node->right explicitly. */
1781 do_jump_if_equal (mode, index,
1782 convert_modes
1783 (mode, imode,
1784 expand_normal (node->right->low),
1785 unsignedp),
1786 jump_target_rtx (node->right->code_label),
1787 unsignedp, probability);
1791 else if (node->right == 0 && node->left != 0)
1793 /* Just one subtree, on the left. */
1794 if (node->left->left || node->left->right
1795 || !tree_int_cst_equal (node->left->low, node->left->high))
1797 if (!node_has_high_bound (node, index_type))
1799 probability = conditional_probability (
1800 default_prob/2,
1801 subtree_prob + default_prob);
1802 emit_cmp_and_jump_insns (index,
1803 convert_modes
1804 (mode, imode,
1805 expand_normal (node->high),
1806 unsignedp),
1807 GT, NULL_RTX, mode, unsignedp,
1808 default_label,
1809 probability);
1810 default_prob /= 2;
1813 emit_case_nodes (index, node->left, default_label,
1814 default_prob, index_type);
1816 else
1818 probability = conditional_probability (
1819 node->left->subtree_prob,
1820 subtree_prob + default_prob);
1821 /* We cannot process node->left normally
1822 since we haven't ruled out the numbers less than
1823 this node's value. So handle node->left explicitly. */
1824 do_jump_if_equal (mode, index,
1825 convert_modes
1826 (mode, imode,
1827 expand_normal (node->left->low),
1828 unsignedp),
1829 jump_target_rtx (node->left->code_label),
1830 unsignedp, probability);
1834 else
1836 /* Node is a range. These cases are very similar to those for a single
1837 value, except that we do not start by testing whether this node
1838 is the one to branch to. */
1840 if (node->right != 0 && node->left != 0)
1842 /* Node has subtrees on both sides.
1843 If the right-hand subtree is bounded,
1844 test for it first, since we can go straight there.
1845 Otherwise, we need to make a branch in the control structure,
1846 then handle the two subtrees. */
1847 tree test_label = 0;
1849 if (node_is_bounded (node->right, index_type))
1851 /* Right hand node is fully bounded so we can eliminate any
1852 testing and branch directly to the target code. */
1853 probability = conditional_probability (
1854 node->right->subtree_prob,
1855 subtree_prob + default_prob);
1856 emit_cmp_and_jump_insns (index,
1857 convert_modes
1858 (mode, imode,
1859 expand_normal (node->high),
1860 unsignedp),
1861 GT, NULL_RTX, mode, unsignedp,
1862 label_rtx (node->right->code_label),
1863 probability);
1865 else
1867 /* Right hand node requires testing.
1868 Branch to a label where we will handle it later. */
1870 test_label = build_decl (curr_insn_location (),
1871 LABEL_DECL, NULL_TREE, void_type_node);
1872 probability = conditional_probability (
1873 node->right->subtree_prob + default_prob/2,
1874 subtree_prob + default_prob);
1875 emit_cmp_and_jump_insns (index,
1876 convert_modes
1877 (mode, imode,
1878 expand_normal (node->high),
1879 unsignedp),
1880 GT, NULL_RTX, mode, unsignedp,
1881 label_rtx (test_label),
1882 probability);
1883 default_prob /= 2;
1886 /* Value belongs to this node or to the left-hand subtree. */
1888 probability = conditional_probability (
1889 prob,
1890 subtree_prob + default_prob);
1891 emit_cmp_and_jump_insns (index,
1892 convert_modes
1893 (mode, imode,
1894 expand_normal (node->low),
1895 unsignedp),
1896 GE, NULL_RTX, mode, unsignedp,
1897 label_rtx (node->code_label),
1898 probability);
1900 /* Handle the left-hand subtree. */
1901 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1903 /* If right node had to be handled later, do that now. */
1905 if (test_label)
1907 /* If the left-hand subtree fell through,
1908 don't let it fall into the right-hand subtree. */
1909 if (default_label)
1910 emit_jump (default_label);
1912 expand_label (test_label);
1913 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1917 else if (node->right != 0 && node->left == 0)
1919 /* Deal with values to the left of this node,
1920 if they are possible. */
1921 if (!node_has_low_bound (node, index_type))
1923 probability = conditional_probability (
1924 default_prob/2,
1925 subtree_prob + default_prob);
1926 emit_cmp_and_jump_insns (index,
1927 convert_modes
1928 (mode, imode,
1929 expand_normal (node->low),
1930 unsignedp),
1931 LT, NULL_RTX, mode, unsignedp,
1932 default_label,
1933 probability);
1934 default_prob /= 2;
1937 /* Value belongs to this node or to the right-hand subtree. */
1939 probability = conditional_probability (
1940 prob,
1941 subtree_prob + default_prob);
1942 emit_cmp_and_jump_insns (index,
1943 convert_modes
1944 (mode, imode,
1945 expand_normal (node->high),
1946 unsignedp),
1947 LE, NULL_RTX, mode, unsignedp,
1948 label_rtx (node->code_label),
1949 probability);
1951 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
1954 else if (node->right == 0 && node->left != 0)
1956 /* Deal with values to the right of this node,
1957 if they are possible. */
1958 if (!node_has_high_bound (node, index_type))
1960 probability = conditional_probability (
1961 default_prob/2,
1962 subtree_prob + default_prob);
1963 emit_cmp_and_jump_insns (index,
1964 convert_modes
1965 (mode, imode,
1966 expand_normal (node->high),
1967 unsignedp),
1968 GT, NULL_RTX, mode, unsignedp,
1969 default_label,
1970 probability);
1971 default_prob /= 2;
1974 /* Value belongs to this node or to the left-hand subtree. */
1976 probability = conditional_probability (
1977 prob,
1978 subtree_prob + default_prob);
1979 emit_cmp_and_jump_insns (index,
1980 convert_modes
1981 (mode, imode,
1982 expand_normal (node->low),
1983 unsignedp),
1984 GE, NULL_RTX, mode, unsignedp,
1985 label_rtx (node->code_label),
1986 probability);
1988 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
1991 else
1993 /* Node has no children so we check low and high bounds to remove
1994 redundant tests. Only one of the bounds can exist,
1995 since otherwise this node is bounded--a case tested already. */
1996 int high_bound = node_has_high_bound (node, index_type);
1997 int low_bound = node_has_low_bound (node, index_type);
1999 if (!high_bound && low_bound)
2001 probability = conditional_probability (
2002 default_prob,
2003 subtree_prob + default_prob);
2004 emit_cmp_and_jump_insns (index,
2005 convert_modes
2006 (mode, imode,
2007 expand_normal (node->high),
2008 unsignedp),
2009 GT, NULL_RTX, mode, unsignedp,
2010 default_label,
2011 probability);
2014 else if (!low_bound && high_bound)
2016 probability = conditional_probability (
2017 default_prob,
2018 subtree_prob + default_prob);
2019 emit_cmp_and_jump_insns (index,
2020 convert_modes
2021 (mode, imode,
2022 expand_normal (node->low),
2023 unsignedp),
2024 LT, NULL_RTX, mode, unsignedp,
2025 default_label,
2026 probability);
2028 else if (!low_bound && !high_bound)
2030 /* Widen LOW and HIGH to the same width as INDEX. */
2031 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2032 tree low = build1 (CONVERT_EXPR, type, node->low);
2033 tree high = build1 (CONVERT_EXPR, type, node->high);
2034 rtx low_rtx, new_index, new_bound;
2036 /* Instead of doing two branches, emit one unsigned branch for
2037 (index-low) > (high-low). */
2038 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2039 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2040 NULL_RTX, unsignedp,
2041 OPTAB_WIDEN);
2042 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2043 high, low),
2044 NULL_RTX, mode, EXPAND_NORMAL);
2046 probability = conditional_probability (
2047 default_prob,
2048 subtree_prob + default_prob);
2049 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2050 mode, 1, default_label, probability);
2053 emit_jump (jump_target_rtx (node->code_label));