re PR c++/19476 (Missed null checking elimination with new)
[official-gcc.git] / gcc / stmt.c
blobc385a067e4b11cc7acf17430debd6e1ce939faee
1 /* Expands front end tree to back end RTL for GCC
2 Copyright (C) 1987-2013 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 "tm_p.h"
34 #include "flags.h"
35 #include "except.h"
36 #include "function.h"
37 #include "insn-config.h"
38 #include "expr.h"
39 #include "libfuncs.h"
40 #include "recog.h"
41 #include "machmode.h"
42 #include "diagnostic-core.h"
43 #include "output.h"
44 #include "ggc.h"
45 #include "langhooks.h"
46 #include "predict.h"
47 #include "optabs.h"
48 #include "target.h"
49 #include "gimple.h"
50 #include "regs.h"
51 #include "alloc-pool.h"
52 #include "pretty-print.h"
53 #include "pointer-set.h"
54 #include "params.h"
55 #include "dumpfile.h"
58 /* Functions and data structures for expanding case statements. */
60 /* Case label structure, used to hold info on labels within case
61 statements. We handle "range" labels; for a single-value label
62 as in C, the high and low limits are the same.
64 We start with a vector of case nodes sorted in ascending order, and
65 the default label as the last element in the vector. Before expanding
66 to RTL, we transform this vector into a list linked via the RIGHT
67 fields in the case_node struct. Nodes with higher case values are
68 later in the list.
70 Switch statements can be output in three forms. A branch table is
71 used if there are more than a few labels and the labels are dense
72 within the range between the smallest and largest case value. If a
73 branch table is used, no further manipulations are done with the case
74 node chain.
76 The alternative to the use of a branch table is to generate a series
77 of compare and jump insns. When that is done, we use the LEFT, RIGHT,
78 and PARENT fields to hold a binary tree. Initially the tree is
79 totally unbalanced, with everything on the right. We balance the tree
80 with nodes on the left having lower case values than the parent
81 and nodes on the right having higher values. We then output the tree
82 in order.
84 For very small, suitable switch statements, we can generate a series
85 of simple bit test and branches instead. */
87 struct case_node
89 struct case_node *left; /* Left son in binary tree */
90 struct case_node *right; /* Right son in binary tree; also node chain */
91 struct case_node *parent; /* Parent of node in binary tree */
92 tree low; /* Lowest index value for this label */
93 tree high; /* Highest index value for this label */
94 tree code_label; /* Label to jump to when node matches */
95 int prob; /* Probability of taking this case. */
96 /* Probability of reaching subtree rooted at this node */
97 int subtree_prob;
100 typedef struct case_node case_node;
101 typedef struct case_node *case_node_ptr;
103 extern basic_block label_to_block_fn (struct function *, tree);
105 static int n_occurrences (int, const char *);
106 static bool tree_conflicts_with_clobbers_p (tree, HARD_REG_SET *);
107 static bool check_operand_nalternatives (tree, tree);
108 static bool check_unique_operand_names (tree, tree, tree);
109 static char *resolve_operand_name_1 (char *, tree, tree, tree);
110 static void expand_null_return_1 (void);
111 static void expand_value_return (rtx);
112 static void balance_case_nodes (case_node_ptr *, case_node_ptr);
113 static int node_has_low_bound (case_node_ptr, tree);
114 static int node_has_high_bound (case_node_ptr, tree);
115 static int node_is_bounded (case_node_ptr, tree);
116 static void emit_case_nodes (rtx, case_node_ptr, rtx, int, tree);
118 /* Return the rtx-label that corresponds to a LABEL_DECL,
119 creating it if necessary. */
122 label_rtx (tree label)
124 gcc_assert (TREE_CODE (label) == LABEL_DECL);
126 if (!DECL_RTL_SET_P (label))
128 rtx r = gen_label_rtx ();
129 SET_DECL_RTL (label, r);
130 if (FORCED_LABEL (label) || DECL_NONLOCAL (label))
131 LABEL_PRESERVE_P (r) = 1;
134 return DECL_RTL (label);
137 /* As above, but also put it on the forced-reference list of the
138 function that contains it. */
140 force_label_rtx (tree label)
142 rtx ref = label_rtx (label);
143 tree function = decl_function_context (label);
145 gcc_assert (function);
147 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, ref, forced_labels);
148 return ref;
151 /* Add an unconditional jump to LABEL as the next sequential instruction. */
153 void
154 emit_jump (rtx label)
156 do_pending_stack_adjust ();
157 emit_jump_insn (gen_jump (label));
158 emit_barrier ();
161 /* Emit code to jump to the address
162 specified by the pointer expression EXP. */
164 void
165 expand_computed_goto (tree exp)
167 rtx x = expand_normal (exp);
169 x = convert_memory_address (Pmode, x);
171 do_pending_stack_adjust ();
172 emit_indirect_jump (x);
175 /* Handle goto statements and the labels that they can go to. */
177 /* Specify the location in the RTL code of a label LABEL,
178 which is a LABEL_DECL tree node.
180 This is used for the kind of label that the user can jump to with a
181 goto statement, and for alternatives of a switch or case statement.
182 RTL labels generated for loops and conditionals don't go through here;
183 they are generated directly at the RTL level, by other functions below.
185 Note that this has nothing to do with defining label *names*.
186 Languages vary in how they do that and what that even means. */
188 void
189 expand_label (tree label)
191 rtx label_r = label_rtx (label);
193 do_pending_stack_adjust ();
194 emit_label (label_r);
195 if (DECL_NAME (label))
196 LABEL_NAME (DECL_RTL (label)) = IDENTIFIER_POINTER (DECL_NAME (label));
198 if (DECL_NONLOCAL (label))
200 expand_builtin_setjmp_receiver (NULL);
201 nonlocal_goto_handler_labels
202 = gen_rtx_EXPR_LIST (VOIDmode, label_r,
203 nonlocal_goto_handler_labels);
206 if (FORCED_LABEL (label))
207 forced_labels = gen_rtx_EXPR_LIST (VOIDmode, label_r, forced_labels);
209 if (DECL_NONLOCAL (label) || FORCED_LABEL (label))
210 maybe_set_first_label_num (label_r);
213 /* Generate RTL code for a `goto' statement with target label LABEL.
214 LABEL should be a LABEL_DECL tree node that was or will later be
215 defined with `expand_label'. */
217 void
218 expand_goto (tree label)
220 #ifdef ENABLE_CHECKING
221 /* Check for a nonlocal goto to a containing function. Should have
222 gotten translated to __builtin_nonlocal_goto. */
223 tree context = decl_function_context (label);
224 gcc_assert (!context || context == current_function_decl);
225 #endif
227 emit_jump (label_rtx (label));
230 /* Return the number of times character C occurs in string S. */
231 static int
232 n_occurrences (int c, const char *s)
234 int n = 0;
235 while (*s)
236 n += (*s++ == c);
237 return n;
240 /* Generate RTL for an asm statement (explicit assembler code).
241 STRING is a STRING_CST node containing the assembler code text,
242 or an ADDR_EXPR containing a STRING_CST. VOL nonzero means the
243 insn is volatile; don't optimize it. */
245 static void
246 expand_asm_loc (tree string, int vol, location_t locus)
248 rtx body;
250 if (TREE_CODE (string) == ADDR_EXPR)
251 string = TREE_OPERAND (string, 0);
253 body = gen_rtx_ASM_INPUT_loc (VOIDmode,
254 ggc_strdup (TREE_STRING_POINTER (string)),
255 locus);
257 MEM_VOLATILE_P (body) = vol;
259 emit_insn (body);
262 /* Parse the output constraint pointed to by *CONSTRAINT_P. It is the
263 OPERAND_NUMth output operand, indexed from zero. There are NINPUTS
264 inputs and NOUTPUTS outputs to this extended-asm. Upon return,
265 *ALLOWS_MEM will be TRUE iff the constraint allows the use of a
266 memory operand. Similarly, *ALLOWS_REG will be TRUE iff the
267 constraint allows the use of a register operand. And, *IS_INOUT
268 will be true if the operand is read-write, i.e., if it is used as
269 an input as well as an output. If *CONSTRAINT_P is not in
270 canonical form, it will be made canonical. (Note that `+' will be
271 replaced with `=' as part of this process.)
273 Returns TRUE if all went well; FALSE if an error occurred. */
275 bool
276 parse_output_constraint (const char **constraint_p, int operand_num,
277 int ninputs, int noutputs, bool *allows_mem,
278 bool *allows_reg, bool *is_inout)
280 const char *constraint = *constraint_p;
281 const char *p;
283 /* Assume the constraint doesn't allow the use of either a register
284 or memory. */
285 *allows_mem = false;
286 *allows_reg = false;
288 /* Allow the `=' or `+' to not be at the beginning of the string,
289 since it wasn't explicitly documented that way, and there is a
290 large body of code that puts it last. Swap the character to
291 the front, so as not to uglify any place else. */
292 p = strchr (constraint, '=');
293 if (!p)
294 p = strchr (constraint, '+');
296 /* If the string doesn't contain an `=', issue an error
297 message. */
298 if (!p)
300 error ("output operand constraint lacks %<=%>");
301 return false;
304 /* If the constraint begins with `+', then the operand is both read
305 from and written to. */
306 *is_inout = (*p == '+');
308 /* Canonicalize the output constraint so that it begins with `='. */
309 if (p != constraint || *is_inout)
311 char *buf;
312 size_t c_len = strlen (constraint);
314 if (p != constraint)
315 warning (0, "output constraint %qc for operand %d "
316 "is not at the beginning",
317 *p, operand_num);
319 /* Make a copy of the constraint. */
320 buf = XALLOCAVEC (char, c_len + 1);
321 strcpy (buf, constraint);
322 /* Swap the first character and the `=' or `+'. */
323 buf[p - constraint] = buf[0];
324 /* Make sure the first character is an `='. (Until we do this,
325 it might be a `+'.) */
326 buf[0] = '=';
327 /* Replace the constraint with the canonicalized string. */
328 *constraint_p = ggc_alloc_string (buf, c_len);
329 constraint = *constraint_p;
332 /* Loop through the constraint string. */
333 for (p = constraint + 1; *p; p += CONSTRAINT_LEN (*p, p))
334 switch (*p)
336 case '+':
337 case '=':
338 error ("operand constraint contains incorrectly positioned "
339 "%<+%> or %<=%>");
340 return false;
342 case '%':
343 if (operand_num + 1 == ninputs + noutputs)
345 error ("%<%%%> constraint used with last operand");
346 return false;
348 break;
350 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
351 *allows_mem = true;
352 break;
354 case '?': case '!': case '*': case '&': case '#':
355 case 'E': case 'F': case 'G': case 'H':
356 case 's': case 'i': case 'n':
357 case 'I': case 'J': case 'K': case 'L': case 'M':
358 case 'N': case 'O': case 'P': case ',':
359 break;
361 case '0': case '1': case '2': case '3': case '4':
362 case '5': case '6': case '7': case '8': case '9':
363 case '[':
364 error ("matching constraint not valid in output operand");
365 return false;
367 case '<': case '>':
368 /* ??? Before flow, auto inc/dec insns are not supposed to exist,
369 excepting those that expand_call created. So match memory
370 and hope. */
371 *allows_mem = true;
372 break;
374 case 'g': case 'X':
375 *allows_reg = true;
376 *allows_mem = true;
377 break;
379 case 'p': case 'r':
380 *allows_reg = true;
381 break;
383 default:
384 if (!ISALPHA (*p))
385 break;
386 if (REG_CLASS_FROM_CONSTRAINT (*p, p) != NO_REGS)
387 *allows_reg = true;
388 #ifdef EXTRA_CONSTRAINT_STR
389 else if (EXTRA_ADDRESS_CONSTRAINT (*p, p))
390 *allows_reg = true;
391 else if (EXTRA_MEMORY_CONSTRAINT (*p, p))
392 *allows_mem = true;
393 else
395 /* Otherwise we can't assume anything about the nature of
396 the constraint except that it isn't purely registers.
397 Treat it like "g" and hope for the best. */
398 *allows_reg = true;
399 *allows_mem = true;
401 #endif
402 break;
405 return true;
408 /* Similar, but for input constraints. */
410 bool
411 parse_input_constraint (const char **constraint_p, int input_num,
412 int ninputs, int noutputs, int ninout,
413 const char * const * constraints,
414 bool *allows_mem, bool *allows_reg)
416 const char *constraint = *constraint_p;
417 const char *orig_constraint = constraint;
418 size_t c_len = strlen (constraint);
419 size_t j;
420 bool saw_match = false;
422 /* Assume the constraint doesn't allow the use of either
423 a register or memory. */
424 *allows_mem = false;
425 *allows_reg = false;
427 /* Make sure constraint has neither `=', `+', nor '&'. */
429 for (j = 0; j < c_len; j += CONSTRAINT_LEN (constraint[j], constraint+j))
430 switch (constraint[j])
432 case '+': case '=': case '&':
433 if (constraint == orig_constraint)
435 error ("input operand constraint contains %qc", constraint[j]);
436 return false;
438 break;
440 case '%':
441 if (constraint == orig_constraint
442 && input_num + 1 == ninputs - ninout)
444 error ("%<%%%> constraint used with last operand");
445 return false;
447 break;
449 case 'V': case TARGET_MEM_CONSTRAINT: case 'o':
450 *allows_mem = true;
451 break;
453 case '<': case '>':
454 case '?': case '!': case '*': case '#':
455 case 'E': case 'F': case 'G': case 'H':
456 case 's': case 'i': case 'n':
457 case 'I': case 'J': case 'K': case 'L': case 'M':
458 case 'N': case 'O': case 'P': case ',':
459 break;
461 /* Whether or not a numeric constraint allows a register is
462 decided by the matching constraint, and so there is no need
463 to do anything special with them. We must handle them in
464 the default case, so that we don't unnecessarily force
465 operands to memory. */
466 case '0': case '1': case '2': case '3': case '4':
467 case '5': case '6': case '7': case '8': case '9':
469 char *end;
470 unsigned long match;
472 saw_match = true;
474 match = strtoul (constraint + j, &end, 10);
475 if (match >= (unsigned long) noutputs)
477 error ("matching constraint references invalid operand number");
478 return false;
481 /* Try and find the real constraint for this dup. Only do this
482 if the matching constraint is the only alternative. */
483 if (*end == '\0'
484 && (j == 0 || (j == 1 && constraint[0] == '%')))
486 constraint = constraints[match];
487 *constraint_p = constraint;
488 c_len = strlen (constraint);
489 j = 0;
490 /* ??? At the end of the loop, we will skip the first part of
491 the matched constraint. This assumes not only that the
492 other constraint is an output constraint, but also that
493 the '=' or '+' come first. */
494 break;
496 else
497 j = end - constraint;
498 /* Anticipate increment at end of loop. */
499 j--;
501 /* Fall through. */
503 case 'p': case 'r':
504 *allows_reg = true;
505 break;
507 case 'g': case 'X':
508 *allows_reg = true;
509 *allows_mem = true;
510 break;
512 default:
513 if (! ISALPHA (constraint[j]))
515 error ("invalid punctuation %qc in constraint", constraint[j]);
516 return false;
518 if (REG_CLASS_FROM_CONSTRAINT (constraint[j], constraint + j)
519 != NO_REGS)
520 *allows_reg = true;
521 #ifdef EXTRA_CONSTRAINT_STR
522 else if (EXTRA_ADDRESS_CONSTRAINT (constraint[j], constraint + j))
523 *allows_reg = true;
524 else if (EXTRA_MEMORY_CONSTRAINT (constraint[j], constraint + j))
525 *allows_mem = true;
526 else
528 /* Otherwise we can't assume anything about the nature of
529 the constraint except that it isn't purely registers.
530 Treat it like "g" and hope for the best. */
531 *allows_reg = true;
532 *allows_mem = true;
534 #endif
535 break;
538 if (saw_match && !*allows_reg)
539 warning (0, "matching constraint does not allow a register");
541 return true;
544 /* Return DECL iff there's an overlap between *REGS and DECL, where DECL
545 can be an asm-declared register. Called via walk_tree. */
547 static tree
548 decl_overlaps_hard_reg_set_p (tree *declp, int *walk_subtrees ATTRIBUTE_UNUSED,
549 void *data)
551 tree decl = *declp;
552 const HARD_REG_SET *const regs = (const HARD_REG_SET *) data;
554 if (TREE_CODE (decl) == VAR_DECL)
556 if (DECL_HARD_REGISTER (decl)
557 && REG_P (DECL_RTL (decl))
558 && REGNO (DECL_RTL (decl)) < FIRST_PSEUDO_REGISTER)
560 rtx reg = DECL_RTL (decl);
562 if (overlaps_hard_reg_set_p (*regs, GET_MODE (reg), REGNO (reg)))
563 return decl;
565 walk_subtrees = 0;
567 else if (TYPE_P (decl) || TREE_CODE (decl) == PARM_DECL)
568 walk_subtrees = 0;
569 return NULL_TREE;
572 /* If there is an overlap between *REGS and DECL, return the first overlap
573 found. */
574 tree
575 tree_overlaps_hard_reg_set (tree decl, HARD_REG_SET *regs)
577 return walk_tree (&decl, decl_overlaps_hard_reg_set_p, regs, NULL);
580 /* Check for overlap between registers marked in CLOBBERED_REGS and
581 anything inappropriate in T. Emit error and return the register
582 variable definition for error, NULL_TREE for ok. */
584 static bool
585 tree_conflicts_with_clobbers_p (tree t, HARD_REG_SET *clobbered_regs)
587 /* Conflicts between asm-declared register variables and the clobber
588 list are not allowed. */
589 tree overlap = tree_overlaps_hard_reg_set (t, clobbered_regs);
591 if (overlap)
593 error ("asm-specifier for variable %qE conflicts with asm clobber list",
594 DECL_NAME (overlap));
596 /* Reset registerness to stop multiple errors emitted for a single
597 variable. */
598 DECL_REGISTER (overlap) = 0;
599 return true;
602 return false;
605 /* Generate RTL for an asm statement with arguments.
606 STRING is the instruction template.
607 OUTPUTS is a list of output arguments (lvalues); INPUTS a list of inputs.
608 Each output or input has an expression in the TREE_VALUE and
609 a tree list in TREE_PURPOSE which in turn contains a constraint
610 name in TREE_VALUE (or NULL_TREE) and a constraint string
611 in TREE_PURPOSE.
612 CLOBBERS is a list of STRING_CST nodes each naming a hard register
613 that is clobbered by this insn.
615 Not all kinds of lvalue that may appear in OUTPUTS can be stored directly.
616 Some elements of OUTPUTS may be replaced with trees representing temporary
617 values. The caller should copy those temporary values to the originally
618 specified lvalues.
620 VOL nonzero means the insn is volatile; don't optimize it. */
622 static void
623 expand_asm_operands (tree string, tree outputs, tree inputs,
624 tree clobbers, tree labels, int vol, location_t locus)
626 rtvec argvec, constraintvec, labelvec;
627 rtx body;
628 int ninputs = list_length (inputs);
629 int noutputs = list_length (outputs);
630 int nlabels = list_length (labels);
631 int ninout;
632 int nclobbers;
633 HARD_REG_SET clobbered_regs;
634 int clobber_conflict_found = 0;
635 tree tail;
636 tree t;
637 int i;
638 /* Vector of RTX's of evaluated output operands. */
639 rtx *output_rtx = XALLOCAVEC (rtx, noutputs);
640 int *inout_opnum = XALLOCAVEC (int, noutputs);
641 rtx *real_output_rtx = XALLOCAVEC (rtx, noutputs);
642 enum machine_mode *inout_mode = XALLOCAVEC (enum machine_mode, noutputs);
643 const char **constraints = XALLOCAVEC (const char *, noutputs + ninputs);
644 int old_generating_concat_p = generating_concat_p;
646 /* An ASM with no outputs needs to be treated as volatile, for now. */
647 if (noutputs == 0)
648 vol = 1;
650 if (! check_operand_nalternatives (outputs, inputs))
651 return;
653 string = resolve_asm_operand_names (string, outputs, inputs, labels);
655 /* Collect constraints. */
656 i = 0;
657 for (t = outputs; t ; t = TREE_CHAIN (t), i++)
658 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
659 for (t = inputs; t ; t = TREE_CHAIN (t), i++)
660 constraints[i] = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
662 /* Sometimes we wish to automatically clobber registers across an asm.
663 Case in point is when the i386 backend moved from cc0 to a hard reg --
664 maintaining source-level compatibility means automatically clobbering
665 the flags register. */
666 clobbers = targetm.md_asm_clobbers (outputs, inputs, clobbers);
668 /* Count the number of meaningful clobbered registers, ignoring what
669 we would ignore later. */
670 nclobbers = 0;
671 CLEAR_HARD_REG_SET (clobbered_regs);
672 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
674 const char *regname;
675 int nregs;
677 if (TREE_VALUE (tail) == error_mark_node)
678 return;
679 regname = TREE_STRING_POINTER (TREE_VALUE (tail));
681 i = decode_reg_name_and_count (regname, &nregs);
682 if (i == -4)
683 ++nclobbers;
684 else if (i == -2)
685 error ("unknown register name %qs in %<asm%>", regname);
687 /* Mark clobbered registers. */
688 if (i >= 0)
690 int reg;
692 for (reg = i; reg < i + nregs; reg++)
694 ++nclobbers;
696 /* Clobbering the PIC register is an error. */
697 if (reg == (int) PIC_OFFSET_TABLE_REGNUM)
699 error ("PIC register clobbered by %qs in %<asm%>", regname);
700 return;
703 SET_HARD_REG_BIT (clobbered_regs, reg);
708 /* First pass over inputs and outputs checks validity and sets
709 mark_addressable if needed. */
711 ninout = 0;
712 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
714 tree val = TREE_VALUE (tail);
715 tree type = TREE_TYPE (val);
716 const char *constraint;
717 bool is_inout;
718 bool allows_reg;
719 bool allows_mem;
721 /* If there's an erroneous arg, emit no insn. */
722 if (type == error_mark_node)
723 return;
725 /* Try to parse the output constraint. If that fails, there's
726 no point in going further. */
727 constraint = constraints[i];
728 if (!parse_output_constraint (&constraint, i, ninputs, noutputs,
729 &allows_mem, &allows_reg, &is_inout))
730 return;
732 if (! allows_reg
733 && (allows_mem
734 || is_inout
735 || (DECL_P (val)
736 && REG_P (DECL_RTL (val))
737 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type))))
738 mark_addressable (val);
740 if (is_inout)
741 ninout++;
744 ninputs += ninout;
745 if (ninputs + noutputs > MAX_RECOG_OPERANDS)
747 error ("more than %d operands in %<asm%>", MAX_RECOG_OPERANDS);
748 return;
751 for (i = 0, tail = inputs; tail; i++, tail = TREE_CHAIN (tail))
753 bool allows_reg, allows_mem;
754 const char *constraint;
756 /* If there's an erroneous arg, emit no insn, because the ASM_INPUT
757 would get VOIDmode and that could cause a crash in reload. */
758 if (TREE_TYPE (TREE_VALUE (tail)) == error_mark_node)
759 return;
761 constraint = constraints[i + noutputs];
762 if (! parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
763 constraints, &allows_mem, &allows_reg))
764 return;
766 if (! allows_reg && allows_mem)
767 mark_addressable (TREE_VALUE (tail));
770 /* Second pass evaluates arguments. */
772 /* Make sure stack is consistent for asm goto. */
773 if (nlabels > 0)
774 do_pending_stack_adjust ();
776 ninout = 0;
777 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
779 tree val = TREE_VALUE (tail);
780 tree type = TREE_TYPE (val);
781 bool is_inout;
782 bool allows_reg;
783 bool allows_mem;
784 rtx op;
785 bool ok;
787 ok = parse_output_constraint (&constraints[i], i, ninputs,
788 noutputs, &allows_mem, &allows_reg,
789 &is_inout);
790 gcc_assert (ok);
792 /* If an output operand is not a decl or indirect ref and our constraint
793 allows a register, make a temporary to act as an intermediate.
794 Make the asm insn write into that, then our caller will copy it to
795 the real output operand. Likewise for promoted variables. */
797 generating_concat_p = 0;
799 real_output_rtx[i] = NULL_RTX;
800 if ((TREE_CODE (val) == INDIRECT_REF
801 && allows_mem)
802 || (DECL_P (val)
803 && (allows_mem || REG_P (DECL_RTL (val)))
804 && ! (REG_P (DECL_RTL (val))
805 && GET_MODE (DECL_RTL (val)) != TYPE_MODE (type)))
806 || ! allows_reg
807 || is_inout)
809 op = expand_expr (val, NULL_RTX, VOIDmode,
810 !allows_reg ? EXPAND_MEMORY : EXPAND_WRITE);
811 if (MEM_P (op))
812 op = validize_mem (op);
814 if (! allows_reg && !MEM_P (op))
815 error ("output number %d not directly addressable", i);
816 if ((! allows_mem && MEM_P (op))
817 || GET_CODE (op) == CONCAT)
819 real_output_rtx[i] = op;
820 op = gen_reg_rtx (GET_MODE (op));
821 if (is_inout)
822 emit_move_insn (op, real_output_rtx[i]);
825 else
827 op = assign_temp (type, 0, 1);
828 op = validize_mem (op);
829 if (!MEM_P (op) && TREE_CODE (TREE_VALUE (tail)) == SSA_NAME)
830 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (TREE_VALUE (tail)), op);
831 TREE_VALUE (tail) = make_tree (type, op);
833 output_rtx[i] = op;
835 generating_concat_p = old_generating_concat_p;
837 if (is_inout)
839 inout_mode[ninout] = TYPE_MODE (type);
840 inout_opnum[ninout++] = i;
843 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
844 clobber_conflict_found = 1;
847 /* Make vectors for the expression-rtx, constraint strings,
848 and named operands. */
850 argvec = rtvec_alloc (ninputs);
851 constraintvec = rtvec_alloc (ninputs);
852 labelvec = rtvec_alloc (nlabels);
854 body = gen_rtx_ASM_OPERANDS ((noutputs == 0 ? VOIDmode
855 : GET_MODE (output_rtx[0])),
856 ggc_strdup (TREE_STRING_POINTER (string)),
857 empty_string, 0, argvec, constraintvec,
858 labelvec, locus);
860 MEM_VOLATILE_P (body) = vol;
862 /* Eval the inputs and put them into ARGVEC.
863 Put their constraints into ASM_INPUTs and store in CONSTRAINTS. */
865 for (i = 0, tail = inputs; tail; tail = TREE_CHAIN (tail), ++i)
867 bool allows_reg, allows_mem;
868 const char *constraint;
869 tree val, type;
870 rtx op;
871 bool ok;
873 constraint = constraints[i + noutputs];
874 ok = parse_input_constraint (&constraint, i, ninputs, noutputs, ninout,
875 constraints, &allows_mem, &allows_reg);
876 gcc_assert (ok);
878 generating_concat_p = 0;
880 val = TREE_VALUE (tail);
881 type = TREE_TYPE (val);
882 /* EXPAND_INITIALIZER will not generate code for valid initializer
883 constants, but will still generate code for other types of operand.
884 This is the behavior we want for constant constraints. */
885 op = expand_expr (val, NULL_RTX, VOIDmode,
886 allows_reg ? EXPAND_NORMAL
887 : allows_mem ? EXPAND_MEMORY
888 : EXPAND_INITIALIZER);
890 /* Never pass a CONCAT to an ASM. */
891 if (GET_CODE (op) == CONCAT)
892 op = force_reg (GET_MODE (op), op);
893 else if (MEM_P (op))
894 op = validize_mem (op);
896 if (asm_operand_ok (op, constraint, NULL) <= 0)
898 if (allows_reg && TYPE_MODE (type) != BLKmode)
899 op = force_reg (TYPE_MODE (type), op);
900 else if (!allows_mem)
901 warning (0, "asm operand %d probably doesn%'t match constraints",
902 i + noutputs);
903 else if (MEM_P (op))
905 /* We won't recognize either volatile memory or memory
906 with a queued address as available a memory_operand
907 at this point. Ignore it: clearly this *is* a memory. */
909 else
910 gcc_unreachable ();
913 generating_concat_p = old_generating_concat_p;
914 ASM_OPERANDS_INPUT (body, i) = op;
916 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, i)
917 = gen_rtx_ASM_INPUT (TYPE_MODE (type),
918 ggc_strdup (constraints[i + noutputs]));
920 if (tree_conflicts_with_clobbers_p (val, &clobbered_regs))
921 clobber_conflict_found = 1;
924 /* Protect all the operands from the queue now that they have all been
925 evaluated. */
927 generating_concat_p = 0;
929 /* For in-out operands, copy output rtx to input rtx. */
930 for (i = 0; i < ninout; i++)
932 int j = inout_opnum[i];
933 char buffer[16];
935 ASM_OPERANDS_INPUT (body, ninputs - ninout + i)
936 = output_rtx[j];
938 sprintf (buffer, "%d", j);
939 ASM_OPERANDS_INPUT_CONSTRAINT_EXP (body, ninputs - ninout + i)
940 = gen_rtx_ASM_INPUT (inout_mode[i], ggc_strdup (buffer));
943 /* Copy labels to the vector. */
944 for (i = 0, tail = labels; i < nlabels; ++i, tail = TREE_CHAIN (tail))
945 ASM_OPERANDS_LABEL (body, i)
946 = gen_rtx_LABEL_REF (Pmode, label_rtx (TREE_VALUE (tail)));
948 generating_concat_p = old_generating_concat_p;
950 /* Now, for each output, construct an rtx
951 (set OUTPUT (asm_operands INSN OUTPUTCONSTRAINT OUTPUTNUMBER
952 ARGVEC CONSTRAINTS OPNAMES))
953 If there is more than one, put them inside a PARALLEL. */
955 if (nlabels > 0 && nclobbers == 0)
957 gcc_assert (noutputs == 0);
958 emit_jump_insn (body);
960 else if (noutputs == 0 && nclobbers == 0)
962 /* No output operands: put in a raw ASM_OPERANDS rtx. */
963 emit_insn (body);
965 else if (noutputs == 1 && nclobbers == 0)
967 ASM_OPERANDS_OUTPUT_CONSTRAINT (body) = ggc_strdup (constraints[0]);
968 emit_insn (gen_rtx_SET (VOIDmode, output_rtx[0], body));
970 else
972 rtx obody = body;
973 int num = noutputs;
975 if (num == 0)
976 num = 1;
978 body = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num + nclobbers));
980 /* For each output operand, store a SET. */
981 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
983 XVECEXP (body, 0, i)
984 = gen_rtx_SET (VOIDmode,
985 output_rtx[i],
986 gen_rtx_ASM_OPERANDS
987 (GET_MODE (output_rtx[i]),
988 ggc_strdup (TREE_STRING_POINTER (string)),
989 ggc_strdup (constraints[i]),
990 i, argvec, constraintvec, labelvec, locus));
992 MEM_VOLATILE_P (SET_SRC (XVECEXP (body, 0, i))) = vol;
995 /* If there are no outputs (but there are some clobbers)
996 store the bare ASM_OPERANDS into the PARALLEL. */
998 if (i == 0)
999 XVECEXP (body, 0, i++) = obody;
1001 /* Store (clobber REG) for each clobbered register specified. */
1003 for (tail = clobbers; tail; tail = TREE_CHAIN (tail))
1005 const char *regname = TREE_STRING_POINTER (TREE_VALUE (tail));
1006 int reg, nregs;
1007 int j = decode_reg_name_and_count (regname, &nregs);
1008 rtx clobbered_reg;
1010 if (j < 0)
1012 if (j == -3) /* `cc', which is not a register */
1013 continue;
1015 if (j == -4) /* `memory', don't cache memory across asm */
1017 XVECEXP (body, 0, i++)
1018 = gen_rtx_CLOBBER (VOIDmode,
1019 gen_rtx_MEM
1020 (BLKmode,
1021 gen_rtx_SCRATCH (VOIDmode)));
1022 continue;
1025 /* Ignore unknown register, error already signaled. */
1026 continue;
1029 for (reg = j; reg < j + nregs; reg++)
1031 /* Use QImode since that's guaranteed to clobber just
1032 * one reg. */
1033 clobbered_reg = gen_rtx_REG (QImode, reg);
1035 /* Do sanity check for overlap between clobbers and
1036 respectively input and outputs that hasn't been
1037 handled. Such overlap should have been detected and
1038 reported above. */
1039 if (!clobber_conflict_found)
1041 int opno;
1043 /* We test the old body (obody) contents to avoid
1044 tripping over the under-construction body. */
1045 for (opno = 0; opno < noutputs; opno++)
1046 if (reg_overlap_mentioned_p (clobbered_reg,
1047 output_rtx[opno]))
1048 internal_error
1049 ("asm clobber conflict with output operand");
1051 for (opno = 0; opno < ninputs - ninout; opno++)
1052 if (reg_overlap_mentioned_p (clobbered_reg,
1053 ASM_OPERANDS_INPUT (obody,
1054 opno)))
1055 internal_error
1056 ("asm clobber conflict with input operand");
1059 XVECEXP (body, 0, i++)
1060 = gen_rtx_CLOBBER (VOIDmode, clobbered_reg);
1064 if (nlabels > 0)
1065 emit_jump_insn (body);
1066 else
1067 emit_insn (body);
1070 /* For any outputs that needed reloading into registers, spill them
1071 back to where they belong. */
1072 for (i = 0; i < noutputs; ++i)
1073 if (real_output_rtx[i])
1074 emit_move_insn (real_output_rtx[i], output_rtx[i]);
1076 crtl->has_asm_statement = 1;
1077 free_temp_slots ();
1080 void
1081 expand_asm_stmt (gimple stmt)
1083 int noutputs;
1084 tree outputs, tail, t;
1085 tree *o;
1086 size_t i, n;
1087 const char *s;
1088 tree str, out, in, cl, labels;
1089 location_t locus = gimple_location (stmt);
1091 /* Meh... convert the gimple asm operands into real tree lists.
1092 Eventually we should make all routines work on the vectors instead
1093 of relying on TREE_CHAIN. */
1094 out = NULL_TREE;
1095 n = gimple_asm_noutputs (stmt);
1096 if (n > 0)
1098 t = out = gimple_asm_output_op (stmt, 0);
1099 for (i = 1; i < n; i++)
1100 t = TREE_CHAIN (t) = gimple_asm_output_op (stmt, i);
1103 in = NULL_TREE;
1104 n = gimple_asm_ninputs (stmt);
1105 if (n > 0)
1107 t = in = gimple_asm_input_op (stmt, 0);
1108 for (i = 1; i < n; i++)
1109 t = TREE_CHAIN (t) = gimple_asm_input_op (stmt, i);
1112 cl = NULL_TREE;
1113 n = gimple_asm_nclobbers (stmt);
1114 if (n > 0)
1116 t = cl = gimple_asm_clobber_op (stmt, 0);
1117 for (i = 1; i < n; i++)
1118 t = TREE_CHAIN (t) = gimple_asm_clobber_op (stmt, i);
1121 labels = NULL_TREE;
1122 n = gimple_asm_nlabels (stmt);
1123 if (n > 0)
1125 t = labels = gimple_asm_label_op (stmt, 0);
1126 for (i = 1; i < n; i++)
1127 t = TREE_CHAIN (t) = gimple_asm_label_op (stmt, i);
1130 s = gimple_asm_string (stmt);
1131 str = build_string (strlen (s), s);
1133 if (gimple_asm_input_p (stmt))
1135 expand_asm_loc (str, gimple_asm_volatile_p (stmt), locus);
1136 return;
1139 outputs = out;
1140 noutputs = gimple_asm_noutputs (stmt);
1141 /* o[I] is the place that output number I should be written. */
1142 o = (tree *) alloca (noutputs * sizeof (tree));
1144 /* Record the contents of OUTPUTS before it is modified. */
1145 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1146 o[i] = TREE_VALUE (tail);
1148 /* Generate the ASM_OPERANDS insn; store into the TREE_VALUEs of
1149 OUTPUTS some trees for where the values were actually stored. */
1150 expand_asm_operands (str, outputs, in, cl, labels,
1151 gimple_asm_volatile_p (stmt), locus);
1153 /* Copy all the intermediate outputs into the specified outputs. */
1154 for (i = 0, tail = outputs; tail; tail = TREE_CHAIN (tail), i++)
1156 if (o[i] != TREE_VALUE (tail))
1158 expand_assignment (o[i], TREE_VALUE (tail), false);
1159 free_temp_slots ();
1161 /* Restore the original value so that it's correct the next
1162 time we expand this function. */
1163 TREE_VALUE (tail) = o[i];
1168 /* A subroutine of expand_asm_operands. Check that all operands have
1169 the same number of alternatives. Return true if so. */
1171 static bool
1172 check_operand_nalternatives (tree outputs, tree inputs)
1174 if (outputs || inputs)
1176 tree tmp = TREE_PURPOSE (outputs ? outputs : inputs);
1177 int nalternatives
1178 = n_occurrences (',', TREE_STRING_POINTER (TREE_VALUE (tmp)));
1179 tree next = inputs;
1181 if (nalternatives + 1 > MAX_RECOG_ALTERNATIVES)
1183 error ("too many alternatives in %<asm%>");
1184 return false;
1187 tmp = outputs;
1188 while (tmp)
1190 const char *constraint
1191 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tmp)));
1193 if (n_occurrences (',', constraint) != nalternatives)
1195 error ("operand constraints for %<asm%> differ "
1196 "in number of alternatives");
1197 return false;
1200 if (TREE_CHAIN (tmp))
1201 tmp = TREE_CHAIN (tmp);
1202 else
1203 tmp = next, next = 0;
1207 return true;
1210 /* A subroutine of expand_asm_operands. Check that all operand names
1211 are unique. Return true if so. We rely on the fact that these names
1212 are identifiers, and so have been canonicalized by get_identifier,
1213 so all we need are pointer comparisons. */
1215 static bool
1216 check_unique_operand_names (tree outputs, tree inputs, tree labels)
1218 tree i, j, i_name = NULL_TREE;
1220 for (i = outputs; i ; i = TREE_CHAIN (i))
1222 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1223 if (! i_name)
1224 continue;
1226 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1227 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1228 goto failure;
1231 for (i = inputs; i ; i = TREE_CHAIN (i))
1233 i_name = TREE_PURPOSE (TREE_PURPOSE (i));
1234 if (! i_name)
1235 continue;
1237 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1238 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1239 goto failure;
1240 for (j = outputs; j ; j = TREE_CHAIN (j))
1241 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1242 goto failure;
1245 for (i = labels; i ; i = TREE_CHAIN (i))
1247 i_name = TREE_PURPOSE (i);
1248 if (! i_name)
1249 continue;
1251 for (j = TREE_CHAIN (i); j ; j = TREE_CHAIN (j))
1252 if (simple_cst_equal (i_name, TREE_PURPOSE (j)))
1253 goto failure;
1254 for (j = inputs; j ; j = TREE_CHAIN (j))
1255 if (simple_cst_equal (i_name, TREE_PURPOSE (TREE_PURPOSE (j))))
1256 goto failure;
1259 return true;
1261 failure:
1262 error ("duplicate asm operand name %qs", TREE_STRING_POINTER (i_name));
1263 return false;
1266 /* A subroutine of expand_asm_operands. Resolve the names of the operands
1267 in *POUTPUTS and *PINPUTS to numbers, and replace the name expansions in
1268 STRING and in the constraints to those numbers. */
1270 tree
1271 resolve_asm_operand_names (tree string, tree outputs, tree inputs, tree labels)
1273 char *buffer;
1274 char *p;
1275 const char *c;
1276 tree t;
1278 check_unique_operand_names (outputs, inputs, labels);
1280 /* Substitute [<name>] in input constraint strings. There should be no
1281 named operands in output constraints. */
1282 for (t = inputs; t ; t = TREE_CHAIN (t))
1284 c = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1285 if (strchr (c, '[') != NULL)
1287 p = buffer = xstrdup (c);
1288 while ((p = strchr (p, '[')) != NULL)
1289 p = resolve_operand_name_1 (p, outputs, inputs, NULL);
1290 TREE_VALUE (TREE_PURPOSE (t))
1291 = build_string (strlen (buffer), buffer);
1292 free (buffer);
1296 /* Now check for any needed substitutions in the template. */
1297 c = TREE_STRING_POINTER (string);
1298 while ((c = strchr (c, '%')) != NULL)
1300 if (c[1] == '[')
1301 break;
1302 else if (ISALPHA (c[1]) && c[2] == '[')
1303 break;
1304 else
1306 c += 1 + (c[1] == '%');
1307 continue;
1311 if (c)
1313 /* OK, we need to make a copy so we can perform the substitutions.
1314 Assume that we will not need extra space--we get to remove '['
1315 and ']', which means we cannot have a problem until we have more
1316 than 999 operands. */
1317 buffer = xstrdup (TREE_STRING_POINTER (string));
1318 p = buffer + (c - TREE_STRING_POINTER (string));
1320 while ((p = strchr (p, '%')) != NULL)
1322 if (p[1] == '[')
1323 p += 1;
1324 else if (ISALPHA (p[1]) && p[2] == '[')
1325 p += 2;
1326 else
1328 p += 1 + (p[1] == '%');
1329 continue;
1332 p = resolve_operand_name_1 (p, outputs, inputs, labels);
1335 string = build_string (strlen (buffer), buffer);
1336 free (buffer);
1339 return string;
1342 /* A subroutine of resolve_operand_names. P points to the '[' for a
1343 potential named operand of the form [<name>]. In place, replace
1344 the name and brackets with a number. Return a pointer to the
1345 balance of the string after substitution. */
1347 static char *
1348 resolve_operand_name_1 (char *p, tree outputs, tree inputs, tree labels)
1350 char *q;
1351 int op;
1352 tree t;
1354 /* Collect the operand name. */
1355 q = strchr (++p, ']');
1356 if (!q)
1358 error ("missing close brace for named operand");
1359 return strchr (p, '\0');
1361 *q = '\0';
1363 /* Resolve the name to a number. */
1364 for (op = 0, t = outputs; t ; t = TREE_CHAIN (t), op++)
1366 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1367 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1368 goto found;
1370 for (t = inputs; t ; t = TREE_CHAIN (t), op++)
1372 tree name = TREE_PURPOSE (TREE_PURPOSE (t));
1373 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1374 goto found;
1376 for (t = labels; t ; t = TREE_CHAIN (t), op++)
1378 tree name = TREE_PURPOSE (t);
1379 if (name && strcmp (TREE_STRING_POINTER (name), p) == 0)
1380 goto found;
1383 error ("undefined named operand %qs", identifier_to_locale (p));
1384 op = 0;
1386 found:
1387 /* Replace the name with the number. Unfortunately, not all libraries
1388 get the return value of sprintf correct, so search for the end of the
1389 generated string by hand. */
1390 sprintf (--p, "%d", op);
1391 p = strchr (p, '\0');
1393 /* Verify the no extra buffer space assumption. */
1394 gcc_assert (p <= q);
1396 /* Shift the rest of the buffer down to fill the gap. */
1397 memmove (p, q + 1, strlen (q + 1) + 1);
1399 return p;
1402 /* Generate RTL to return from the current function, with no value.
1403 (That is, we do not do anything about returning any value.) */
1405 void
1406 expand_null_return (void)
1408 /* If this function was declared to return a value, but we
1409 didn't, clobber the return registers so that they are not
1410 propagated live to the rest of the function. */
1411 clobber_return_register ();
1413 expand_null_return_1 ();
1416 /* Generate RTL to return directly from the current function.
1417 (That is, we bypass any return value.) */
1419 void
1420 expand_naked_return (void)
1422 rtx end_label;
1424 clear_pending_stack_adjust ();
1425 do_pending_stack_adjust ();
1427 end_label = naked_return_label;
1428 if (end_label == 0)
1429 end_label = naked_return_label = gen_label_rtx ();
1431 emit_jump (end_label);
1434 /* Generate RTL to return from the current function, with value VAL. */
1436 static void
1437 expand_value_return (rtx val)
1439 /* Copy the value to the return location unless it's already there. */
1441 tree decl = DECL_RESULT (current_function_decl);
1442 rtx return_reg = DECL_RTL (decl);
1443 if (return_reg != val)
1445 tree funtype = TREE_TYPE (current_function_decl);
1446 tree type = TREE_TYPE (decl);
1447 int unsignedp = TYPE_UNSIGNED (type);
1448 enum machine_mode old_mode = DECL_MODE (decl);
1449 enum machine_mode mode;
1450 if (DECL_BY_REFERENCE (decl))
1451 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 2);
1452 else
1453 mode = promote_function_mode (type, old_mode, &unsignedp, funtype, 1);
1455 if (mode != old_mode)
1456 val = convert_modes (mode, old_mode, val, unsignedp);
1458 if (GET_CODE (return_reg) == PARALLEL)
1459 emit_group_load (return_reg, val, type, int_size_in_bytes (type));
1460 else
1461 emit_move_insn (return_reg, val);
1464 expand_null_return_1 ();
1467 /* Output a return with no value. */
1469 static void
1470 expand_null_return_1 (void)
1472 clear_pending_stack_adjust ();
1473 do_pending_stack_adjust ();
1474 emit_jump (return_label);
1477 /* Generate RTL to evaluate the expression RETVAL and return it
1478 from the current function. */
1480 void
1481 expand_return (tree retval)
1483 rtx result_rtl;
1484 rtx val = 0;
1485 tree retval_rhs;
1487 /* If function wants no value, give it none. */
1488 if (TREE_CODE (TREE_TYPE (TREE_TYPE (current_function_decl))) == VOID_TYPE)
1490 expand_normal (retval);
1491 expand_null_return ();
1492 return;
1495 if (retval == error_mark_node)
1497 /* Treat this like a return of no value from a function that
1498 returns a value. */
1499 expand_null_return ();
1500 return;
1502 else if ((TREE_CODE (retval) == MODIFY_EXPR
1503 || TREE_CODE (retval) == INIT_EXPR)
1504 && TREE_CODE (TREE_OPERAND (retval, 0)) == RESULT_DECL)
1505 retval_rhs = TREE_OPERAND (retval, 1);
1506 else
1507 retval_rhs = retval;
1509 result_rtl = DECL_RTL (DECL_RESULT (current_function_decl));
1511 /* If we are returning the RESULT_DECL, then the value has already
1512 been stored into it, so we don't have to do anything special. */
1513 if (TREE_CODE (retval_rhs) == RESULT_DECL)
1514 expand_value_return (result_rtl);
1516 /* If the result is an aggregate that is being returned in one (or more)
1517 registers, load the registers here. */
1519 else if (retval_rhs != 0
1520 && TYPE_MODE (TREE_TYPE (retval_rhs)) == BLKmode
1521 && REG_P (result_rtl))
1523 val = copy_blkmode_to_reg (GET_MODE (result_rtl), retval_rhs);
1524 if (val)
1526 /* Use the mode of the result value on the return register. */
1527 PUT_MODE (result_rtl, GET_MODE (val));
1528 expand_value_return (val);
1530 else
1531 expand_null_return ();
1533 else if (retval_rhs != 0
1534 && !VOID_TYPE_P (TREE_TYPE (retval_rhs))
1535 && (REG_P (result_rtl)
1536 || (GET_CODE (result_rtl) == PARALLEL)))
1538 /* Calculate the return value into a temporary (usually a pseudo
1539 reg). */
1540 tree ot = TREE_TYPE (DECL_RESULT (current_function_decl));
1541 tree nt = build_qualified_type (ot, TYPE_QUALS (ot) | TYPE_QUAL_CONST);
1543 val = assign_temp (nt, 0, 1);
1544 val = expand_expr (retval_rhs, val, GET_MODE (val), EXPAND_NORMAL);
1545 val = force_not_mem (val);
1546 /* Return the calculated value. */
1547 expand_value_return (val);
1549 else
1551 /* No hard reg used; calculate value into hard return reg. */
1552 expand_expr (retval, const0_rtx, VOIDmode, EXPAND_NORMAL);
1553 expand_value_return (result_rtl);
1558 /* Emit code to save the current value of stack. */
1560 expand_stack_save (void)
1562 rtx ret = NULL_RTX;
1564 do_pending_stack_adjust ();
1565 emit_stack_save (SAVE_BLOCK, &ret);
1566 return ret;
1569 /* Emit code to restore the current value of stack. */
1570 void
1571 expand_stack_restore (tree var)
1573 rtx prev, sa = expand_normal (var);
1575 sa = convert_memory_address (Pmode, sa);
1577 prev = get_last_insn ();
1578 emit_stack_restore (SAVE_BLOCK, sa);
1579 fixup_args_size_notes (prev, get_last_insn (), 0);
1582 /* Generate code to jump to LABEL if OP0 and OP1 are equal in mode MODE. PROB
1583 is the probability of jumping to LABEL. */
1584 static void
1585 do_jump_if_equal (enum machine_mode mode, rtx op0, rtx op1, rtx label,
1586 int unsignedp, int prob)
1588 gcc_assert (prob <= REG_BR_PROB_BASE);
1589 do_compare_rtx_and_jump (op0, op1, EQ, unsignedp, mode,
1590 NULL_RTX, NULL_RTX, label, prob);
1593 /* Do the insertion of a case label into case_list. The labels are
1594 fed to us in descending order from the sorted vector of case labels used
1595 in the tree part of the middle end. So the list we construct is
1596 sorted in ascending order.
1598 LABEL is the case label to be inserted. LOW and HIGH are the bounds
1599 against which the index is compared to jump to LABEL and PROB is the
1600 estimated probability LABEL is reached from the switch statement. */
1602 static struct case_node *
1603 add_case_node (struct case_node *head, tree low, tree high,
1604 tree label, int prob, alloc_pool case_node_pool)
1606 struct case_node *r;
1608 gcc_checking_assert (low);
1609 gcc_checking_assert (high && (TREE_TYPE (low) == TREE_TYPE (high)));
1611 /* Add this label to the chain. */
1612 r = (struct case_node *) pool_alloc (case_node_pool);
1613 r->low = low;
1614 r->high = high;
1615 r->code_label = label;
1616 r->parent = r->left = NULL;
1617 r->prob = prob;
1618 r->subtree_prob = prob;
1619 r->right = head;
1620 return r;
1623 /* Dump ROOT, a list or tree of case nodes, to file. */
1625 static void
1626 dump_case_nodes (FILE *f, struct case_node *root,
1627 int indent_step, int indent_level)
1629 HOST_WIDE_INT low, high;
1631 if (root == 0)
1632 return;
1633 indent_level++;
1635 dump_case_nodes (f, root->left, indent_step, indent_level);
1637 low = tree_low_cst (root->low, 0);
1638 high = tree_low_cst (root->high, 0);
1640 fputs (";; ", f);
1641 if (high == low)
1642 fprintf (f, "%*s" HOST_WIDE_INT_PRINT_DEC,
1643 indent_step * indent_level, "", low);
1644 else
1645 fprintf (f, "%*s" HOST_WIDE_INT_PRINT_DEC " ... " HOST_WIDE_INT_PRINT_DEC,
1646 indent_step * indent_level, "", low, high);
1647 fputs ("\n", f);
1649 dump_case_nodes (f, root->right, indent_step, indent_level);
1652 #ifndef HAVE_casesi
1653 #define HAVE_casesi 0
1654 #endif
1656 #ifndef HAVE_tablejump
1657 #define HAVE_tablejump 0
1658 #endif
1660 /* Return the smallest number of different values for which it is best to use a
1661 jump-table instead of a tree of conditional branches. */
1663 static unsigned int
1664 case_values_threshold (void)
1666 unsigned int threshold = PARAM_VALUE (PARAM_CASE_VALUES_THRESHOLD);
1668 if (threshold == 0)
1669 threshold = targetm.case_values_threshold ();
1671 return threshold;
1674 /* Return true if a switch should be expanded as a decision tree.
1675 RANGE is the difference between highest and lowest case.
1676 UNIQ is number of unique case node targets, not counting the default case.
1677 COUNT is the number of comparisons needed, not counting the default case. */
1679 static bool
1680 expand_switch_as_decision_tree_p (tree range,
1681 unsigned int uniq ATTRIBUTE_UNUSED,
1682 unsigned int count)
1684 int max_ratio;
1686 /* If neither casesi or tablejump is available, or flag_jump_tables
1687 over-ruled us, we really have no choice. */
1688 if (!HAVE_casesi && !HAVE_tablejump)
1689 return true;
1690 if (!flag_jump_tables)
1691 return true;
1692 #ifndef ASM_OUTPUT_ADDR_DIFF_ELT
1693 if (flag_pic)
1694 return true;
1695 #endif
1697 /* If the switch is relatively small such that the cost of one
1698 indirect jump on the target are higher than the cost of a
1699 decision tree, go with the decision tree.
1701 If range of values is much bigger than number of values,
1702 or if it is too large to represent in a HOST_WIDE_INT,
1703 make a sequence of conditional branches instead of a dispatch.
1705 The definition of "much bigger" depends on whether we are
1706 optimizing for size or for speed. If the former, the maximum
1707 ratio range/count = 3, because this was found to be the optimal
1708 ratio for size on i686-pc-linux-gnu, see PR11823. The ratio
1709 10 is much older, and was probably selected after an extensive
1710 benchmarking investigation on numerous platforms. Or maybe it
1711 just made sense to someone at some point in the history of GCC,
1712 who knows... */
1713 max_ratio = optimize_insn_for_size_p () ? 3 : 10;
1714 if (count < case_values_threshold ()
1715 || ! host_integerp (range, /*pos=*/1)
1716 || compare_tree_int (range, max_ratio * count) > 0)
1717 return true;
1719 return false;
1722 /* Generate a decision tree, switching on INDEX_EXPR and jumping to
1723 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1724 DEFAULT_PROB is the estimated probability that it jumps to
1725 DEFAULT_LABEL.
1727 We generate a binary decision tree to select the appropriate target
1728 code. This is done as follows:
1730 If the index is a short or char that we do not have
1731 an insn to handle comparisons directly, convert it to
1732 a full integer now, rather than letting each comparison
1733 generate the conversion.
1735 Load the index into a register.
1737 The list of cases is rearranged into a binary tree,
1738 nearly optimal assuming equal probability for each case.
1740 The tree is transformed into RTL, eliminating redundant
1741 test conditions at the same time.
1743 If program flow could reach the end of the decision tree
1744 an unconditional jump to the default code is emitted.
1746 The above process is unaware of the CFG. The caller has to fix up
1747 the CFG itself. This is done in cfgexpand.c. */
1749 static void
1750 emit_case_decision_tree (tree index_expr, tree index_type,
1751 struct case_node *case_list, rtx default_label,
1752 int default_prob)
1754 rtx index = expand_normal (index_expr);
1756 if (GET_MODE_CLASS (GET_MODE (index)) == MODE_INT
1757 && ! have_insn_for (COMPARE, GET_MODE (index)))
1759 int unsignedp = TYPE_UNSIGNED (index_type);
1760 enum machine_mode wider_mode;
1761 for (wider_mode = GET_MODE (index); wider_mode != VOIDmode;
1762 wider_mode = GET_MODE_WIDER_MODE (wider_mode))
1763 if (have_insn_for (COMPARE, wider_mode))
1765 index = convert_to_mode (wider_mode, index, unsignedp);
1766 break;
1770 do_pending_stack_adjust ();
1772 if (MEM_P (index))
1774 index = copy_to_reg (index);
1775 if (TREE_CODE (index_expr) == SSA_NAME)
1776 set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (index_expr), index);
1779 balance_case_nodes (&case_list, NULL);
1781 if (dump_file && (dump_flags & TDF_DETAILS))
1783 int indent_step = ceil_log2 (TYPE_PRECISION (index_type)) + 2;
1784 fprintf (dump_file, ";; Expanding GIMPLE switch as decision tree:\n");
1785 dump_case_nodes (dump_file, case_list, indent_step, 0);
1788 emit_case_nodes (index, case_list, default_label, default_prob, index_type);
1789 if (default_label)
1790 emit_jump (default_label);
1793 /* Return the sum of probabilities of outgoing edges of basic block BB. */
1795 static int
1796 get_outgoing_edge_probs (basic_block bb)
1798 edge e;
1799 edge_iterator ei;
1800 int prob_sum = 0;
1801 if (!bb)
1802 return 0;
1803 FOR_EACH_EDGE (e, ei, bb->succs)
1804 prob_sum += e->probability;
1805 return prob_sum;
1808 /* Computes the conditional probability of jumping to a target if the branch
1809 instruction is executed.
1810 TARGET_PROB is the estimated probability of jumping to a target relative
1811 to some basic block BB.
1812 BASE_PROB is the probability of reaching the branch instruction relative
1813 to the same basic block BB. */
1815 static inline int
1816 conditional_probability (int target_prob, int base_prob)
1818 if (base_prob > 0)
1820 gcc_assert (target_prob >= 0);
1821 gcc_assert (target_prob <= base_prob);
1822 return GCOV_COMPUTE_SCALE (target_prob, base_prob);
1824 return -1;
1827 /* Generate a dispatch tabler, switching on INDEX_EXPR and jumping to
1828 one of the labels in CASE_LIST or to the DEFAULT_LABEL.
1829 MINVAL, MAXVAL, and RANGE are the extrema and range of the case
1830 labels in CASE_LIST. STMT_BB is the basic block containing the statement.
1832 First, a jump insn is emitted. First we try "casesi". If that
1833 fails, try "tablejump". A target *must* have one of them (or both).
1835 Then, a table with the target labels is emitted.
1837 The process is unaware of the CFG. The caller has to fix up
1838 the CFG itself. This is done in cfgexpand.c. */
1840 static void
1841 emit_case_dispatch_table (tree index_expr, tree index_type,
1842 struct case_node *case_list, rtx default_label,
1843 tree minval, tree maxval, tree range,
1844 basic_block stmt_bb)
1846 int i, ncases;
1847 struct case_node *n;
1848 rtx *labelvec;
1849 rtx fallback_label = label_rtx (case_list->code_label);
1850 rtx table_label = gen_label_rtx ();
1851 bool has_gaps = false;
1852 edge default_edge = stmt_bb ? EDGE_SUCC (stmt_bb, 0) : NULL;
1853 int default_prob = default_edge ? default_edge->probability : 0;
1854 int base = get_outgoing_edge_probs (stmt_bb);
1855 bool try_with_tablejump = false;
1857 int new_default_prob = conditional_probability (default_prob,
1858 base);
1860 if (! try_casesi (index_type, index_expr, minval, range,
1861 table_label, default_label, fallback_label,
1862 new_default_prob))
1864 /* Index jumptables from zero for suitable values of minval to avoid
1865 a subtraction. For the rationale see:
1866 "http://gcc.gnu.org/ml/gcc-patches/2001-10/msg01234.html". */
1867 if (optimize_insn_for_speed_p ()
1868 && compare_tree_int (minval, 0) > 0
1869 && compare_tree_int (minval, 3) < 0)
1871 minval = build_int_cst (index_type, 0);
1872 range = maxval;
1873 has_gaps = true;
1875 try_with_tablejump = true;
1878 /* Get table of labels to jump to, in order of case index. */
1880 ncases = tree_low_cst (range, 0) + 1;
1881 labelvec = XALLOCAVEC (rtx, ncases);
1882 memset (labelvec, 0, ncases * sizeof (rtx));
1884 for (n = case_list; n; n = n->right)
1886 /* Compute the low and high bounds relative to the minimum
1887 value since that should fit in a HOST_WIDE_INT while the
1888 actual values may not. */
1889 HOST_WIDE_INT i_low
1890 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1891 n->low, minval), 1);
1892 HOST_WIDE_INT i_high
1893 = tree_low_cst (fold_build2 (MINUS_EXPR, index_type,
1894 n->high, minval), 1);
1895 HOST_WIDE_INT i;
1897 for (i = i_low; i <= i_high; i ++)
1898 labelvec[i]
1899 = gen_rtx_LABEL_REF (Pmode, label_rtx (n->code_label));
1902 /* Fill in the gaps with the default. We may have gaps at
1903 the beginning if we tried to avoid the minval subtraction,
1904 so substitute some label even if the default label was
1905 deemed unreachable. */
1906 if (!default_label)
1907 default_label = fallback_label;
1908 for (i = 0; i < ncases; i++)
1909 if (labelvec[i] == 0)
1911 has_gaps = true;
1912 labelvec[i] = gen_rtx_LABEL_REF (Pmode, default_label);
1915 if (has_gaps)
1917 /* There is at least one entry in the jump table that jumps
1918 to default label. The default label can either be reached
1919 through the indirect jump or the direct conditional jump
1920 before that. Split the probability of reaching the
1921 default label among these two jumps. */
1922 new_default_prob = conditional_probability (default_prob/2,
1923 base);
1924 default_prob /= 2;
1925 base -= default_prob;
1927 else
1929 base -= default_prob;
1930 default_prob = 0;
1933 if (default_edge)
1934 default_edge->probability = default_prob;
1936 /* We have altered the probability of the default edge. So the probabilities
1937 of all other edges need to be adjusted so that it sums up to
1938 REG_BR_PROB_BASE. */
1939 if (base)
1941 edge e;
1942 edge_iterator ei;
1943 FOR_EACH_EDGE (e, ei, stmt_bb->succs)
1944 e->probability = GCOV_COMPUTE_SCALE (e->probability, base);
1947 if (try_with_tablejump)
1949 bool ok = try_tablejump (index_type, index_expr, minval, range,
1950 table_label, default_label, new_default_prob);
1951 gcc_assert (ok);
1953 /* Output the table. */
1954 emit_label (table_label);
1956 if (CASE_VECTOR_PC_RELATIVE || flag_pic)
1957 emit_jump_table_data (gen_rtx_ADDR_DIFF_VEC (CASE_VECTOR_MODE,
1958 gen_rtx_LABEL_REF (Pmode,
1959 table_label),
1960 gen_rtvec_v (ncases, labelvec),
1961 const0_rtx, const0_rtx));
1962 else
1963 emit_jump_table_data (gen_rtx_ADDR_VEC (CASE_VECTOR_MODE,
1964 gen_rtvec_v (ncases, labelvec)));
1966 /* Record no drop-through after the table. */
1967 emit_barrier ();
1970 /* Reset the aux field of all outgoing edges of basic block BB. */
1972 static inline void
1973 reset_out_edges_aux (basic_block bb)
1975 edge e;
1976 edge_iterator ei;
1977 FOR_EACH_EDGE (e, ei, bb->succs)
1978 e->aux = (void *)0;
1981 /* Compute the number of case labels that correspond to each outgoing edge of
1982 STMT. Record this information in the aux field of the edge. */
1984 static inline void
1985 compute_cases_per_edge (gimple stmt)
1987 basic_block bb = gimple_bb (stmt);
1988 reset_out_edges_aux (bb);
1989 int ncases = gimple_switch_num_labels (stmt);
1990 for (int i = ncases - 1; i >= 1; --i)
1992 tree elt = gimple_switch_label (stmt, i);
1993 tree lab = CASE_LABEL (elt);
1994 basic_block case_bb = label_to_block_fn (cfun, lab);
1995 edge case_edge = find_edge (bb, case_bb);
1996 case_edge->aux = (void *)((intptr_t)(case_edge->aux) + 1);
2000 /* Terminate a case (Pascal/Ada) or switch (C) statement
2001 in which ORIG_INDEX is the expression to be tested.
2002 If ORIG_TYPE is not NULL, it is the original ORIG_INDEX
2003 type as given in the source before any compiler conversions.
2004 Generate the code to test it and jump to the right place. */
2006 void
2007 expand_case (gimple stmt)
2009 tree minval = NULL_TREE, maxval = NULL_TREE, range = NULL_TREE;
2010 rtx default_label = NULL_RTX;
2011 unsigned int count, uniq;
2012 int i;
2013 int ncases = gimple_switch_num_labels (stmt);
2014 tree index_expr = gimple_switch_index (stmt);
2015 tree index_type = TREE_TYPE (index_expr);
2016 tree elt;
2017 basic_block bb = gimple_bb (stmt);
2019 /* A list of case labels; it is first built as a list and it may then
2020 be rearranged into a nearly balanced binary tree. */
2021 struct case_node *case_list = 0;
2023 /* A pool for case nodes. */
2024 alloc_pool case_node_pool;
2026 /* An ERROR_MARK occurs for various reasons including invalid data type.
2027 ??? Can this still happen, with GIMPLE and all? */
2028 if (index_type == error_mark_node)
2029 return;
2031 /* cleanup_tree_cfg removes all SWITCH_EXPR with their index
2032 expressions being INTEGER_CST. */
2033 gcc_assert (TREE_CODE (index_expr) != INTEGER_CST);
2035 case_node_pool = create_alloc_pool ("struct case_node pool",
2036 sizeof (struct case_node),
2037 100);
2039 do_pending_stack_adjust ();
2041 /* Find the default case target label. */
2042 default_label = label_rtx (CASE_LABEL (gimple_switch_default_label (stmt)));
2043 edge default_edge = EDGE_SUCC (bb, 0);
2044 int default_prob = default_edge->probability;
2046 /* Get upper and lower bounds of case values. */
2047 elt = gimple_switch_label (stmt, 1);
2048 minval = fold_convert (index_type, CASE_LOW (elt));
2049 elt = gimple_switch_label (stmt, ncases - 1);
2050 if (CASE_HIGH (elt))
2051 maxval = fold_convert (index_type, CASE_HIGH (elt));
2052 else
2053 maxval = fold_convert (index_type, CASE_LOW (elt));
2055 /* Compute span of values. */
2056 range = fold_build2 (MINUS_EXPR, index_type, maxval, minval);
2058 /* Listify the labels queue and gather some numbers to decide
2059 how to expand this switch(). */
2060 uniq = 0;
2061 count = 0;
2062 struct pointer_set_t *seen_labels = pointer_set_create ();
2063 compute_cases_per_edge (stmt);
2065 for (i = ncases - 1; i >= 1; --i)
2067 elt = gimple_switch_label (stmt, i);
2068 tree low = CASE_LOW (elt);
2069 gcc_assert (low);
2070 tree high = CASE_HIGH (elt);
2071 gcc_assert (! high || tree_int_cst_lt (low, high));
2072 tree lab = CASE_LABEL (elt);
2074 /* Count the elements.
2075 A range counts double, since it requires two compares. */
2076 count++;
2077 if (high)
2078 count++;
2080 /* If we have not seen this label yet, then increase the
2081 number of unique case node targets seen. */
2082 if (!pointer_set_insert (seen_labels, lab))
2083 uniq++;
2085 /* The bounds on the case range, LOW and HIGH, have to be converted
2086 to case's index type TYPE. Note that the original type of the
2087 case index in the source code is usually "lost" during
2088 gimplification due to type promotion, but the case labels retain the
2089 original type. Make sure to drop overflow flags. */
2090 low = fold_convert (index_type, low);
2091 if (TREE_OVERFLOW (low))
2092 low = build_int_cst_wide (index_type,
2093 TREE_INT_CST_LOW (low),
2094 TREE_INT_CST_HIGH (low));
2096 /* The canonical from of a case label in GIMPLE is that a simple case
2097 has an empty CASE_HIGH. For the casesi and tablejump expanders,
2098 the back ends want simple cases to have high == low. */
2099 if (! high)
2100 high = low;
2101 high = fold_convert (index_type, high);
2102 if (TREE_OVERFLOW (high))
2103 high = build_int_cst_wide (index_type,
2104 TREE_INT_CST_LOW (high),
2105 TREE_INT_CST_HIGH (high));
2107 basic_block case_bb = label_to_block_fn (cfun, lab);
2108 edge case_edge = find_edge (bb, case_bb);
2109 case_list = add_case_node (
2110 case_list, low, high, lab,
2111 case_edge->probability / (intptr_t)(case_edge->aux),
2112 case_node_pool);
2114 pointer_set_destroy (seen_labels);
2115 reset_out_edges_aux (bb);
2117 /* cleanup_tree_cfg removes all SWITCH_EXPR with a single
2118 destination, such as one with a default case only.
2119 It also removes cases that are out of range for the switch
2120 type, so we should never get a zero here. */
2121 gcc_assert (count > 0);
2123 rtx before_case = get_last_insn ();
2125 /* Decide how to expand this switch.
2126 The two options at this point are a dispatch table (casesi or
2127 tablejump) or a decision tree. */
2129 if (expand_switch_as_decision_tree_p (range, uniq, count))
2130 emit_case_decision_tree (index_expr, index_type,
2131 case_list, default_label,
2132 default_prob);
2133 else
2134 emit_case_dispatch_table (index_expr, index_type,
2135 case_list, default_label,
2136 minval, maxval, range, bb);
2138 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2140 free_temp_slots ();
2141 free_alloc_pool (case_node_pool);
2144 /* Expand the dispatch to a short decrement chain if there are few cases
2145 to dispatch to. Likewise if neither casesi nor tablejump is available,
2146 or if flag_jump_tables is set. Otherwise, expand as a casesi or a
2147 tablejump. The index mode is always the mode of integer_type_node.
2148 Trap if no case matches the index.
2150 DISPATCH_INDEX is the index expression to switch on. It should be a
2151 memory or register operand.
2153 DISPATCH_TABLE is a set of case labels. The set should be sorted in
2154 ascending order, be contiguous, starting with value 0, and contain only
2155 single-valued case labels. */
2157 void
2158 expand_sjlj_dispatch_table (rtx dispatch_index,
2159 vec<tree> dispatch_table)
2161 tree index_type = integer_type_node;
2162 enum machine_mode index_mode = TYPE_MODE (index_type);
2164 int ncases = dispatch_table.length ();
2166 do_pending_stack_adjust ();
2167 rtx before_case = get_last_insn ();
2169 /* Expand as a decrement-chain if there are 5 or fewer dispatch
2170 labels. This covers more than 98% of the cases in libjava,
2171 and seems to be a reasonable compromise between the "old way"
2172 of expanding as a decision tree or dispatch table vs. the "new
2173 way" with decrement chain or dispatch table. */
2174 if (dispatch_table.length () <= 5
2175 || (!HAVE_casesi && !HAVE_tablejump)
2176 || !flag_jump_tables)
2178 /* Expand the dispatch as a decrement chain:
2180 "switch(index) {case 0: do_0; case 1: do_1; ...; case N: do_N;}"
2184 if (index == 0) do_0; else index--;
2185 if (index == 0) do_1; else index--;
2187 if (index == 0) do_N; else index--;
2189 This is more efficient than a dispatch table on most machines.
2190 The last "index--" is redundant but the code is trivially dead
2191 and will be cleaned up by later passes. */
2192 rtx index = copy_to_mode_reg (index_mode, dispatch_index);
2193 rtx zero = CONST0_RTX (index_mode);
2194 for (int i = 0; i < ncases; i++)
2196 tree elt = dispatch_table[i];
2197 rtx lab = label_rtx (CASE_LABEL (elt));
2198 do_jump_if_equal (index_mode, index, zero, lab, 0, -1);
2199 force_expand_binop (index_mode, sub_optab,
2200 index, CONST1_RTX (index_mode),
2201 index, 0, OPTAB_DIRECT);
2204 else
2206 /* Similar to expand_case, but much simpler. */
2207 struct case_node *case_list = 0;
2208 alloc_pool case_node_pool = create_alloc_pool ("struct sjlj_case pool",
2209 sizeof (struct case_node),
2210 ncases);
2211 tree index_expr = make_tree (index_type, dispatch_index);
2212 tree minval = build_int_cst (index_type, 0);
2213 tree maxval = CASE_LOW (dispatch_table.last ());
2214 tree range = maxval;
2215 rtx default_label = gen_label_rtx ();
2217 for (int i = ncases - 1; i >= 0; --i)
2219 tree elt = dispatch_table[i];
2220 tree low = CASE_LOW (elt);
2221 tree lab = CASE_LABEL (elt);
2222 case_list = add_case_node (case_list, low, low, lab, 0, case_node_pool);
2225 emit_case_dispatch_table (index_expr, index_type,
2226 case_list, default_label,
2227 minval, maxval, range,
2228 BLOCK_FOR_INSN (before_case));
2229 emit_label (default_label);
2230 free_alloc_pool (case_node_pool);
2233 /* Dispatching something not handled? Trap! */
2234 expand_builtin_trap ();
2236 reorder_insns (NEXT_INSN (before_case), get_last_insn (), before_case);
2238 free_temp_slots ();
2242 /* Take an ordered list of case nodes
2243 and transform them into a near optimal binary tree,
2244 on the assumption that any target code selection value is as
2245 likely as any other.
2247 The transformation is performed by splitting the ordered
2248 list into two equal sections plus a pivot. The parts are
2249 then attached to the pivot as left and right branches. Each
2250 branch is then transformed recursively. */
2252 static void
2253 balance_case_nodes (case_node_ptr *head, case_node_ptr parent)
2255 case_node_ptr np;
2257 np = *head;
2258 if (np)
2260 int i = 0;
2261 int ranges = 0;
2262 case_node_ptr *npp;
2263 case_node_ptr left;
2265 /* Count the number of entries on branch. Also count the ranges. */
2267 while (np)
2269 if (!tree_int_cst_equal (np->low, np->high))
2270 ranges++;
2272 i++;
2273 np = np->right;
2276 if (i > 2)
2278 /* Split this list if it is long enough for that to help. */
2279 npp = head;
2280 left = *npp;
2282 /* If there are just three nodes, split at the middle one. */
2283 if (i == 3)
2284 npp = &(*npp)->right;
2285 else
2287 /* Find the place in the list that bisects the list's total cost,
2288 where ranges count as 2.
2289 Here I gets half the total cost. */
2290 i = (i + ranges + 1) / 2;
2291 while (1)
2293 /* Skip nodes while their cost does not reach that amount. */
2294 if (!tree_int_cst_equal ((*npp)->low, (*npp)->high))
2295 i--;
2296 i--;
2297 if (i <= 0)
2298 break;
2299 npp = &(*npp)->right;
2302 *head = np = *npp;
2303 *npp = 0;
2304 np->parent = parent;
2305 np->left = left;
2307 /* Optimize each of the two split parts. */
2308 balance_case_nodes (&np->left, np);
2309 balance_case_nodes (&np->right, np);
2310 np->subtree_prob = np->prob;
2311 np->subtree_prob += np->left->subtree_prob;
2312 np->subtree_prob += np->right->subtree_prob;
2314 else
2316 /* Else leave this branch as one level,
2317 but fill in `parent' fields. */
2318 np = *head;
2319 np->parent = parent;
2320 np->subtree_prob = np->prob;
2321 for (; np->right; np = np->right)
2323 np->right->parent = np;
2324 (*head)->subtree_prob += np->right->subtree_prob;
2330 /* Search the parent sections of the case node tree
2331 to see if a test for the lower bound of NODE would be redundant.
2332 INDEX_TYPE is the type of the index expression.
2334 The instructions to generate the case decision tree are
2335 output in the same order as nodes are processed so it is
2336 known that if a parent node checks the range of the current
2337 node minus one that the current node is bounded at its lower
2338 span. Thus the test would be redundant. */
2340 static int
2341 node_has_low_bound (case_node_ptr node, tree index_type)
2343 tree low_minus_one;
2344 case_node_ptr pnode;
2346 /* If the lower bound of this node is the lowest value in the index type,
2347 we need not test it. */
2349 if (tree_int_cst_equal (node->low, TYPE_MIN_VALUE (index_type)))
2350 return 1;
2352 /* If this node has a left branch, the value at the left must be less
2353 than that at this node, so it cannot be bounded at the bottom and
2354 we need not bother testing any further. */
2356 if (node->left)
2357 return 0;
2359 low_minus_one = fold_build2 (MINUS_EXPR, TREE_TYPE (node->low),
2360 node->low,
2361 build_int_cst (TREE_TYPE (node->low), 1));
2363 /* If the subtraction above overflowed, we can't verify anything.
2364 Otherwise, look for a parent that tests our value - 1. */
2366 if (! tree_int_cst_lt (low_minus_one, node->low))
2367 return 0;
2369 for (pnode = node->parent; pnode; pnode = pnode->parent)
2370 if (tree_int_cst_equal (low_minus_one, pnode->high))
2371 return 1;
2373 return 0;
2376 /* Search the parent sections of the case node tree
2377 to see if a test for the upper bound of NODE would be redundant.
2378 INDEX_TYPE is the type of the index expression.
2380 The instructions to generate the case decision tree are
2381 output in the same order as nodes are processed so it is
2382 known that if a parent node checks the range of the current
2383 node plus one that the current node is bounded at its upper
2384 span. Thus the test would be redundant. */
2386 static int
2387 node_has_high_bound (case_node_ptr node, tree index_type)
2389 tree high_plus_one;
2390 case_node_ptr pnode;
2392 /* If there is no upper bound, obviously no test is needed. */
2394 if (TYPE_MAX_VALUE (index_type) == NULL)
2395 return 1;
2397 /* If the upper bound of this node is the highest value in the type
2398 of the index expression, we need not test against it. */
2400 if (tree_int_cst_equal (node->high, TYPE_MAX_VALUE (index_type)))
2401 return 1;
2403 /* If this node has a right branch, the value at the right must be greater
2404 than that at this node, so it cannot be bounded at the top and
2405 we need not bother testing any further. */
2407 if (node->right)
2408 return 0;
2410 high_plus_one = fold_build2 (PLUS_EXPR, TREE_TYPE (node->high),
2411 node->high,
2412 build_int_cst (TREE_TYPE (node->high), 1));
2414 /* If the addition above overflowed, we can't verify anything.
2415 Otherwise, look for a parent that tests our value + 1. */
2417 if (! tree_int_cst_lt (node->high, high_plus_one))
2418 return 0;
2420 for (pnode = node->parent; pnode; pnode = pnode->parent)
2421 if (tree_int_cst_equal (high_plus_one, pnode->low))
2422 return 1;
2424 return 0;
2427 /* Search the parent sections of the
2428 case node tree to see if both tests for the upper and lower
2429 bounds of NODE would be redundant. */
2431 static int
2432 node_is_bounded (case_node_ptr node, tree index_type)
2434 return (node_has_low_bound (node, index_type)
2435 && node_has_high_bound (node, index_type));
2439 /* Emit step-by-step code to select a case for the value of INDEX.
2440 The thus generated decision tree follows the form of the
2441 case-node binary tree NODE, whose nodes represent test conditions.
2442 INDEX_TYPE is the type of the index of the switch.
2444 Care is taken to prune redundant tests from the decision tree
2445 by detecting any boundary conditions already checked by
2446 emitted rtx. (See node_has_high_bound, node_has_low_bound
2447 and node_is_bounded, above.)
2449 Where the test conditions can be shown to be redundant we emit
2450 an unconditional jump to the target code. As a further
2451 optimization, the subordinates of a tree node are examined to
2452 check for bounded nodes. In this case conditional and/or
2453 unconditional jumps as a result of the boundary check for the
2454 current node are arranged to target the subordinates associated
2455 code for out of bound conditions on the current node.
2457 We can assume that when control reaches the code generated here,
2458 the index value has already been compared with the parents
2459 of this node, and determined to be on the same side of each parent
2460 as this node is. Thus, if this node tests for the value 51,
2461 and a parent tested for 52, we don't need to consider
2462 the possibility of a value greater than 51. If another parent
2463 tests for the value 50, then this node need not test anything. */
2465 static void
2466 emit_case_nodes (rtx index, case_node_ptr node, rtx default_label,
2467 int default_prob, tree index_type)
2469 /* If INDEX has an unsigned type, we must make unsigned branches. */
2470 int unsignedp = TYPE_UNSIGNED (index_type);
2471 int probability;
2472 int prob = node->prob, subtree_prob = node->subtree_prob;
2473 enum machine_mode mode = GET_MODE (index);
2474 enum machine_mode imode = TYPE_MODE (index_type);
2476 /* Handle indices detected as constant during RTL expansion. */
2477 if (mode == VOIDmode)
2478 mode = imode;
2480 /* See if our parents have already tested everything for us.
2481 If they have, emit an unconditional jump for this node. */
2482 if (node_is_bounded (node, index_type))
2483 emit_jump (label_rtx (node->code_label));
2485 else if (tree_int_cst_equal (node->low, node->high))
2487 probability = conditional_probability (prob, subtree_prob + default_prob);
2488 /* Node is single valued. First see if the index expression matches
2489 this node and then check our children, if any. */
2490 do_jump_if_equal (mode, index,
2491 convert_modes (mode, imode,
2492 expand_normal (node->low),
2493 unsignedp),
2494 label_rtx (node->code_label), unsignedp, probability);
2495 /* Since this case is taken at this point, reduce its weight from
2496 subtree_weight. */
2497 subtree_prob -= prob;
2498 if (node->right != 0 && node->left != 0)
2500 /* This node has children on both sides.
2501 Dispatch to one side or the other
2502 by comparing the index value with this node's value.
2503 If one subtree is bounded, check that one first,
2504 so we can avoid real branches in the tree. */
2506 if (node_is_bounded (node->right, index_type))
2508 probability = conditional_probability (
2509 node->right->prob,
2510 subtree_prob + default_prob);
2511 emit_cmp_and_jump_insns (index,
2512 convert_modes
2513 (mode, imode,
2514 expand_normal (node->high),
2515 unsignedp),
2516 GT, NULL_RTX, mode, unsignedp,
2517 label_rtx (node->right->code_label),
2518 probability);
2519 emit_case_nodes (index, node->left, default_label, default_prob,
2520 index_type);
2523 else if (node_is_bounded (node->left, index_type))
2525 probability = conditional_probability (
2526 node->left->prob,
2527 subtree_prob + default_prob);
2528 emit_cmp_and_jump_insns (index,
2529 convert_modes
2530 (mode, imode,
2531 expand_normal (node->high),
2532 unsignedp),
2533 LT, NULL_RTX, mode, unsignedp,
2534 label_rtx (node->left->code_label),
2535 probability);
2536 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2539 /* If both children are single-valued cases with no
2540 children, finish up all the work. This way, we can save
2541 one ordered comparison. */
2542 else if (tree_int_cst_equal (node->right->low, node->right->high)
2543 && node->right->left == 0
2544 && node->right->right == 0
2545 && tree_int_cst_equal (node->left->low, node->left->high)
2546 && node->left->left == 0
2547 && node->left->right == 0)
2549 /* Neither node is bounded. First distinguish the two sides;
2550 then emit the code for one side at a time. */
2552 /* See if the value matches what the right hand side
2553 wants. */
2554 probability = conditional_probability (
2555 node->right->prob,
2556 subtree_prob + default_prob);
2557 do_jump_if_equal (mode, index,
2558 convert_modes (mode, imode,
2559 expand_normal (node->right->low),
2560 unsignedp),
2561 label_rtx (node->right->code_label),
2562 unsignedp, probability);
2564 /* See if the value matches what the left hand side
2565 wants. */
2566 probability = conditional_probability (
2567 node->left->prob,
2568 subtree_prob + default_prob);
2569 do_jump_if_equal (mode, index,
2570 convert_modes (mode, imode,
2571 expand_normal (node->left->low),
2572 unsignedp),
2573 label_rtx (node->left->code_label),
2574 unsignedp, probability);
2577 else
2579 /* Neither node is bounded. First distinguish the two sides;
2580 then emit the code for one side at a time. */
2582 tree test_label
2583 = build_decl (curr_insn_location (),
2584 LABEL_DECL, NULL_TREE, NULL_TREE);
2586 /* The default label could be reached either through the right
2587 subtree or the left subtree. Divide the probability
2588 equally. */
2589 probability = conditional_probability (
2590 node->right->subtree_prob + default_prob/2,
2591 subtree_prob + default_prob);
2592 /* See if the value is on the right. */
2593 emit_cmp_and_jump_insns (index,
2594 convert_modes
2595 (mode, imode,
2596 expand_normal (node->high),
2597 unsignedp),
2598 GT, NULL_RTX, mode, unsignedp,
2599 label_rtx (test_label),
2600 probability);
2601 default_prob /= 2;
2603 /* Value must be on the left.
2604 Handle the left-hand subtree. */
2605 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2606 /* If left-hand subtree does nothing,
2607 go to default. */
2608 if (default_label)
2609 emit_jump (default_label);
2611 /* Code branches here for the right-hand subtree. */
2612 expand_label (test_label);
2613 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2617 else if (node->right != 0 && node->left == 0)
2619 /* Here we have a right child but no left so we issue a conditional
2620 branch to default and process the right child.
2622 Omit the conditional branch to default if the right child
2623 does not have any children and is single valued; it would
2624 cost too much space to save so little time. */
2626 if (node->right->right || node->right->left
2627 || !tree_int_cst_equal (node->right->low, node->right->high))
2629 if (!node_has_low_bound (node, index_type))
2631 probability = conditional_probability (
2632 default_prob/2,
2633 subtree_prob + default_prob);
2634 emit_cmp_and_jump_insns (index,
2635 convert_modes
2636 (mode, imode,
2637 expand_normal (node->high),
2638 unsignedp),
2639 LT, NULL_RTX, mode, unsignedp,
2640 default_label,
2641 probability);
2642 default_prob /= 2;
2645 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2647 else
2649 probability = conditional_probability (
2650 node->right->subtree_prob,
2651 subtree_prob + default_prob);
2652 /* We cannot process node->right normally
2653 since we haven't ruled out the numbers less than
2654 this node's value. So handle node->right explicitly. */
2655 do_jump_if_equal (mode, index,
2656 convert_modes
2657 (mode, imode,
2658 expand_normal (node->right->low),
2659 unsignedp),
2660 label_rtx (node->right->code_label), unsignedp, probability);
2664 else if (node->right == 0 && node->left != 0)
2666 /* Just one subtree, on the left. */
2667 if (node->left->left || node->left->right
2668 || !tree_int_cst_equal (node->left->low, node->left->high))
2670 if (!node_has_high_bound (node, index_type))
2672 probability = conditional_probability (
2673 default_prob/2,
2674 subtree_prob + default_prob);
2675 emit_cmp_and_jump_insns (index,
2676 convert_modes
2677 (mode, imode,
2678 expand_normal (node->high),
2679 unsignedp),
2680 GT, NULL_RTX, mode, unsignedp,
2681 default_label,
2682 probability);
2683 default_prob /= 2;
2686 emit_case_nodes (index, node->left, default_label,
2687 default_prob, index_type);
2689 else
2691 probability = conditional_probability (
2692 node->left->subtree_prob,
2693 subtree_prob + default_prob);
2694 /* We cannot process node->left normally
2695 since we haven't ruled out the numbers less than
2696 this node's value. So handle node->left explicitly. */
2697 do_jump_if_equal (mode, index,
2698 convert_modes
2699 (mode, imode,
2700 expand_normal (node->left->low),
2701 unsignedp),
2702 label_rtx (node->left->code_label), unsignedp, probability);
2706 else
2708 /* Node is a range. These cases are very similar to those for a single
2709 value, except that we do not start by testing whether this node
2710 is the one to branch to. */
2712 if (node->right != 0 && node->left != 0)
2714 /* Node has subtrees on both sides.
2715 If the right-hand subtree is bounded,
2716 test for it first, since we can go straight there.
2717 Otherwise, we need to make a branch in the control structure,
2718 then handle the two subtrees. */
2719 tree test_label = 0;
2721 if (node_is_bounded (node->right, index_type))
2723 /* Right hand node is fully bounded so we can eliminate any
2724 testing and branch directly to the target code. */
2725 probability = conditional_probability (
2726 node->right->subtree_prob,
2727 subtree_prob + default_prob);
2728 emit_cmp_and_jump_insns (index,
2729 convert_modes
2730 (mode, imode,
2731 expand_normal (node->high),
2732 unsignedp),
2733 GT, NULL_RTX, mode, unsignedp,
2734 label_rtx (node->right->code_label),
2735 probability);
2737 else
2739 /* Right hand node requires testing.
2740 Branch to a label where we will handle it later. */
2742 test_label = build_decl (curr_insn_location (),
2743 LABEL_DECL, NULL_TREE, NULL_TREE);
2744 probability = conditional_probability (
2745 node->right->subtree_prob + default_prob/2,
2746 subtree_prob + default_prob);
2747 emit_cmp_and_jump_insns (index,
2748 convert_modes
2749 (mode, imode,
2750 expand_normal (node->high),
2751 unsignedp),
2752 GT, NULL_RTX, mode, unsignedp,
2753 label_rtx (test_label),
2754 probability);
2755 default_prob /= 2;
2758 /* Value belongs to this node or to the left-hand subtree. */
2760 probability = conditional_probability (
2761 prob,
2762 subtree_prob + default_prob);
2763 emit_cmp_and_jump_insns (index,
2764 convert_modes
2765 (mode, imode,
2766 expand_normal (node->low),
2767 unsignedp),
2768 GE, NULL_RTX, mode, unsignedp,
2769 label_rtx (node->code_label),
2770 probability);
2772 /* Handle the left-hand subtree. */
2773 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2775 /* If right node had to be handled later, do that now. */
2777 if (test_label)
2779 /* If the left-hand subtree fell through,
2780 don't let it fall into the right-hand subtree. */
2781 if (default_label)
2782 emit_jump (default_label);
2784 expand_label (test_label);
2785 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2789 else if (node->right != 0 && node->left == 0)
2791 /* Deal with values to the left of this node,
2792 if they are possible. */
2793 if (!node_has_low_bound (node, index_type))
2795 probability = conditional_probability (
2796 default_prob/2,
2797 subtree_prob + default_prob);
2798 emit_cmp_and_jump_insns (index,
2799 convert_modes
2800 (mode, imode,
2801 expand_normal (node->low),
2802 unsignedp),
2803 LT, NULL_RTX, mode, unsignedp,
2804 default_label,
2805 probability);
2806 default_prob /= 2;
2809 /* Value belongs to this node or to the right-hand subtree. */
2811 probability = conditional_probability (
2812 prob,
2813 subtree_prob + default_prob);
2814 emit_cmp_and_jump_insns (index,
2815 convert_modes
2816 (mode, imode,
2817 expand_normal (node->high),
2818 unsignedp),
2819 LE, NULL_RTX, mode, unsignedp,
2820 label_rtx (node->code_label),
2821 probability);
2823 emit_case_nodes (index, node->right, default_label, default_prob, index_type);
2826 else if (node->right == 0 && node->left != 0)
2828 /* Deal with values to the right of this node,
2829 if they are possible. */
2830 if (!node_has_high_bound (node, index_type))
2832 probability = conditional_probability (
2833 default_prob/2,
2834 subtree_prob + default_prob);
2835 emit_cmp_and_jump_insns (index,
2836 convert_modes
2837 (mode, imode,
2838 expand_normal (node->high),
2839 unsignedp),
2840 GT, NULL_RTX, mode, unsignedp,
2841 default_label,
2842 probability);
2843 default_prob /= 2;
2846 /* Value belongs to this node or to the left-hand subtree. */
2848 probability = conditional_probability (
2849 prob,
2850 subtree_prob + default_prob);
2851 emit_cmp_and_jump_insns (index,
2852 convert_modes
2853 (mode, imode,
2854 expand_normal (node->low),
2855 unsignedp),
2856 GE, NULL_RTX, mode, unsignedp,
2857 label_rtx (node->code_label),
2858 probability);
2860 emit_case_nodes (index, node->left, default_label, default_prob, index_type);
2863 else
2865 /* Node has no children so we check low and high bounds to remove
2866 redundant tests. Only one of the bounds can exist,
2867 since otherwise this node is bounded--a case tested already. */
2868 int high_bound = node_has_high_bound (node, index_type);
2869 int low_bound = node_has_low_bound (node, index_type);
2871 if (!high_bound && low_bound)
2873 probability = conditional_probability (
2874 default_prob,
2875 subtree_prob + default_prob);
2876 emit_cmp_and_jump_insns (index,
2877 convert_modes
2878 (mode, imode,
2879 expand_normal (node->high),
2880 unsignedp),
2881 GT, NULL_RTX, mode, unsignedp,
2882 default_label,
2883 probability);
2886 else if (!low_bound && high_bound)
2888 probability = conditional_probability (
2889 default_prob,
2890 subtree_prob + default_prob);
2891 emit_cmp_and_jump_insns (index,
2892 convert_modes
2893 (mode, imode,
2894 expand_normal (node->low),
2895 unsignedp),
2896 LT, NULL_RTX, mode, unsignedp,
2897 default_label,
2898 probability);
2900 else if (!low_bound && !high_bound)
2902 /* Widen LOW and HIGH to the same width as INDEX. */
2903 tree type = lang_hooks.types.type_for_mode (mode, unsignedp);
2904 tree low = build1 (CONVERT_EXPR, type, node->low);
2905 tree high = build1 (CONVERT_EXPR, type, node->high);
2906 rtx low_rtx, new_index, new_bound;
2908 /* Instead of doing two branches, emit one unsigned branch for
2909 (index-low) > (high-low). */
2910 low_rtx = expand_expr (low, NULL_RTX, mode, EXPAND_NORMAL);
2911 new_index = expand_simple_binop (mode, MINUS, index, low_rtx,
2912 NULL_RTX, unsignedp,
2913 OPTAB_WIDEN);
2914 new_bound = expand_expr (fold_build2 (MINUS_EXPR, type,
2915 high, low),
2916 NULL_RTX, mode, EXPAND_NORMAL);
2918 probability = conditional_probability (
2919 default_prob,
2920 subtree_prob + default_prob);
2921 emit_cmp_and_jump_insns (new_index, new_bound, GT, NULL_RTX,
2922 mode, 1, default_label, probability);
2925 emit_jump (label_rtx (node->code_label));