[rs6000] Use gen_int_mode in ieee_128bit_negative_zero
[official-gcc.git] / gcc / tree-eh.c
blobfc5fb02ddcd52e8653b47126f8e3a591426af5c9
1 /* Exception handling semantics and decomposition for trees.
2 Copyright (C) 2003-2017 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "cgraph.h"
31 #include "diagnostic-core.h"
32 #include "fold-const.h"
33 #include "calls.h"
34 #include "except.h"
35 #include "cfganal.h"
36 #include "cfgcleanup.h"
37 #include "tree-eh.h"
38 #include "gimple-iterator.h"
39 #include "tree-cfg.h"
40 #include "tree-into-ssa.h"
41 #include "tree-ssa.h"
42 #include "tree-inline.h"
43 #include "langhooks.h"
44 #include "cfgloop.h"
45 #include "gimple-low.h"
46 #include "stringpool.h"
47 #include "attribs.h"
48 #include "asan.h"
50 /* In some instances a tree and a gimple need to be stored in a same table,
51 i.e. in hash tables. This is a structure to do this. */
52 typedef union {tree *tp; tree t; gimple *g;} treemple;
54 /* Misc functions used in this file. */
56 /* Remember and lookup EH landing pad data for arbitrary statements.
57 Really this means any statement that could_throw_p. We could
58 stuff this information into the stmt_ann data structure, but:
60 (1) We absolutely rely on this information being kept until
61 we get to rtl. Once we're done with lowering here, if we lose
62 the information there's no way to recover it!
64 (2) There are many more statements that *cannot* throw as
65 compared to those that can. We should be saving some amount
66 of space by only allocating memory for those that can throw. */
68 /* Add statement T in function IFUN to landing pad NUM. */
70 static void
71 add_stmt_to_eh_lp_fn (struct function *ifun, gimple *t, int num)
73 gcc_assert (num != 0);
75 if (!get_eh_throw_stmt_table (ifun))
76 set_eh_throw_stmt_table (ifun, hash_map<gimple *, int>::create_ggc (31));
78 gcc_assert (!get_eh_throw_stmt_table (ifun)->put (t, num));
81 /* Add statement T in the current function (cfun) to EH landing pad NUM. */
83 void
84 add_stmt_to_eh_lp (gimple *t, int num)
86 add_stmt_to_eh_lp_fn (cfun, t, num);
89 /* Add statement T to the single EH landing pad in REGION. */
91 static void
92 record_stmt_eh_region (eh_region region, gimple *t)
94 if (region == NULL)
95 return;
96 if (region->type == ERT_MUST_NOT_THROW)
97 add_stmt_to_eh_lp_fn (cfun, t, -region->index);
98 else
100 eh_landing_pad lp = region->landing_pads;
101 if (lp == NULL)
102 lp = gen_eh_landing_pad (region);
103 else
104 gcc_assert (lp->next_lp == NULL);
105 add_stmt_to_eh_lp_fn (cfun, t, lp->index);
110 /* Remove statement T in function IFUN from its EH landing pad. */
112 bool
113 remove_stmt_from_eh_lp_fn (struct function *ifun, gimple *t)
115 if (!get_eh_throw_stmt_table (ifun))
116 return false;
118 if (!get_eh_throw_stmt_table (ifun)->get (t))
119 return false;
121 get_eh_throw_stmt_table (ifun)->remove (t);
122 return true;
126 /* Remove statement T in the current function (cfun) from its
127 EH landing pad. */
129 bool
130 remove_stmt_from_eh_lp (gimple *t)
132 return remove_stmt_from_eh_lp_fn (cfun, t);
135 /* Determine if statement T is inside an EH region in function IFUN.
136 Positive numbers indicate a landing pad index; negative numbers
137 indicate a MUST_NOT_THROW region index; zero indicates that the
138 statement is not recorded in the region table. */
141 lookup_stmt_eh_lp_fn (struct function *ifun, gimple *t)
143 if (ifun->eh->throw_stmt_table == NULL)
144 return 0;
146 int *lp_nr = ifun->eh->throw_stmt_table->get (t);
147 return lp_nr ? *lp_nr : 0;
150 /* Likewise, but always use the current function. */
153 lookup_stmt_eh_lp (gimple *t)
155 /* We can get called from initialized data when -fnon-call-exceptions
156 is on; prevent crash. */
157 if (!cfun)
158 return 0;
159 return lookup_stmt_eh_lp_fn (cfun, t);
162 /* First pass of EH node decomposition. Build up a tree of GIMPLE_TRY_FINALLY
163 nodes and LABEL_DECL nodes. We will use this during the second phase to
164 determine if a goto leaves the body of a TRY_FINALLY_EXPR node. */
166 struct finally_tree_node
168 /* When storing a GIMPLE_TRY, we have to record a gimple. However
169 when deciding whether a GOTO to a certain LABEL_DECL (which is a
170 tree) leaves the TRY block, its necessary to record a tree in
171 this field. Thus a treemple is used. */
172 treemple child;
173 gtry *parent;
176 /* Hashtable helpers. */
178 struct finally_tree_hasher : free_ptr_hash <finally_tree_node>
180 static inline hashval_t hash (const finally_tree_node *);
181 static inline bool equal (const finally_tree_node *,
182 const finally_tree_node *);
185 inline hashval_t
186 finally_tree_hasher::hash (const finally_tree_node *v)
188 return (intptr_t)v->child.t >> 4;
191 inline bool
192 finally_tree_hasher::equal (const finally_tree_node *v,
193 const finally_tree_node *c)
195 return v->child.t == c->child.t;
198 /* Note that this table is *not* marked GTY. It is short-lived. */
199 static hash_table<finally_tree_hasher> *finally_tree;
201 static void
202 record_in_finally_tree (treemple child, gtry *parent)
204 struct finally_tree_node *n;
205 finally_tree_node **slot;
207 n = XNEW (struct finally_tree_node);
208 n->child = child;
209 n->parent = parent;
211 slot = finally_tree->find_slot (n, INSERT);
212 gcc_assert (!*slot);
213 *slot = n;
216 static void
217 collect_finally_tree (gimple *stmt, gtry *region);
219 /* Go through the gimple sequence. Works with collect_finally_tree to
220 record all GIMPLE_LABEL and GIMPLE_TRY statements. */
222 static void
223 collect_finally_tree_1 (gimple_seq seq, gtry *region)
225 gimple_stmt_iterator gsi;
227 for (gsi = gsi_start (seq); !gsi_end_p (gsi); gsi_next (&gsi))
228 collect_finally_tree (gsi_stmt (gsi), region);
231 static void
232 collect_finally_tree (gimple *stmt, gtry *region)
234 treemple temp;
236 switch (gimple_code (stmt))
238 case GIMPLE_LABEL:
239 temp.t = gimple_label_label (as_a <glabel *> (stmt));
240 record_in_finally_tree (temp, region);
241 break;
243 case GIMPLE_TRY:
244 if (gimple_try_kind (stmt) == GIMPLE_TRY_FINALLY)
246 temp.g = stmt;
247 record_in_finally_tree (temp, region);
248 collect_finally_tree_1 (gimple_try_eval (stmt),
249 as_a <gtry *> (stmt));
250 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
252 else if (gimple_try_kind (stmt) == GIMPLE_TRY_CATCH)
254 collect_finally_tree_1 (gimple_try_eval (stmt), region);
255 collect_finally_tree_1 (gimple_try_cleanup (stmt), region);
257 break;
259 case GIMPLE_CATCH:
260 collect_finally_tree_1 (gimple_catch_handler (
261 as_a <gcatch *> (stmt)),
262 region);
263 break;
265 case GIMPLE_EH_FILTER:
266 collect_finally_tree_1 (gimple_eh_filter_failure (stmt), region);
267 break;
269 case GIMPLE_EH_ELSE:
271 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
272 collect_finally_tree_1 (gimple_eh_else_n_body (eh_else_stmt), region);
273 collect_finally_tree_1 (gimple_eh_else_e_body (eh_else_stmt), region);
275 break;
277 default:
278 /* A type, a decl, or some kind of statement that we're not
279 interested in. Don't walk them. */
280 break;
285 /* Use the finally tree to determine if a jump from START to TARGET
286 would leave the try_finally node that START lives in. */
288 static bool
289 outside_finally_tree (treemple start, gimple *target)
291 struct finally_tree_node n, *p;
295 n.child = start;
296 p = finally_tree->find (&n);
297 if (!p)
298 return true;
299 start.g = p->parent;
301 while (start.g != target);
303 return false;
306 /* Second pass of EH node decomposition. Actually transform the GIMPLE_TRY
307 nodes into a set of gotos, magic labels, and eh regions.
308 The eh region creation is straight-forward, but frobbing all the gotos
309 and such into shape isn't. */
311 /* The sequence into which we record all EH stuff. This will be
312 placed at the end of the function when we're all done. */
313 static gimple_seq eh_seq;
315 /* Record whether an EH region contains something that can throw,
316 indexed by EH region number. */
317 static bitmap eh_region_may_contain_throw_map;
319 /* The GOTO_QUEUE is an array of GIMPLE_GOTO and GIMPLE_RETURN
320 statements that are seen to escape this GIMPLE_TRY_FINALLY node.
321 The idea is to record a gimple statement for everything except for
322 the conditionals, which get their labels recorded. Since labels are
323 of type 'tree', we need this node to store both gimple and tree
324 objects. REPL_STMT is the sequence used to replace the goto/return
325 statement. CONT_STMT is used to store the statement that allows
326 the return/goto to jump to the original destination. */
328 struct goto_queue_node
330 treemple stmt;
331 location_t location;
332 gimple_seq repl_stmt;
333 gimple *cont_stmt;
334 int index;
335 /* This is used when index >= 0 to indicate that stmt is a label (as
336 opposed to a goto stmt). */
337 int is_label;
340 /* State of the world while lowering. */
342 struct leh_state
344 /* What's "current" while constructing the eh region tree. These
345 correspond to variables of the same name in cfun->eh, which we
346 don't have easy access to. */
347 eh_region cur_region;
349 /* What's "current" for the purposes of __builtin_eh_pointer. For
350 a CATCH, this is the associated TRY. For an EH_FILTER, this is
351 the associated ALLOWED_EXCEPTIONS, etc. */
352 eh_region ehp_region;
354 /* Processing of TRY_FINALLY requires a bit more state. This is
355 split out into a separate structure so that we don't have to
356 copy so much when processing other nodes. */
357 struct leh_tf_state *tf;
360 struct leh_tf_state
362 /* Pointer to the GIMPLE_TRY_FINALLY node under discussion. The
363 try_finally_expr is the original GIMPLE_TRY_FINALLY. We need to retain
364 this so that outside_finally_tree can reliably reference the tree used
365 in the collect_finally_tree data structures. */
366 gtry *try_finally_expr;
367 gtry *top_p;
369 /* While lowering a top_p usually it is expanded into multiple statements,
370 thus we need the following field to store them. */
371 gimple_seq top_p_seq;
373 /* The state outside this try_finally node. */
374 struct leh_state *outer;
376 /* The exception region created for it. */
377 eh_region region;
379 /* The goto queue. */
380 struct goto_queue_node *goto_queue;
381 size_t goto_queue_size;
382 size_t goto_queue_active;
384 /* Pointer map to help in searching goto_queue when it is large. */
385 hash_map<gimple *, goto_queue_node *> *goto_queue_map;
387 /* The set of unique labels seen as entries in the goto queue. */
388 vec<tree> dest_array;
390 /* A label to be added at the end of the completed transformed
391 sequence. It will be set if may_fallthru was true *at one time*,
392 though subsequent transformations may have cleared that flag. */
393 tree fallthru_label;
395 /* True if it is possible to fall out the bottom of the try block.
396 Cleared if the fallthru is converted to a goto. */
397 bool may_fallthru;
399 /* True if any entry in goto_queue is a GIMPLE_RETURN. */
400 bool may_return;
402 /* True if the finally block can receive an exception edge.
403 Cleared if the exception case is handled by code duplication. */
404 bool may_throw;
407 static gimple_seq lower_eh_must_not_throw (struct leh_state *, gtry *);
409 /* Search for STMT in the goto queue. Return the replacement,
410 or null if the statement isn't in the queue. */
412 #define LARGE_GOTO_QUEUE 20
414 static void lower_eh_constructs_1 (struct leh_state *state, gimple_seq *seq);
416 static gimple_seq
417 find_goto_replacement (struct leh_tf_state *tf, treemple stmt)
419 unsigned int i;
421 if (tf->goto_queue_active < LARGE_GOTO_QUEUE)
423 for (i = 0; i < tf->goto_queue_active; i++)
424 if ( tf->goto_queue[i].stmt.g == stmt.g)
425 return tf->goto_queue[i].repl_stmt;
426 return NULL;
429 /* If we have a large number of entries in the goto_queue, create a
430 pointer map and use that for searching. */
432 if (!tf->goto_queue_map)
434 tf->goto_queue_map = new hash_map<gimple *, goto_queue_node *>;
435 for (i = 0; i < tf->goto_queue_active; i++)
437 bool existed = tf->goto_queue_map->put (tf->goto_queue[i].stmt.g,
438 &tf->goto_queue[i]);
439 gcc_assert (!existed);
443 goto_queue_node **slot = tf->goto_queue_map->get (stmt.g);
444 if (slot != NULL)
445 return ((*slot)->repl_stmt);
447 return NULL;
450 /* A subroutine of replace_goto_queue_1. Handles the sub-clauses of a
451 lowered GIMPLE_COND. If, by chance, the replacement is a simple goto,
452 then we can just splat it in, otherwise we add the new stmts immediately
453 after the GIMPLE_COND and redirect. */
455 static void
456 replace_goto_queue_cond_clause (tree *tp, struct leh_tf_state *tf,
457 gimple_stmt_iterator *gsi)
459 tree label;
460 gimple_seq new_seq;
461 treemple temp;
462 location_t loc = gimple_location (gsi_stmt (*gsi));
464 temp.tp = tp;
465 new_seq = find_goto_replacement (tf, temp);
466 if (!new_seq)
467 return;
469 if (gimple_seq_singleton_p (new_seq)
470 && gimple_code (gimple_seq_first_stmt (new_seq)) == GIMPLE_GOTO)
472 *tp = gimple_goto_dest (gimple_seq_first_stmt (new_seq));
473 return;
476 label = create_artificial_label (loc);
477 /* Set the new label for the GIMPLE_COND */
478 *tp = label;
480 gsi_insert_after (gsi, gimple_build_label (label), GSI_CONTINUE_LINKING);
481 gsi_insert_seq_after (gsi, gimple_seq_copy (new_seq), GSI_CONTINUE_LINKING);
484 /* The real work of replace_goto_queue. Returns with TSI updated to
485 point to the next statement. */
487 static void replace_goto_queue_stmt_list (gimple_seq *, struct leh_tf_state *);
489 static void
490 replace_goto_queue_1 (gimple *stmt, struct leh_tf_state *tf,
491 gimple_stmt_iterator *gsi)
493 gimple_seq seq;
494 treemple temp;
495 temp.g = NULL;
497 switch (gimple_code (stmt))
499 case GIMPLE_GOTO:
500 case GIMPLE_RETURN:
501 temp.g = stmt;
502 seq = find_goto_replacement (tf, temp);
503 if (seq)
505 gsi_insert_seq_before (gsi, gimple_seq_copy (seq), GSI_SAME_STMT);
506 gsi_remove (gsi, false);
507 return;
509 break;
511 case GIMPLE_COND:
512 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 2), tf, gsi);
513 replace_goto_queue_cond_clause (gimple_op_ptr (stmt, 3), tf, gsi);
514 break;
516 case GIMPLE_TRY:
517 replace_goto_queue_stmt_list (gimple_try_eval_ptr (stmt), tf);
518 replace_goto_queue_stmt_list (gimple_try_cleanup_ptr (stmt), tf);
519 break;
520 case GIMPLE_CATCH:
521 replace_goto_queue_stmt_list (gimple_catch_handler_ptr (
522 as_a <gcatch *> (stmt)),
523 tf);
524 break;
525 case GIMPLE_EH_FILTER:
526 replace_goto_queue_stmt_list (gimple_eh_filter_failure_ptr (stmt), tf);
527 break;
528 case GIMPLE_EH_ELSE:
530 geh_else *eh_else_stmt = as_a <geh_else *> (stmt);
531 replace_goto_queue_stmt_list (gimple_eh_else_n_body_ptr (eh_else_stmt),
532 tf);
533 replace_goto_queue_stmt_list (gimple_eh_else_e_body_ptr (eh_else_stmt),
534 tf);
536 break;
538 default:
539 /* These won't have gotos in them. */
540 break;
543 gsi_next (gsi);
546 /* A subroutine of replace_goto_queue. Handles GIMPLE_SEQ. */
548 static void
549 replace_goto_queue_stmt_list (gimple_seq *seq, struct leh_tf_state *tf)
551 gimple_stmt_iterator gsi = gsi_start (*seq);
553 while (!gsi_end_p (gsi))
554 replace_goto_queue_1 (gsi_stmt (gsi), tf, &gsi);
557 /* Replace all goto queue members. */
559 static void
560 replace_goto_queue (struct leh_tf_state *tf)
562 if (tf->goto_queue_active == 0)
563 return;
564 replace_goto_queue_stmt_list (&tf->top_p_seq, tf);
565 replace_goto_queue_stmt_list (&eh_seq, tf);
568 /* Add a new record to the goto queue contained in TF. NEW_STMT is the
569 data to be added, IS_LABEL indicates whether NEW_STMT is a label or
570 a gimple return. */
572 static void
573 record_in_goto_queue (struct leh_tf_state *tf,
574 treemple new_stmt,
575 int index,
576 bool is_label,
577 location_t location)
579 size_t active, size;
580 struct goto_queue_node *q;
582 gcc_assert (!tf->goto_queue_map);
584 active = tf->goto_queue_active;
585 size = tf->goto_queue_size;
586 if (active >= size)
588 size = (size ? size * 2 : 32);
589 tf->goto_queue_size = size;
590 tf->goto_queue
591 = XRESIZEVEC (struct goto_queue_node, tf->goto_queue, size);
594 q = &tf->goto_queue[active];
595 tf->goto_queue_active = active + 1;
597 memset (q, 0, sizeof (*q));
598 q->stmt = new_stmt;
599 q->index = index;
600 q->location = location;
601 q->is_label = is_label;
604 /* Record the LABEL label in the goto queue contained in TF.
605 TF is not null. */
607 static void
608 record_in_goto_queue_label (struct leh_tf_state *tf, treemple stmt, tree label,
609 location_t location)
611 int index;
612 treemple temp, new_stmt;
614 if (!label)
615 return;
617 /* Computed and non-local gotos do not get processed. Given
618 their nature we can neither tell whether we've escaped the
619 finally block nor redirect them if we knew. */
620 if (TREE_CODE (label) != LABEL_DECL)
621 return;
623 /* No need to record gotos that don't leave the try block. */
624 temp.t = label;
625 if (!outside_finally_tree (temp, tf->try_finally_expr))
626 return;
628 if (! tf->dest_array.exists ())
630 tf->dest_array.create (10);
631 tf->dest_array.quick_push (label);
632 index = 0;
634 else
636 int n = tf->dest_array.length ();
637 for (index = 0; index < n; ++index)
638 if (tf->dest_array[index] == label)
639 break;
640 if (index == n)
641 tf->dest_array.safe_push (label);
644 /* In the case of a GOTO we want to record the destination label,
645 since with a GIMPLE_COND we have an easy access to the then/else
646 labels. */
647 new_stmt = stmt;
648 record_in_goto_queue (tf, new_stmt, index, true, location);
651 /* For any GIMPLE_GOTO or GIMPLE_RETURN, decide whether it leaves a try_finally
652 node, and if so record that fact in the goto queue associated with that
653 try_finally node. */
655 static void
656 maybe_record_in_goto_queue (struct leh_state *state, gimple *stmt)
658 struct leh_tf_state *tf = state->tf;
659 treemple new_stmt;
661 if (!tf)
662 return;
664 switch (gimple_code (stmt))
666 case GIMPLE_COND:
668 gcond *cond_stmt = as_a <gcond *> (stmt);
669 new_stmt.tp = gimple_op_ptr (cond_stmt, 2);
670 record_in_goto_queue_label (tf, new_stmt,
671 gimple_cond_true_label (cond_stmt),
672 EXPR_LOCATION (*new_stmt.tp));
673 new_stmt.tp = gimple_op_ptr (cond_stmt, 3);
674 record_in_goto_queue_label (tf, new_stmt,
675 gimple_cond_false_label (cond_stmt),
676 EXPR_LOCATION (*new_stmt.tp));
678 break;
679 case GIMPLE_GOTO:
680 new_stmt.g = stmt;
681 record_in_goto_queue_label (tf, new_stmt, gimple_goto_dest (stmt),
682 gimple_location (stmt));
683 break;
685 case GIMPLE_RETURN:
686 tf->may_return = true;
687 new_stmt.g = stmt;
688 record_in_goto_queue (tf, new_stmt, -1, false, gimple_location (stmt));
689 break;
691 default:
692 gcc_unreachable ();
697 #if CHECKING_P
698 /* We do not process GIMPLE_SWITCHes for now. As long as the original source
699 was in fact structured, and we've not yet done jump threading, then none
700 of the labels will leave outer GIMPLE_TRY_FINALLY nodes. Verify this. */
702 static void
703 verify_norecord_switch_expr (struct leh_state *state,
704 gswitch *switch_expr)
706 struct leh_tf_state *tf = state->tf;
707 size_t i, n;
709 if (!tf)
710 return;
712 n = gimple_switch_num_labels (switch_expr);
714 for (i = 0; i < n; ++i)
716 treemple temp;
717 tree lab = CASE_LABEL (gimple_switch_label (switch_expr, i));
718 temp.t = lab;
719 gcc_assert (!outside_finally_tree (temp, tf->try_finally_expr));
722 #else
723 #define verify_norecord_switch_expr(state, switch_expr)
724 #endif
726 /* Redirect a RETURN_EXPR pointed to by Q to FINLAB. If MOD is
727 non-null, insert it before the new branch. */
729 static void
730 do_return_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod)
732 gimple *x;
734 /* In the case of a return, the queue node must be a gimple statement. */
735 gcc_assert (!q->is_label);
737 /* Note that the return value may have already been computed, e.g.,
739 int x;
740 int foo (void)
742 x = 0;
743 try {
744 return x;
745 } finally {
746 x++;
750 should return 0, not 1. We don't have to do anything to make
751 this happens because the return value has been placed in the
752 RESULT_DECL already. */
754 q->cont_stmt = q->stmt.g;
756 if (mod)
757 gimple_seq_add_seq (&q->repl_stmt, mod);
759 x = gimple_build_goto (finlab);
760 gimple_set_location (x, q->location);
761 gimple_seq_add_stmt (&q->repl_stmt, x);
764 /* Similar, but easier, for GIMPLE_GOTO. */
766 static void
767 do_goto_redirection (struct goto_queue_node *q, tree finlab, gimple_seq mod,
768 struct leh_tf_state *tf)
770 ggoto *x;
772 gcc_assert (q->is_label);
774 q->cont_stmt = gimple_build_goto (tf->dest_array[q->index]);
776 if (mod)
777 gimple_seq_add_seq (&q->repl_stmt, mod);
779 x = gimple_build_goto (finlab);
780 gimple_set_location (x, q->location);
781 gimple_seq_add_stmt (&q->repl_stmt, x);
784 /* Emit a standard landing pad sequence into SEQ for REGION. */
786 static void
787 emit_post_landing_pad (gimple_seq *seq, eh_region region)
789 eh_landing_pad lp = region->landing_pads;
790 glabel *x;
792 if (lp == NULL)
793 lp = gen_eh_landing_pad (region);
795 lp->post_landing_pad = create_artificial_label (UNKNOWN_LOCATION);
796 EH_LANDING_PAD_NR (lp->post_landing_pad) = lp->index;
798 x = gimple_build_label (lp->post_landing_pad);
799 gimple_seq_add_stmt (seq, x);
802 /* Emit a RESX statement into SEQ for REGION. */
804 static void
805 emit_resx (gimple_seq *seq, eh_region region)
807 gresx *x = gimple_build_resx (region->index);
808 gimple_seq_add_stmt (seq, x);
809 if (region->outer)
810 record_stmt_eh_region (region->outer, x);
813 /* Emit an EH_DISPATCH statement into SEQ for REGION. */
815 static void
816 emit_eh_dispatch (gimple_seq *seq, eh_region region)
818 geh_dispatch *x = gimple_build_eh_dispatch (region->index);
819 gimple_seq_add_stmt (seq, x);
822 /* Note that the current EH region may contain a throw, or a
823 call to a function which itself may contain a throw. */
825 static void
826 note_eh_region_may_contain_throw (eh_region region)
828 while (bitmap_set_bit (eh_region_may_contain_throw_map, region->index))
830 if (region->type == ERT_MUST_NOT_THROW)
831 break;
832 region = region->outer;
833 if (region == NULL)
834 break;
838 /* Check if REGION has been marked as containing a throw. If REGION is
839 NULL, this predicate is false. */
841 static inline bool
842 eh_region_may_contain_throw (eh_region r)
844 return r && bitmap_bit_p (eh_region_may_contain_throw_map, r->index);
847 /* We want to transform
848 try { body; } catch { stuff; }
850 normal_sequence:
851 body;
852 over:
853 eh_sequence:
854 landing_pad:
855 stuff;
856 goto over;
858 TP is a GIMPLE_TRY node. REGION is the region whose post_landing_pad
859 should be placed before the second operand, or NULL. OVER is
860 an existing label that should be put at the exit, or NULL. */
862 static gimple_seq
863 frob_into_branch_around (gtry *tp, eh_region region, tree over)
865 gimple *x;
866 gimple_seq cleanup, result;
867 location_t loc = gimple_location (tp);
869 cleanup = gimple_try_cleanup (tp);
870 result = gimple_try_eval (tp);
872 if (region)
873 emit_post_landing_pad (&eh_seq, region);
875 if (gimple_seq_may_fallthru (cleanup))
877 if (!over)
878 over = create_artificial_label (loc);
879 x = gimple_build_goto (over);
880 gimple_set_location (x, loc);
881 gimple_seq_add_stmt (&cleanup, x);
883 gimple_seq_add_seq (&eh_seq, cleanup);
885 if (over)
887 x = gimple_build_label (over);
888 gimple_seq_add_stmt (&result, x);
890 return result;
893 /* A subroutine of lower_try_finally. Duplicate the tree rooted at T.
894 Make sure to record all new labels found. */
896 static gimple_seq
897 lower_try_finally_dup_block (gimple_seq seq, struct leh_state *outer_state,
898 location_t loc)
900 gtry *region = NULL;
901 gimple_seq new_seq;
902 gimple_stmt_iterator gsi;
904 new_seq = copy_gimple_seq_and_replace_locals (seq);
906 for (gsi = gsi_start (new_seq); !gsi_end_p (gsi); gsi_next (&gsi))
908 gimple *stmt = gsi_stmt (gsi);
909 /* We duplicate __builtin_stack_restore at -O0 in the hope of eliminating
910 it on the EH paths. When it is not eliminated, make it transparent in
911 the debug info. */
912 if (gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
913 gimple_set_location (stmt, UNKNOWN_LOCATION);
914 else if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
916 tree block = gimple_block (stmt);
917 gimple_set_location (stmt, loc);
918 gimple_set_block (stmt, block);
922 if (outer_state->tf)
923 region = outer_state->tf->try_finally_expr;
924 collect_finally_tree_1 (new_seq, region);
926 return new_seq;
929 /* A subroutine of lower_try_finally. Create a fallthru label for
930 the given try_finally state. The only tricky bit here is that
931 we have to make sure to record the label in our outer context. */
933 static tree
934 lower_try_finally_fallthru_label (struct leh_tf_state *tf)
936 tree label = tf->fallthru_label;
937 treemple temp;
939 if (!label)
941 label = create_artificial_label (gimple_location (tf->try_finally_expr));
942 tf->fallthru_label = label;
943 if (tf->outer->tf)
945 temp.t = label;
946 record_in_finally_tree (temp, tf->outer->tf->try_finally_expr);
949 return label;
952 /* A subroutine of lower_try_finally. If FINALLY consits of a
953 GIMPLE_EH_ELSE node, return it. */
955 static inline geh_else *
956 get_eh_else (gimple_seq finally)
958 gimple *x = gimple_seq_first_stmt (finally);
959 if (gimple_code (x) == GIMPLE_EH_ELSE)
961 gcc_assert (gimple_seq_singleton_p (finally));
962 return as_a <geh_else *> (x);
964 return NULL;
967 /* A subroutine of lower_try_finally. If the eh_protect_cleanup_actions
968 langhook returns non-null, then the language requires that the exception
969 path out of a try_finally be treated specially. To wit: the code within
970 the finally block may not itself throw an exception. We have two choices
971 here. First we can duplicate the finally block and wrap it in a
972 must_not_throw region. Second, we can generate code like
974 try {
975 finally_block;
976 } catch {
977 if (fintmp == eh_edge)
978 protect_cleanup_actions;
981 where "fintmp" is the temporary used in the switch statement generation
982 alternative considered below. For the nonce, we always choose the first
983 option.
985 THIS_STATE may be null if this is a try-cleanup, not a try-finally. */
987 static void
988 honor_protect_cleanup_actions (struct leh_state *outer_state,
989 struct leh_state *this_state,
990 struct leh_tf_state *tf)
992 gimple_seq finally = gimple_try_cleanup (tf->top_p);
994 /* EH_ELSE doesn't come from user code; only compiler generated stuff.
995 It does need to be handled here, so as to separate the (different)
996 EH path from the normal path. But we should not attempt to wrap
997 it with a must-not-throw node (which indeed gets in the way). */
998 if (geh_else *eh_else = get_eh_else (finally))
1000 gimple_try_set_cleanup (tf->top_p, gimple_eh_else_n_body (eh_else));
1001 finally = gimple_eh_else_e_body (eh_else);
1003 /* Let the ELSE see the exception that's being processed. */
1004 eh_region save_ehp = this_state->ehp_region;
1005 this_state->ehp_region = this_state->cur_region;
1006 lower_eh_constructs_1 (this_state, &finally);
1007 this_state->ehp_region = save_ehp;
1009 else
1011 /* First check for nothing to do. */
1012 if (lang_hooks.eh_protect_cleanup_actions == NULL)
1013 return;
1014 tree actions = lang_hooks.eh_protect_cleanup_actions ();
1015 if (actions == NULL)
1016 return;
1018 if (this_state)
1019 finally = lower_try_finally_dup_block (finally, outer_state,
1020 gimple_location (tf->try_finally_expr));
1022 /* If this cleanup consists of a TRY_CATCH_EXPR with TRY_CATCH_IS_CLEANUP
1023 set, the handler of the TRY_CATCH_EXPR is another cleanup which ought
1024 to be in an enclosing scope, but needs to be implemented at this level
1025 to avoid a nesting violation (see wrap_temporary_cleanups in
1026 cp/decl.c). Since it's logically at an outer level, we should call
1027 terminate before we get to it, so strip it away before adding the
1028 MUST_NOT_THROW filter. */
1029 gimple_stmt_iterator gsi = gsi_start (finally);
1030 gimple *x = gsi_stmt (gsi);
1031 if (gimple_code (x) == GIMPLE_TRY
1032 && gimple_try_kind (x) == GIMPLE_TRY_CATCH
1033 && gimple_try_catch_is_cleanup (x))
1035 gsi_insert_seq_before (&gsi, gimple_try_eval (x), GSI_SAME_STMT);
1036 gsi_remove (&gsi, false);
1039 /* Wrap the block with protect_cleanup_actions as the action. */
1040 geh_mnt *eh_mnt = gimple_build_eh_must_not_throw (actions);
1041 gtry *try_stmt = gimple_build_try (finally,
1042 gimple_seq_alloc_with_stmt (eh_mnt),
1043 GIMPLE_TRY_CATCH);
1044 finally = lower_eh_must_not_throw (outer_state, try_stmt);
1047 /* Drop all of this into the exception sequence. */
1048 emit_post_landing_pad (&eh_seq, tf->region);
1049 gimple_seq_add_seq (&eh_seq, finally);
1050 if (gimple_seq_may_fallthru (finally))
1051 emit_resx (&eh_seq, tf->region);
1053 /* Having now been handled, EH isn't to be considered with
1054 the rest of the outgoing edges. */
1055 tf->may_throw = false;
1058 /* A subroutine of lower_try_finally. We have determined that there is
1059 no fallthru edge out of the finally block. This means that there is
1060 no outgoing edge corresponding to any incoming edge. Restructure the
1061 try_finally node for this special case. */
1063 static void
1064 lower_try_finally_nofallthru (struct leh_state *state,
1065 struct leh_tf_state *tf)
1067 tree lab;
1068 gimple *x;
1069 geh_else *eh_else;
1070 gimple_seq finally;
1071 struct goto_queue_node *q, *qe;
1073 lab = create_artificial_label (gimple_location (tf->try_finally_expr));
1075 /* We expect that tf->top_p is a GIMPLE_TRY. */
1076 finally = gimple_try_cleanup (tf->top_p);
1077 tf->top_p_seq = gimple_try_eval (tf->top_p);
1079 x = gimple_build_label (lab);
1080 gimple_seq_add_stmt (&tf->top_p_seq, x);
1082 q = tf->goto_queue;
1083 qe = q + tf->goto_queue_active;
1084 for (; q < qe; ++q)
1085 if (q->index < 0)
1086 do_return_redirection (q, lab, NULL);
1087 else
1088 do_goto_redirection (q, lab, NULL, tf);
1090 replace_goto_queue (tf);
1092 /* Emit the finally block into the stream. Lower EH_ELSE at this time. */
1093 eh_else = get_eh_else (finally);
1094 if (eh_else)
1096 finally = gimple_eh_else_n_body (eh_else);
1097 lower_eh_constructs_1 (state, &finally);
1098 gimple_seq_add_seq (&tf->top_p_seq, finally);
1100 if (tf->may_throw)
1102 finally = gimple_eh_else_e_body (eh_else);
1103 lower_eh_constructs_1 (state, &finally);
1105 emit_post_landing_pad (&eh_seq, tf->region);
1106 gimple_seq_add_seq (&eh_seq, finally);
1109 else
1111 lower_eh_constructs_1 (state, &finally);
1112 gimple_seq_add_seq (&tf->top_p_seq, finally);
1114 if (tf->may_throw)
1116 emit_post_landing_pad (&eh_seq, tf->region);
1118 x = gimple_build_goto (lab);
1119 gimple_set_location (x, gimple_location (tf->try_finally_expr));
1120 gimple_seq_add_stmt (&eh_seq, x);
1125 /* A subroutine of lower_try_finally. We have determined that there is
1126 exactly one destination of the finally block. Restructure the
1127 try_finally node for this special case. */
1129 static void
1130 lower_try_finally_onedest (struct leh_state *state, struct leh_tf_state *tf)
1132 struct goto_queue_node *q, *qe;
1133 geh_else *eh_else;
1134 glabel *label_stmt;
1135 gimple *x;
1136 gimple_seq finally;
1137 gimple_stmt_iterator gsi;
1138 tree finally_label;
1139 location_t loc = gimple_location (tf->try_finally_expr);
1141 finally = gimple_try_cleanup (tf->top_p);
1142 tf->top_p_seq = gimple_try_eval (tf->top_p);
1144 /* Since there's only one destination, and the destination edge can only
1145 either be EH or non-EH, that implies that all of our incoming edges
1146 are of the same type. Therefore we can lower EH_ELSE immediately. */
1147 eh_else = get_eh_else (finally);
1148 if (eh_else)
1150 if (tf->may_throw)
1151 finally = gimple_eh_else_e_body (eh_else);
1152 else
1153 finally = gimple_eh_else_n_body (eh_else);
1156 lower_eh_constructs_1 (state, &finally);
1158 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1160 gimple *stmt = gsi_stmt (gsi);
1161 if (LOCATION_LOCUS (gimple_location (stmt)) == UNKNOWN_LOCATION)
1163 tree block = gimple_block (stmt);
1164 gimple_set_location (stmt, gimple_location (tf->try_finally_expr));
1165 gimple_set_block (stmt, block);
1169 if (tf->may_throw)
1171 /* Only reachable via the exception edge. Add the given label to
1172 the head of the FINALLY block. Append a RESX at the end. */
1173 emit_post_landing_pad (&eh_seq, tf->region);
1174 gimple_seq_add_seq (&eh_seq, finally);
1175 emit_resx (&eh_seq, tf->region);
1176 return;
1179 if (tf->may_fallthru)
1181 /* Only reachable via the fallthru edge. Do nothing but let
1182 the two blocks run together; we'll fall out the bottom. */
1183 gimple_seq_add_seq (&tf->top_p_seq, finally);
1184 return;
1187 finally_label = create_artificial_label (loc);
1188 label_stmt = gimple_build_label (finally_label);
1189 gimple_seq_add_stmt (&tf->top_p_seq, label_stmt);
1191 gimple_seq_add_seq (&tf->top_p_seq, finally);
1193 q = tf->goto_queue;
1194 qe = q + tf->goto_queue_active;
1196 if (tf->may_return)
1198 /* Reachable by return expressions only. Redirect them. */
1199 for (; q < qe; ++q)
1200 do_return_redirection (q, finally_label, NULL);
1201 replace_goto_queue (tf);
1203 else
1205 /* Reachable by goto expressions only. Redirect them. */
1206 for (; q < qe; ++q)
1207 do_goto_redirection (q, finally_label, NULL, tf);
1208 replace_goto_queue (tf);
1210 if (tf->dest_array[0] == tf->fallthru_label)
1212 /* Reachable by goto to fallthru label only. Redirect it
1213 to the new label (already created, sadly), and do not
1214 emit the final branch out, or the fallthru label. */
1215 tf->fallthru_label = NULL;
1216 return;
1220 /* Place the original return/goto to the original destination
1221 immediately after the finally block. */
1222 x = tf->goto_queue[0].cont_stmt;
1223 gimple_seq_add_stmt (&tf->top_p_seq, x);
1224 maybe_record_in_goto_queue (state, x);
1227 /* A subroutine of lower_try_finally. There are multiple edges incoming
1228 and outgoing from the finally block. Implement this by duplicating the
1229 finally block for every destination. */
1231 static void
1232 lower_try_finally_copy (struct leh_state *state, struct leh_tf_state *tf)
1234 gimple_seq finally;
1235 gimple_seq new_stmt;
1236 gimple_seq seq;
1237 gimple *x;
1238 geh_else *eh_else;
1239 tree tmp;
1240 location_t tf_loc = gimple_location (tf->try_finally_expr);
1242 finally = gimple_try_cleanup (tf->top_p);
1244 /* Notice EH_ELSE, and simplify some of the remaining code
1245 by considering FINALLY to be the normal return path only. */
1246 eh_else = get_eh_else (finally);
1247 if (eh_else)
1248 finally = gimple_eh_else_n_body (eh_else);
1250 tf->top_p_seq = gimple_try_eval (tf->top_p);
1251 new_stmt = NULL;
1253 if (tf->may_fallthru)
1255 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1256 lower_eh_constructs_1 (state, &seq);
1257 gimple_seq_add_seq (&new_stmt, seq);
1259 tmp = lower_try_finally_fallthru_label (tf);
1260 x = gimple_build_goto (tmp);
1261 gimple_set_location (x, tf_loc);
1262 gimple_seq_add_stmt (&new_stmt, x);
1265 if (tf->may_throw)
1267 /* We don't need to copy the EH path of EH_ELSE,
1268 since it is only emitted once. */
1269 if (eh_else)
1270 seq = gimple_eh_else_e_body (eh_else);
1271 else
1272 seq = lower_try_finally_dup_block (finally, state, tf_loc);
1273 lower_eh_constructs_1 (state, &seq);
1275 emit_post_landing_pad (&eh_seq, tf->region);
1276 gimple_seq_add_seq (&eh_seq, seq);
1277 emit_resx (&eh_seq, tf->region);
1280 if (tf->goto_queue)
1282 struct goto_queue_node *q, *qe;
1283 int return_index, index;
1284 struct labels_s
1286 struct goto_queue_node *q;
1287 tree label;
1288 } *labels;
1290 return_index = tf->dest_array.length ();
1291 labels = XCNEWVEC (struct labels_s, return_index + 1);
1293 q = tf->goto_queue;
1294 qe = q + tf->goto_queue_active;
1295 for (; q < qe; q++)
1297 index = q->index < 0 ? return_index : q->index;
1299 if (!labels[index].q)
1300 labels[index].q = q;
1303 for (index = 0; index < return_index + 1; index++)
1305 tree lab;
1307 q = labels[index].q;
1308 if (! q)
1309 continue;
1311 lab = labels[index].label
1312 = create_artificial_label (tf_loc);
1314 if (index == return_index)
1315 do_return_redirection (q, lab, NULL);
1316 else
1317 do_goto_redirection (q, lab, NULL, tf);
1319 x = gimple_build_label (lab);
1320 gimple_seq_add_stmt (&new_stmt, x);
1322 seq = lower_try_finally_dup_block (finally, state, q->location);
1323 lower_eh_constructs_1 (state, &seq);
1324 gimple_seq_add_seq (&new_stmt, seq);
1326 gimple_seq_add_stmt (&new_stmt, q->cont_stmt);
1327 maybe_record_in_goto_queue (state, q->cont_stmt);
1330 for (q = tf->goto_queue; q < qe; q++)
1332 tree lab;
1334 index = q->index < 0 ? return_index : q->index;
1336 if (labels[index].q == q)
1337 continue;
1339 lab = labels[index].label;
1341 if (index == return_index)
1342 do_return_redirection (q, lab, NULL);
1343 else
1344 do_goto_redirection (q, lab, NULL, tf);
1347 replace_goto_queue (tf);
1348 free (labels);
1351 /* Need to link new stmts after running replace_goto_queue due
1352 to not wanting to process the same goto stmts twice. */
1353 gimple_seq_add_seq (&tf->top_p_seq, new_stmt);
1356 /* A subroutine of lower_try_finally. There are multiple edges incoming
1357 and outgoing from the finally block. Implement this by instrumenting
1358 each incoming edge and creating a switch statement at the end of the
1359 finally block that branches to the appropriate destination. */
1361 static void
1362 lower_try_finally_switch (struct leh_state *state, struct leh_tf_state *tf)
1364 struct goto_queue_node *q, *qe;
1365 tree finally_tmp, finally_label;
1366 int return_index, eh_index, fallthru_index;
1367 int nlabels, ndests, j, last_case_index;
1368 tree last_case;
1369 auto_vec<tree> case_label_vec;
1370 gimple_seq switch_body = NULL;
1371 gimple *x;
1372 geh_else *eh_else;
1373 tree tmp;
1374 gimple *switch_stmt;
1375 gimple_seq finally;
1376 hash_map<tree, gimple *> *cont_map = NULL;
1377 /* The location of the TRY_FINALLY stmt. */
1378 location_t tf_loc = gimple_location (tf->try_finally_expr);
1379 /* The location of the finally block. */
1380 location_t finally_loc;
1382 finally = gimple_try_cleanup (tf->top_p);
1383 eh_else = get_eh_else (finally);
1385 /* Mash the TRY block to the head of the chain. */
1386 tf->top_p_seq = gimple_try_eval (tf->top_p);
1388 /* The location of the finally is either the last stmt in the finally
1389 block or the location of the TRY_FINALLY itself. */
1390 x = gimple_seq_last_stmt (finally);
1391 finally_loc = x ? gimple_location (x) : tf_loc;
1393 /* Prepare for switch statement generation. */
1394 nlabels = tf->dest_array.length ();
1395 return_index = nlabels;
1396 eh_index = return_index + tf->may_return;
1397 fallthru_index = eh_index + (tf->may_throw && !eh_else);
1398 ndests = fallthru_index + tf->may_fallthru;
1400 finally_tmp = create_tmp_var (integer_type_node, "finally_tmp");
1401 finally_label = create_artificial_label (finally_loc);
1403 /* We use vec::quick_push on case_label_vec throughout this function,
1404 since we know the size in advance and allocate precisely as muce
1405 space as needed. */
1406 case_label_vec.create (ndests);
1407 last_case = NULL;
1408 last_case_index = 0;
1410 /* Begin inserting code for getting to the finally block. Things
1411 are done in this order to correspond to the sequence the code is
1412 laid out. */
1414 if (tf->may_fallthru)
1416 x = gimple_build_assign (finally_tmp,
1417 build_int_cst (integer_type_node,
1418 fallthru_index));
1419 gimple_set_location (x, finally_loc);
1420 gimple_seq_add_stmt (&tf->top_p_seq, x);
1422 tmp = build_int_cst (integer_type_node, fallthru_index);
1423 last_case = build_case_label (tmp, NULL,
1424 create_artificial_label (finally_loc));
1425 case_label_vec.quick_push (last_case);
1426 last_case_index++;
1428 x = gimple_build_label (CASE_LABEL (last_case));
1429 gimple_seq_add_stmt (&switch_body, x);
1431 tmp = lower_try_finally_fallthru_label (tf);
1432 x = gimple_build_goto (tmp);
1433 gimple_set_location (x, finally_loc);
1434 gimple_seq_add_stmt (&switch_body, x);
1437 /* For EH_ELSE, emit the exception path (plus resx) now, then
1438 subsequently we only need consider the normal path. */
1439 if (eh_else)
1441 if (tf->may_throw)
1443 finally = gimple_eh_else_e_body (eh_else);
1444 lower_eh_constructs_1 (state, &finally);
1446 emit_post_landing_pad (&eh_seq, tf->region);
1447 gimple_seq_add_seq (&eh_seq, finally);
1448 emit_resx (&eh_seq, tf->region);
1451 finally = gimple_eh_else_n_body (eh_else);
1453 else if (tf->may_throw)
1455 emit_post_landing_pad (&eh_seq, tf->region);
1457 x = gimple_build_assign (finally_tmp,
1458 build_int_cst (integer_type_node, eh_index));
1459 gimple_seq_add_stmt (&eh_seq, x);
1461 x = gimple_build_goto (finally_label);
1462 gimple_set_location (x, tf_loc);
1463 gimple_seq_add_stmt (&eh_seq, x);
1465 tmp = build_int_cst (integer_type_node, eh_index);
1466 last_case = build_case_label (tmp, NULL,
1467 create_artificial_label (tf_loc));
1468 case_label_vec.quick_push (last_case);
1469 last_case_index++;
1471 x = gimple_build_label (CASE_LABEL (last_case));
1472 gimple_seq_add_stmt (&eh_seq, x);
1473 emit_resx (&eh_seq, tf->region);
1476 x = gimple_build_label (finally_label);
1477 gimple_seq_add_stmt (&tf->top_p_seq, x);
1479 lower_eh_constructs_1 (state, &finally);
1480 gimple_seq_add_seq (&tf->top_p_seq, finally);
1482 /* Redirect each incoming goto edge. */
1483 q = tf->goto_queue;
1484 qe = q + tf->goto_queue_active;
1485 j = last_case_index + tf->may_return;
1486 /* Prepare the assignments to finally_tmp that are executed upon the
1487 entrance through a particular edge. */
1488 for (; q < qe; ++q)
1490 gimple_seq mod = NULL;
1491 int switch_id;
1492 unsigned int case_index;
1494 if (q->index < 0)
1496 x = gimple_build_assign (finally_tmp,
1497 build_int_cst (integer_type_node,
1498 return_index));
1499 gimple_seq_add_stmt (&mod, x);
1500 do_return_redirection (q, finally_label, mod);
1501 switch_id = return_index;
1503 else
1505 x = gimple_build_assign (finally_tmp,
1506 build_int_cst (integer_type_node, q->index));
1507 gimple_seq_add_stmt (&mod, x);
1508 do_goto_redirection (q, finally_label, mod, tf);
1509 switch_id = q->index;
1512 case_index = j + q->index;
1513 if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1515 tree case_lab;
1516 tmp = build_int_cst (integer_type_node, switch_id);
1517 case_lab = build_case_label (tmp, NULL,
1518 create_artificial_label (tf_loc));
1519 /* We store the cont_stmt in the pointer map, so that we can recover
1520 it in the loop below. */
1521 if (!cont_map)
1522 cont_map = new hash_map<tree, gimple *>;
1523 cont_map->put (case_lab, q->cont_stmt);
1524 case_label_vec.quick_push (case_lab);
1527 for (j = last_case_index; j < last_case_index + nlabels; j++)
1529 gimple *cont_stmt;
1531 last_case = case_label_vec[j];
1533 gcc_assert (last_case);
1534 gcc_assert (cont_map);
1536 cont_stmt = *cont_map->get (last_case);
1538 x = gimple_build_label (CASE_LABEL (last_case));
1539 gimple_seq_add_stmt (&switch_body, x);
1540 gimple_seq_add_stmt (&switch_body, cont_stmt);
1541 maybe_record_in_goto_queue (state, cont_stmt);
1543 if (cont_map)
1544 delete cont_map;
1546 replace_goto_queue (tf);
1548 /* Make sure that the last case is the default label, as one is required.
1549 Then sort the labels, which is also required in GIMPLE. */
1550 CASE_LOW (last_case) = NULL;
1551 tree tem = case_label_vec.pop ();
1552 gcc_assert (tem == last_case);
1553 sort_case_labels (case_label_vec);
1555 /* Build the switch statement, setting last_case to be the default
1556 label. */
1557 switch_stmt = gimple_build_switch (finally_tmp, last_case,
1558 case_label_vec);
1559 gimple_set_location (switch_stmt, finally_loc);
1561 /* Need to link SWITCH_STMT after running replace_goto_queue
1562 due to not wanting to process the same goto stmts twice. */
1563 gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1564 gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1567 /* Decide whether or not we are going to duplicate the finally block.
1568 There are several considerations.
1570 Second, we'd like to prevent egregious code growth. One way to
1571 do this is to estimate the size of the finally block, multiply
1572 that by the number of copies we'd need to make, and compare against
1573 the estimate of the size of the switch machinery we'd have to add. */
1575 static bool
1576 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1578 int f_estimate, sw_estimate;
1579 geh_else *eh_else;
1581 /* If there's an EH_ELSE involved, the exception path is separate
1582 and really doesn't come into play for this computation. */
1583 eh_else = get_eh_else (finally);
1584 if (eh_else)
1586 ndests -= may_throw;
1587 finally = gimple_eh_else_n_body (eh_else);
1590 if (!optimize)
1592 gimple_stmt_iterator gsi;
1594 if (ndests == 1)
1595 return true;
1597 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1599 /* Duplicate __builtin_stack_restore in the hope of eliminating it
1600 on the EH paths and, consequently, useless cleanups. */
1601 gimple *stmt = gsi_stmt (gsi);
1602 if (!is_gimple_debug (stmt)
1603 && !gimple_clobber_p (stmt)
1604 && !gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
1605 return false;
1607 return true;
1610 /* Finally estimate N times, plus N gotos. */
1611 f_estimate = estimate_num_insns_seq (finally, &eni_size_weights);
1612 f_estimate = (f_estimate + 1) * ndests;
1614 /* Switch statement (cost 10), N variable assignments, N gotos. */
1615 sw_estimate = 10 + 2 * ndests;
1617 /* Optimize for size clearly wants our best guess. */
1618 if (optimize_function_for_size_p (cfun))
1619 return f_estimate < sw_estimate;
1621 /* ??? These numbers are completely made up so far. */
1622 if (optimize > 1)
1623 return f_estimate < 100 || f_estimate < sw_estimate * 2;
1624 else
1625 return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1628 /* REG is the enclosing region for a possible cleanup region, or the region
1629 itself. Returns TRUE if such a region would be unreachable.
1631 Cleanup regions within a must-not-throw region aren't actually reachable
1632 even if there are throwing stmts within them, because the personality
1633 routine will call terminate before unwinding. */
1635 static bool
1636 cleanup_is_dead_in (eh_region reg)
1638 while (reg && reg->type == ERT_CLEANUP)
1639 reg = reg->outer;
1640 return (reg && reg->type == ERT_MUST_NOT_THROW);
1643 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_FINALLY nodes
1644 to a sequence of labels and blocks, plus the exception region trees
1645 that record all the magic. This is complicated by the need to
1646 arrange for the FINALLY block to be executed on all exits. */
1648 static gimple_seq
1649 lower_try_finally (struct leh_state *state, gtry *tp)
1651 struct leh_tf_state this_tf;
1652 struct leh_state this_state;
1653 int ndests;
1654 gimple_seq old_eh_seq;
1656 /* Process the try block. */
1658 memset (&this_tf, 0, sizeof (this_tf));
1659 this_tf.try_finally_expr = tp;
1660 this_tf.top_p = tp;
1661 this_tf.outer = state;
1662 if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1664 this_tf.region = gen_eh_region_cleanup (state->cur_region);
1665 this_state.cur_region = this_tf.region;
1667 else
1669 this_tf.region = NULL;
1670 this_state.cur_region = state->cur_region;
1673 this_state.ehp_region = state->ehp_region;
1674 this_state.tf = &this_tf;
1676 old_eh_seq = eh_seq;
1677 eh_seq = NULL;
1679 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1681 /* Determine if the try block is escaped through the bottom. */
1682 this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1684 /* Determine if any exceptions are possible within the try block. */
1685 if (this_tf.region)
1686 this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1687 if (this_tf.may_throw)
1688 honor_protect_cleanup_actions (state, &this_state, &this_tf);
1690 /* Determine how many edges (still) reach the finally block. Or rather,
1691 how many destinations are reached by the finally block. Use this to
1692 determine how we process the finally block itself. */
1694 ndests = this_tf.dest_array.length ();
1695 ndests += this_tf.may_fallthru;
1696 ndests += this_tf.may_return;
1697 ndests += this_tf.may_throw;
1699 /* If the FINALLY block is not reachable, dike it out. */
1700 if (ndests == 0)
1702 gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1703 gimple_try_set_cleanup (tp, NULL);
1705 /* If the finally block doesn't fall through, then any destination
1706 we might try to impose there isn't reached either. There may be
1707 some minor amount of cleanup and redirection still needed. */
1708 else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1709 lower_try_finally_nofallthru (state, &this_tf);
1711 /* We can easily special-case redirection to a single destination. */
1712 else if (ndests == 1)
1713 lower_try_finally_onedest (state, &this_tf);
1714 else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1715 gimple_try_cleanup (tp)))
1716 lower_try_finally_copy (state, &this_tf);
1717 else
1718 lower_try_finally_switch (state, &this_tf);
1720 /* If someone requested we add a label at the end of the transformed
1721 block, do so. */
1722 if (this_tf.fallthru_label)
1724 /* This must be reached only if ndests == 0. */
1725 gimple *x = gimple_build_label (this_tf.fallthru_label);
1726 gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1729 this_tf.dest_array.release ();
1730 free (this_tf.goto_queue);
1731 if (this_tf.goto_queue_map)
1732 delete this_tf.goto_queue_map;
1734 /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1735 If there was no old eh_seq, then the append is trivially already done. */
1736 if (old_eh_seq)
1738 if (eh_seq == NULL)
1739 eh_seq = old_eh_seq;
1740 else
1742 gimple_seq new_eh_seq = eh_seq;
1743 eh_seq = old_eh_seq;
1744 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1748 return this_tf.top_p_seq;
1751 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_CATCH with a
1752 list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1753 exception region trees that records all the magic. */
1755 static gimple_seq
1756 lower_catch (struct leh_state *state, gtry *tp)
1758 eh_region try_region = NULL;
1759 struct leh_state this_state = *state;
1760 gimple_stmt_iterator gsi;
1761 tree out_label;
1762 gimple_seq new_seq, cleanup;
1763 gimple *x;
1764 location_t try_catch_loc = gimple_location (tp);
1766 if (flag_exceptions)
1768 try_region = gen_eh_region_try (state->cur_region);
1769 this_state.cur_region = try_region;
1772 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1774 if (!eh_region_may_contain_throw (try_region))
1775 return gimple_try_eval (tp);
1777 new_seq = NULL;
1778 emit_eh_dispatch (&new_seq, try_region);
1779 emit_resx (&new_seq, try_region);
1781 this_state.cur_region = state->cur_region;
1782 this_state.ehp_region = try_region;
1784 /* Add eh_seq from lowering EH in the cleanup sequence after the cleanup
1785 itself, so that e.g. for coverage purposes the nested cleanups don't
1786 appear before the cleanup body. See PR64634 for details. */
1787 gimple_seq old_eh_seq = eh_seq;
1788 eh_seq = NULL;
1790 out_label = NULL;
1791 cleanup = gimple_try_cleanup (tp);
1792 for (gsi = gsi_start (cleanup);
1793 !gsi_end_p (gsi);
1794 gsi_next (&gsi))
1796 eh_catch c;
1797 gcatch *catch_stmt;
1798 gimple_seq handler;
1800 catch_stmt = as_a <gcatch *> (gsi_stmt (gsi));
1801 c = gen_eh_region_catch (try_region, gimple_catch_types (catch_stmt));
1803 handler = gimple_catch_handler (catch_stmt);
1804 lower_eh_constructs_1 (&this_state, &handler);
1806 c->label = create_artificial_label (UNKNOWN_LOCATION);
1807 x = gimple_build_label (c->label);
1808 gimple_seq_add_stmt (&new_seq, x);
1810 gimple_seq_add_seq (&new_seq, handler);
1812 if (gimple_seq_may_fallthru (new_seq))
1814 if (!out_label)
1815 out_label = create_artificial_label (try_catch_loc);
1817 x = gimple_build_goto (out_label);
1818 gimple_seq_add_stmt (&new_seq, x);
1820 if (!c->type_list)
1821 break;
1824 gimple_try_set_cleanup (tp, new_seq);
1826 gimple_seq new_eh_seq = eh_seq;
1827 eh_seq = old_eh_seq;
1828 gimple_seq ret_seq = frob_into_branch_around (tp, try_region, out_label);
1829 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1830 return ret_seq;
1833 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with a
1834 GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1835 region trees that record all the magic. */
1837 static gimple_seq
1838 lower_eh_filter (struct leh_state *state, gtry *tp)
1840 struct leh_state this_state = *state;
1841 eh_region this_region = NULL;
1842 gimple *inner, *x;
1843 gimple_seq new_seq;
1845 inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1847 if (flag_exceptions)
1849 this_region = gen_eh_region_allowed (state->cur_region,
1850 gimple_eh_filter_types (inner));
1851 this_state.cur_region = this_region;
1854 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1856 if (!eh_region_may_contain_throw (this_region))
1857 return gimple_try_eval (tp);
1859 new_seq = NULL;
1860 this_state.cur_region = state->cur_region;
1861 this_state.ehp_region = this_region;
1863 emit_eh_dispatch (&new_seq, this_region);
1864 emit_resx (&new_seq, this_region);
1866 this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1867 x = gimple_build_label (this_region->u.allowed.label);
1868 gimple_seq_add_stmt (&new_seq, x);
1870 lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1871 gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1873 gimple_try_set_cleanup (tp, new_seq);
1875 return frob_into_branch_around (tp, this_region, NULL);
1878 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with
1879 an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1880 plus the exception region trees that record all the magic. */
1882 static gimple_seq
1883 lower_eh_must_not_throw (struct leh_state *state, gtry *tp)
1885 struct leh_state this_state = *state;
1887 if (flag_exceptions)
1889 gimple *inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1890 eh_region this_region;
1892 this_region = gen_eh_region_must_not_throw (state->cur_region);
1893 this_region->u.must_not_throw.failure_decl
1894 = gimple_eh_must_not_throw_fndecl (
1895 as_a <geh_mnt *> (inner));
1896 this_region->u.must_not_throw.failure_loc
1897 = LOCATION_LOCUS (gimple_location (tp));
1899 /* In order to get mangling applied to this decl, we must mark it
1900 used now. Otherwise, pass_ipa_free_lang_data won't think it
1901 needs to happen. */
1902 TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1904 this_state.cur_region = this_region;
1907 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1909 return gimple_try_eval (tp);
1912 /* Implement a cleanup expression. This is similar to try-finally,
1913 except that we only execute the cleanup block for exception edges. */
1915 static gimple_seq
1916 lower_cleanup (struct leh_state *state, gtry *tp)
1918 struct leh_state this_state = *state;
1919 eh_region this_region = NULL;
1920 struct leh_tf_state fake_tf;
1921 gimple_seq result;
1922 bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1924 if (flag_exceptions && !cleanup_dead)
1926 this_region = gen_eh_region_cleanup (state->cur_region);
1927 this_state.cur_region = this_region;
1930 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1932 if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1933 return gimple_try_eval (tp);
1935 /* Build enough of a try-finally state so that we can reuse
1936 honor_protect_cleanup_actions. */
1937 memset (&fake_tf, 0, sizeof (fake_tf));
1938 fake_tf.top_p = fake_tf.try_finally_expr = tp;
1939 fake_tf.outer = state;
1940 fake_tf.region = this_region;
1941 fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1942 fake_tf.may_throw = true;
1944 honor_protect_cleanup_actions (state, NULL, &fake_tf);
1946 if (fake_tf.may_throw)
1948 /* In this case honor_protect_cleanup_actions had nothing to do,
1949 and we should process this normally. */
1950 lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1951 result = frob_into_branch_around (tp, this_region,
1952 fake_tf.fallthru_label);
1954 else
1956 /* In this case honor_protect_cleanup_actions did nearly all of
1957 the work. All we have left is to append the fallthru_label. */
1959 result = gimple_try_eval (tp);
1960 if (fake_tf.fallthru_label)
1962 gimple *x = gimple_build_label (fake_tf.fallthru_label);
1963 gimple_seq_add_stmt (&result, x);
1966 return result;
1969 /* Main loop for lowering eh constructs. Also moves gsi to the next
1970 statement. */
1972 static void
1973 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1975 gimple_seq replace;
1976 gimple *x;
1977 gimple *stmt = gsi_stmt (*gsi);
1979 switch (gimple_code (stmt))
1981 case GIMPLE_CALL:
1983 tree fndecl = gimple_call_fndecl (stmt);
1984 tree rhs, lhs;
1986 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1987 switch (DECL_FUNCTION_CODE (fndecl))
1989 case BUILT_IN_EH_POINTER:
1990 /* The front end may have generated a call to
1991 __builtin_eh_pointer (0) within a catch region. Replace
1992 this zero argument with the current catch region number. */
1993 if (state->ehp_region)
1995 tree nr = build_int_cst (integer_type_node,
1996 state->ehp_region->index);
1997 gimple_call_set_arg (stmt, 0, nr);
1999 else
2001 /* The user has dome something silly. Remove it. */
2002 rhs = null_pointer_node;
2003 goto do_replace;
2005 break;
2007 case BUILT_IN_EH_FILTER:
2008 /* ??? This should never appear, but since it's a builtin it
2009 is accessible to abuse by users. Just remove it and
2010 replace the use with the arbitrary value zero. */
2011 rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2012 do_replace:
2013 lhs = gimple_call_lhs (stmt);
2014 x = gimple_build_assign (lhs, rhs);
2015 gsi_insert_before (gsi, x, GSI_SAME_STMT);
2016 /* FALLTHRU */
2018 case BUILT_IN_EH_COPY_VALUES:
2019 /* Likewise this should not appear. Remove it. */
2020 gsi_remove (gsi, true);
2021 return;
2023 default:
2024 break;
2027 /* FALLTHRU */
2029 case GIMPLE_ASSIGN:
2030 /* If the stmt can throw use a new temporary for the assignment
2031 to a LHS. This makes sure the old value of the LHS is
2032 available on the EH edge. Only do so for statements that
2033 potentially fall through (no noreturn calls e.g.), otherwise
2034 this new assignment might create fake fallthru regions. */
2035 if (stmt_could_throw_p (stmt)
2036 && gimple_has_lhs (stmt)
2037 && gimple_stmt_may_fallthru (stmt)
2038 && !tree_could_throw_p (gimple_get_lhs (stmt))
2039 && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2041 tree lhs = gimple_get_lhs (stmt);
2042 tree tmp = create_tmp_var (TREE_TYPE (lhs));
2043 gimple *s = gimple_build_assign (lhs, tmp);
2044 gimple_set_location (s, gimple_location (stmt));
2045 gimple_set_block (s, gimple_block (stmt));
2046 gimple_set_lhs (stmt, tmp);
2047 if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2048 || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2049 DECL_GIMPLE_REG_P (tmp) = 1;
2050 gsi_insert_after (gsi, s, GSI_SAME_STMT);
2052 /* Look for things that can throw exceptions, and record them. */
2053 if (state->cur_region && stmt_could_throw_p (stmt))
2055 record_stmt_eh_region (state->cur_region, stmt);
2056 note_eh_region_may_contain_throw (state->cur_region);
2058 break;
2060 case GIMPLE_COND:
2061 case GIMPLE_GOTO:
2062 case GIMPLE_RETURN:
2063 maybe_record_in_goto_queue (state, stmt);
2064 break;
2066 case GIMPLE_SWITCH:
2067 verify_norecord_switch_expr (state, as_a <gswitch *> (stmt));
2068 break;
2070 case GIMPLE_TRY:
2072 gtry *try_stmt = as_a <gtry *> (stmt);
2073 if (gimple_try_kind (try_stmt) == GIMPLE_TRY_FINALLY)
2074 replace = lower_try_finally (state, try_stmt);
2075 else
2077 x = gimple_seq_first_stmt (gimple_try_cleanup (try_stmt));
2078 if (!x)
2080 replace = gimple_try_eval (try_stmt);
2081 lower_eh_constructs_1 (state, &replace);
2083 else
2084 switch (gimple_code (x))
2086 case GIMPLE_CATCH:
2087 replace = lower_catch (state, try_stmt);
2088 break;
2089 case GIMPLE_EH_FILTER:
2090 replace = lower_eh_filter (state, try_stmt);
2091 break;
2092 case GIMPLE_EH_MUST_NOT_THROW:
2093 replace = lower_eh_must_not_throw (state, try_stmt);
2094 break;
2095 case GIMPLE_EH_ELSE:
2096 /* This code is only valid with GIMPLE_TRY_FINALLY. */
2097 gcc_unreachable ();
2098 default:
2099 replace = lower_cleanup (state, try_stmt);
2100 break;
2105 /* Remove the old stmt and insert the transformed sequence
2106 instead. */
2107 gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2108 gsi_remove (gsi, true);
2110 /* Return since we don't want gsi_next () */
2111 return;
2113 case GIMPLE_EH_ELSE:
2114 /* We should be eliminating this in lower_try_finally et al. */
2115 gcc_unreachable ();
2117 default:
2118 /* A type, a decl, or some kind of statement that we're not
2119 interested in. Don't walk them. */
2120 break;
2123 gsi_next (gsi);
2126 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2128 static void
2129 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2131 gimple_stmt_iterator gsi;
2132 for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2133 lower_eh_constructs_2 (state, &gsi);
2136 namespace {
2138 const pass_data pass_data_lower_eh =
2140 GIMPLE_PASS, /* type */
2141 "eh", /* name */
2142 OPTGROUP_NONE, /* optinfo_flags */
2143 TV_TREE_EH, /* tv_id */
2144 PROP_gimple_lcf, /* properties_required */
2145 PROP_gimple_leh, /* properties_provided */
2146 0, /* properties_destroyed */
2147 0, /* todo_flags_start */
2148 0, /* todo_flags_finish */
2151 class pass_lower_eh : public gimple_opt_pass
2153 public:
2154 pass_lower_eh (gcc::context *ctxt)
2155 : gimple_opt_pass (pass_data_lower_eh, ctxt)
2158 /* opt_pass methods: */
2159 virtual unsigned int execute (function *);
2161 }; // class pass_lower_eh
2163 unsigned int
2164 pass_lower_eh::execute (function *fun)
2166 struct leh_state null_state;
2167 gimple_seq bodyp;
2169 bodyp = gimple_body (current_function_decl);
2170 if (bodyp == NULL)
2171 return 0;
2173 finally_tree = new hash_table<finally_tree_hasher> (31);
2174 eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2175 memset (&null_state, 0, sizeof (null_state));
2177 collect_finally_tree_1 (bodyp, NULL);
2178 lower_eh_constructs_1 (&null_state, &bodyp);
2179 gimple_set_body (current_function_decl, bodyp);
2181 /* We assume there's a return statement, or something, at the end of
2182 the function, and thus ploping the EH sequence afterward won't
2183 change anything. */
2184 gcc_assert (!gimple_seq_may_fallthru (bodyp));
2185 gimple_seq_add_seq (&bodyp, eh_seq);
2187 /* We assume that since BODYP already existed, adding EH_SEQ to it
2188 didn't change its value, and we don't have to re-set the function. */
2189 gcc_assert (bodyp == gimple_body (current_function_decl));
2191 delete finally_tree;
2192 finally_tree = NULL;
2193 BITMAP_FREE (eh_region_may_contain_throw_map);
2194 eh_seq = NULL;
2196 /* If this function needs a language specific EH personality routine
2197 and the frontend didn't already set one do so now. */
2198 if (function_needs_eh_personality (fun) == eh_personality_lang
2199 && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2200 DECL_FUNCTION_PERSONALITY (current_function_decl)
2201 = lang_hooks.eh_personality ();
2203 return 0;
2206 } // anon namespace
2208 gimple_opt_pass *
2209 make_pass_lower_eh (gcc::context *ctxt)
2211 return new pass_lower_eh (ctxt);
2214 /* Create the multiple edges from an EH_DISPATCH statement to all of
2215 the possible handlers for its EH region. Return true if there's
2216 no fallthru edge; false if there is. */
2218 bool
2219 make_eh_dispatch_edges (geh_dispatch *stmt)
2221 eh_region r;
2222 eh_catch c;
2223 basic_block src, dst;
2225 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2226 src = gimple_bb (stmt);
2228 switch (r->type)
2230 case ERT_TRY:
2231 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2233 dst = label_to_block (c->label);
2234 make_edge (src, dst, 0);
2236 /* A catch-all handler doesn't have a fallthru. */
2237 if (c->type_list == NULL)
2238 return false;
2240 break;
2242 case ERT_ALLOWED_EXCEPTIONS:
2243 dst = label_to_block (r->u.allowed.label);
2244 make_edge (src, dst, 0);
2245 break;
2247 default:
2248 gcc_unreachable ();
2251 return true;
2254 /* Create the single EH edge from STMT to its nearest landing pad,
2255 if there is such a landing pad within the current function. */
2257 void
2258 make_eh_edges (gimple *stmt)
2260 basic_block src, dst;
2261 eh_landing_pad lp;
2262 int lp_nr;
2264 lp_nr = lookup_stmt_eh_lp (stmt);
2265 if (lp_nr <= 0)
2266 return;
2268 lp = get_eh_landing_pad_from_number (lp_nr);
2269 gcc_assert (lp != NULL);
2271 src = gimple_bb (stmt);
2272 dst = label_to_block (lp->post_landing_pad);
2273 make_edge (src, dst, EDGE_EH);
2276 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2277 do not actually perform the final edge redirection.
2279 CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2280 we intend to change the destination EH region as well; this means
2281 EH_LANDING_PAD_NR must already be set on the destination block label.
2282 If false, we're being called from generic cfg manipulation code and we
2283 should preserve our place within the region tree. */
2285 static void
2286 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2288 eh_landing_pad old_lp, new_lp;
2289 basic_block old_bb;
2290 gimple *throw_stmt;
2291 int old_lp_nr, new_lp_nr;
2292 tree old_label, new_label;
2293 edge_iterator ei;
2294 edge e;
2296 old_bb = edge_in->dest;
2297 old_label = gimple_block_label (old_bb);
2298 old_lp_nr = EH_LANDING_PAD_NR (old_label);
2299 gcc_assert (old_lp_nr > 0);
2300 old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2302 throw_stmt = last_stmt (edge_in->src);
2303 gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2305 new_label = gimple_block_label (new_bb);
2307 /* Look for an existing region that might be using NEW_BB already. */
2308 new_lp_nr = EH_LANDING_PAD_NR (new_label);
2309 if (new_lp_nr)
2311 new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2312 gcc_assert (new_lp);
2314 /* Unless CHANGE_REGION is true, the new and old landing pad
2315 had better be associated with the same EH region. */
2316 gcc_assert (change_region || new_lp->region == old_lp->region);
2318 else
2320 new_lp = NULL;
2321 gcc_assert (!change_region);
2324 /* Notice when we redirect the last EH edge away from OLD_BB. */
2325 FOR_EACH_EDGE (e, ei, old_bb->preds)
2326 if (e != edge_in && (e->flags & EDGE_EH))
2327 break;
2329 if (new_lp)
2331 /* NEW_LP already exists. If there are still edges into OLD_LP,
2332 there's nothing to do with the EH tree. If there are no more
2333 edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2334 If CHANGE_REGION is true, then our caller is expecting to remove
2335 the landing pad. */
2336 if (e == NULL && !change_region)
2337 remove_eh_landing_pad (old_lp);
2339 else
2341 /* No correct landing pad exists. If there are no more edges
2342 into OLD_LP, then we can simply re-use the existing landing pad.
2343 Otherwise, we have to create a new landing pad. */
2344 if (e == NULL)
2346 EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2347 new_lp = old_lp;
2349 else
2350 new_lp = gen_eh_landing_pad (old_lp->region);
2351 new_lp->post_landing_pad = new_label;
2352 EH_LANDING_PAD_NR (new_label) = new_lp->index;
2355 /* Maybe move the throwing statement to the new region. */
2356 if (old_lp != new_lp)
2358 remove_stmt_from_eh_lp (throw_stmt);
2359 add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2363 /* Redirect EH edge E to NEW_BB. */
2365 edge
2366 redirect_eh_edge (edge edge_in, basic_block new_bb)
2368 redirect_eh_edge_1 (edge_in, new_bb, false);
2369 return ssa_redirect_edge (edge_in, new_bb);
2372 /* This is a subroutine of gimple_redirect_edge_and_branch. Update the
2373 labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2374 The actual edge update will happen in the caller. */
2376 void
2377 redirect_eh_dispatch_edge (geh_dispatch *stmt, edge e, basic_block new_bb)
2379 tree new_lab = gimple_block_label (new_bb);
2380 bool any_changed = false;
2381 basic_block old_bb;
2382 eh_region r;
2383 eh_catch c;
2385 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2386 switch (r->type)
2388 case ERT_TRY:
2389 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2391 old_bb = label_to_block (c->label);
2392 if (old_bb == e->dest)
2394 c->label = new_lab;
2395 any_changed = true;
2398 break;
2400 case ERT_ALLOWED_EXCEPTIONS:
2401 old_bb = label_to_block (r->u.allowed.label);
2402 gcc_assert (old_bb == e->dest);
2403 r->u.allowed.label = new_lab;
2404 any_changed = true;
2405 break;
2407 default:
2408 gcc_unreachable ();
2411 gcc_assert (any_changed);
2414 /* Helper function for operation_could_trap_p and stmt_could_throw_p. */
2416 bool
2417 operation_could_trap_helper_p (enum tree_code op,
2418 bool fp_operation,
2419 bool honor_trapv,
2420 bool honor_nans,
2421 bool honor_snans,
2422 tree divisor,
2423 bool *handled)
2425 *handled = true;
2426 switch (op)
2428 case TRUNC_DIV_EXPR:
2429 case CEIL_DIV_EXPR:
2430 case FLOOR_DIV_EXPR:
2431 case ROUND_DIV_EXPR:
2432 case EXACT_DIV_EXPR:
2433 case CEIL_MOD_EXPR:
2434 case FLOOR_MOD_EXPR:
2435 case ROUND_MOD_EXPR:
2436 case TRUNC_MOD_EXPR:
2437 case RDIV_EXPR:
2438 if (honor_snans || honor_trapv)
2439 return true;
2440 if (fp_operation)
2441 return flag_trapping_math;
2442 if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2443 return true;
2444 return false;
2446 case LT_EXPR:
2447 case LE_EXPR:
2448 case GT_EXPR:
2449 case GE_EXPR:
2450 case LTGT_EXPR:
2451 /* Some floating point comparisons may trap. */
2452 return honor_nans;
2454 case EQ_EXPR:
2455 case NE_EXPR:
2456 case UNORDERED_EXPR:
2457 case ORDERED_EXPR:
2458 case UNLT_EXPR:
2459 case UNLE_EXPR:
2460 case UNGT_EXPR:
2461 case UNGE_EXPR:
2462 case UNEQ_EXPR:
2463 return honor_snans;
2465 case NEGATE_EXPR:
2466 case ABS_EXPR:
2467 case CONJ_EXPR:
2468 /* These operations don't trap with floating point. */
2469 if (honor_trapv)
2470 return true;
2471 return false;
2473 case PLUS_EXPR:
2474 case MINUS_EXPR:
2475 case MULT_EXPR:
2476 /* Any floating arithmetic may trap. */
2477 if (fp_operation && flag_trapping_math)
2478 return true;
2479 if (honor_trapv)
2480 return true;
2481 return false;
2483 case COMPLEX_EXPR:
2484 case CONSTRUCTOR:
2485 /* Constructing an object cannot trap. */
2486 return false;
2488 default:
2489 /* Any floating arithmetic may trap. */
2490 if (fp_operation && flag_trapping_math)
2491 return true;
2493 *handled = false;
2494 return false;
2498 /* Return true if operation OP may trap. FP_OPERATION is true if OP is applied
2499 on floating-point values. HONOR_TRAPV is true if OP is applied on integer
2500 type operands that may trap. If OP is a division operator, DIVISOR contains
2501 the value of the divisor. */
2503 bool
2504 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2505 tree divisor)
2507 bool honor_nans = (fp_operation && flag_trapping_math
2508 && !flag_finite_math_only);
2509 bool honor_snans = fp_operation && flag_signaling_nans != 0;
2510 bool handled;
2512 if (TREE_CODE_CLASS (op) != tcc_comparison
2513 && TREE_CODE_CLASS (op) != tcc_unary
2514 && TREE_CODE_CLASS (op) != tcc_binary
2515 && op != FMA_EXPR)
2516 return false;
2518 return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2519 honor_nans, honor_snans, divisor,
2520 &handled);
2524 /* Returns true if it is possible to prove that the index of
2525 an array access REF (an ARRAY_REF expression) falls into the
2526 array bounds. */
2528 static bool
2529 in_array_bounds_p (tree ref)
2531 tree idx = TREE_OPERAND (ref, 1);
2532 tree min, max;
2534 if (TREE_CODE (idx) != INTEGER_CST)
2535 return false;
2537 min = array_ref_low_bound (ref);
2538 max = array_ref_up_bound (ref);
2539 if (!min
2540 || !max
2541 || TREE_CODE (min) != INTEGER_CST
2542 || TREE_CODE (max) != INTEGER_CST)
2543 return false;
2545 if (tree_int_cst_lt (idx, min)
2546 || tree_int_cst_lt (max, idx))
2547 return false;
2549 return true;
2552 /* Returns true if it is possible to prove that the range of
2553 an array access REF (an ARRAY_RANGE_REF expression) falls
2554 into the array bounds. */
2556 static bool
2557 range_in_array_bounds_p (tree ref)
2559 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2560 tree range_min, range_max, min, max;
2562 range_min = TYPE_MIN_VALUE (domain_type);
2563 range_max = TYPE_MAX_VALUE (domain_type);
2564 if (!range_min
2565 || !range_max
2566 || TREE_CODE (range_min) != INTEGER_CST
2567 || TREE_CODE (range_max) != INTEGER_CST)
2568 return false;
2570 min = array_ref_low_bound (ref);
2571 max = array_ref_up_bound (ref);
2572 if (!min
2573 || !max
2574 || TREE_CODE (min) != INTEGER_CST
2575 || TREE_CODE (max) != INTEGER_CST)
2576 return false;
2578 if (tree_int_cst_lt (range_min, min)
2579 || tree_int_cst_lt (max, range_max))
2580 return false;
2582 return true;
2585 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2586 location or floating point arithmetic. C.f. the rtl version, may_trap_p.
2587 This routine expects only GIMPLE lhs or rhs input. */
2589 bool
2590 tree_could_trap_p (tree expr)
2592 enum tree_code code;
2593 bool fp_operation = false;
2594 bool honor_trapv = false;
2595 tree t, base, div = NULL_TREE;
2597 if (!expr)
2598 return false;
2600 code = TREE_CODE (expr);
2601 t = TREE_TYPE (expr);
2603 if (t)
2605 if (COMPARISON_CLASS_P (expr))
2606 fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2607 else
2608 fp_operation = FLOAT_TYPE_P (t);
2609 honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2612 if (TREE_CODE_CLASS (code) == tcc_binary)
2613 div = TREE_OPERAND (expr, 1);
2614 if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2615 return true;
2617 restart:
2618 switch (code)
2620 case COMPONENT_REF:
2621 case REALPART_EXPR:
2622 case IMAGPART_EXPR:
2623 case BIT_FIELD_REF:
2624 case VIEW_CONVERT_EXPR:
2625 case WITH_SIZE_EXPR:
2626 expr = TREE_OPERAND (expr, 0);
2627 code = TREE_CODE (expr);
2628 goto restart;
2630 case ARRAY_RANGE_REF:
2631 base = TREE_OPERAND (expr, 0);
2632 if (tree_could_trap_p (base))
2633 return true;
2634 if (TREE_THIS_NOTRAP (expr))
2635 return false;
2636 return !range_in_array_bounds_p (expr);
2638 case ARRAY_REF:
2639 base = TREE_OPERAND (expr, 0);
2640 if (tree_could_trap_p (base))
2641 return true;
2642 if (TREE_THIS_NOTRAP (expr))
2643 return false;
2644 return !in_array_bounds_p (expr);
2646 case TARGET_MEM_REF:
2647 case MEM_REF:
2648 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR
2649 && tree_could_trap_p (TREE_OPERAND (TREE_OPERAND (expr, 0), 0)))
2650 return true;
2651 if (TREE_THIS_NOTRAP (expr))
2652 return false;
2653 /* We cannot prove that the access is in-bounds when we have
2654 variable-index TARGET_MEM_REFs. */
2655 if (code == TARGET_MEM_REF
2656 && (TMR_INDEX (expr) || TMR_INDEX2 (expr)))
2657 return true;
2658 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2660 tree base = TREE_OPERAND (TREE_OPERAND (expr, 0), 0);
2661 poly_offset_int off = mem_ref_offset (expr);
2662 if (maybe_lt (off, 0))
2663 return true;
2664 if (TREE_CODE (base) == STRING_CST)
2665 return maybe_le (TREE_STRING_LENGTH (base), off);
2666 tree size = DECL_SIZE_UNIT (base);
2667 if (size == NULL_TREE
2668 || !poly_int_tree_p (size)
2669 || maybe_le (wi::to_poly_offset (size), off))
2670 return true;
2671 /* Now we are sure the first byte of the access is inside
2672 the object. */
2673 return false;
2675 return true;
2677 case INDIRECT_REF:
2678 return !TREE_THIS_NOTRAP (expr);
2680 case ASM_EXPR:
2681 return TREE_THIS_VOLATILE (expr);
2683 case CALL_EXPR:
2684 t = get_callee_fndecl (expr);
2685 /* Assume that calls to weak functions may trap. */
2686 if (!t || !DECL_P (t))
2687 return true;
2688 if (DECL_WEAK (t))
2689 return tree_could_trap_p (t);
2690 return false;
2692 case FUNCTION_DECL:
2693 /* Assume that accesses to weak functions may trap, unless we know
2694 they are certainly defined in current TU or in some other
2695 LTO partition. */
2696 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2698 cgraph_node *node = cgraph_node::get (expr);
2699 if (node)
2700 node = node->function_symbol ();
2701 return !(node && node->in_other_partition);
2703 return false;
2705 case VAR_DECL:
2706 /* Assume that accesses to weak vars may trap, unless we know
2707 they are certainly defined in current TU or in some other
2708 LTO partition. */
2709 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2711 varpool_node *node = varpool_node::get (expr);
2712 if (node)
2713 node = node->ultimate_alias_target ();
2714 return !(node && node->in_other_partition);
2716 return false;
2718 default:
2719 return false;
2724 /* Helper for stmt_could_throw_p. Return true if STMT (assumed to be a
2725 an assignment or a conditional) may throw. */
2727 static bool
2728 stmt_could_throw_1_p (gassign *stmt)
2730 enum tree_code code = gimple_assign_rhs_code (stmt);
2731 bool honor_nans = false;
2732 bool honor_snans = false;
2733 bool fp_operation = false;
2734 bool honor_trapv = false;
2735 tree t;
2736 size_t i;
2737 bool handled, ret;
2739 if (TREE_CODE_CLASS (code) == tcc_comparison
2740 || TREE_CODE_CLASS (code) == tcc_unary
2741 || TREE_CODE_CLASS (code) == tcc_binary
2742 || code == FMA_EXPR)
2744 if (TREE_CODE_CLASS (code) == tcc_comparison)
2745 t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2746 else
2747 t = gimple_expr_type (stmt);
2748 fp_operation = FLOAT_TYPE_P (t);
2749 if (fp_operation)
2751 honor_nans = flag_trapping_math && !flag_finite_math_only;
2752 honor_snans = flag_signaling_nans != 0;
2754 else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2755 honor_trapv = true;
2758 /* First check the LHS. */
2759 if (tree_could_trap_p (gimple_assign_lhs (stmt)))
2760 return true;
2762 /* Check if the main expression may trap. */
2763 ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2764 honor_nans, honor_snans,
2765 gimple_assign_rhs2 (stmt),
2766 &handled);
2767 if (handled)
2768 return ret;
2770 /* If the expression does not trap, see if any of the individual operands may
2771 trap. */
2772 for (i = 1; i < gimple_num_ops (stmt); i++)
2773 if (tree_could_trap_p (gimple_op (stmt, i)))
2774 return true;
2776 return false;
2780 /* Return true if statement STMT could throw an exception. */
2782 bool
2783 stmt_could_throw_p (gimple *stmt)
2785 if (!flag_exceptions)
2786 return false;
2788 /* The only statements that can throw an exception are assignments,
2789 conditionals, calls, resx, and asms. */
2790 switch (gimple_code (stmt))
2792 case GIMPLE_RESX:
2793 return true;
2795 case GIMPLE_CALL:
2796 return !gimple_call_nothrow_p (as_a <gcall *> (stmt));
2798 case GIMPLE_COND:
2800 if (!cfun->can_throw_non_call_exceptions)
2801 return false;
2802 gcond *cond = as_a <gcond *> (stmt);
2803 tree lhs = gimple_cond_lhs (cond);
2804 return operation_could_trap_p (gimple_cond_code (cond),
2805 FLOAT_TYPE_P (TREE_TYPE (lhs)),
2806 false, NULL_TREE);
2809 case GIMPLE_ASSIGN:
2810 if (!cfun->can_throw_non_call_exceptions
2811 || gimple_clobber_p (stmt))
2812 return false;
2813 return stmt_could_throw_1_p (as_a <gassign *> (stmt));
2815 case GIMPLE_ASM:
2816 if (!cfun->can_throw_non_call_exceptions)
2817 return false;
2818 return gimple_asm_volatile_p (as_a <gasm *> (stmt));
2820 default:
2821 return false;
2826 /* Return true if expression T could throw an exception. */
2828 bool
2829 tree_could_throw_p (tree t)
2831 if (!flag_exceptions)
2832 return false;
2833 if (TREE_CODE (t) == MODIFY_EXPR)
2835 if (cfun->can_throw_non_call_exceptions
2836 && tree_could_trap_p (TREE_OPERAND (t, 0)))
2837 return true;
2838 t = TREE_OPERAND (t, 1);
2841 if (TREE_CODE (t) == WITH_SIZE_EXPR)
2842 t = TREE_OPERAND (t, 0);
2843 if (TREE_CODE (t) == CALL_EXPR)
2844 return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2845 if (cfun->can_throw_non_call_exceptions)
2846 return tree_could_trap_p (t);
2847 return false;
2850 /* Return true if STMT can throw an exception that is not caught within
2851 the current function (CFUN). */
2853 bool
2854 stmt_can_throw_external (gimple *stmt)
2856 int lp_nr;
2858 if (!stmt_could_throw_p (stmt))
2859 return false;
2861 lp_nr = lookup_stmt_eh_lp (stmt);
2862 return lp_nr == 0;
2865 /* Return true if STMT can throw an exception that is caught within
2866 the current function (CFUN). */
2868 bool
2869 stmt_can_throw_internal (gimple *stmt)
2871 int lp_nr;
2873 if (!stmt_could_throw_p (stmt))
2874 return false;
2876 lp_nr = lookup_stmt_eh_lp (stmt);
2877 return lp_nr > 0;
2880 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2881 remove any entry it might have from the EH table. Return true if
2882 any change was made. */
2884 bool
2885 maybe_clean_eh_stmt_fn (struct function *ifun, gimple *stmt)
2887 if (stmt_could_throw_p (stmt))
2888 return false;
2889 return remove_stmt_from_eh_lp_fn (ifun, stmt);
2892 /* Likewise, but always use the current function. */
2894 bool
2895 maybe_clean_eh_stmt (gimple *stmt)
2897 return maybe_clean_eh_stmt_fn (cfun, stmt);
2900 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2901 OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2902 in the table if it should be in there. Return TRUE if a replacement was
2903 done that my require an EH edge purge. */
2905 bool
2906 maybe_clean_or_replace_eh_stmt (gimple *old_stmt, gimple *new_stmt)
2908 int lp_nr = lookup_stmt_eh_lp (old_stmt);
2910 if (lp_nr != 0)
2912 bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2914 if (new_stmt == old_stmt && new_stmt_could_throw)
2915 return false;
2917 remove_stmt_from_eh_lp (old_stmt);
2918 if (new_stmt_could_throw)
2920 add_stmt_to_eh_lp (new_stmt, lp_nr);
2921 return false;
2923 else
2924 return true;
2927 return false;
2930 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2931 in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT. The MAP
2932 operand is the return value of duplicate_eh_regions. */
2934 bool
2935 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple *new_stmt,
2936 struct function *old_fun, gimple *old_stmt,
2937 hash_map<void *, void *> *map,
2938 int default_lp_nr)
2940 int old_lp_nr, new_lp_nr;
2942 if (!stmt_could_throw_p (new_stmt))
2943 return false;
2945 old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2946 if (old_lp_nr == 0)
2948 if (default_lp_nr == 0)
2949 return false;
2950 new_lp_nr = default_lp_nr;
2952 else if (old_lp_nr > 0)
2954 eh_landing_pad old_lp, new_lp;
2956 old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2957 new_lp = static_cast<eh_landing_pad> (*map->get (old_lp));
2958 new_lp_nr = new_lp->index;
2960 else
2962 eh_region old_r, new_r;
2964 old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2965 new_r = static_cast<eh_region> (*map->get (old_r));
2966 new_lp_nr = -new_r->index;
2969 add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2970 return true;
2973 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2974 and thus no remapping is required. */
2976 bool
2977 maybe_duplicate_eh_stmt (gimple *new_stmt, gimple *old_stmt)
2979 int lp_nr;
2981 if (!stmt_could_throw_p (new_stmt))
2982 return false;
2984 lp_nr = lookup_stmt_eh_lp (old_stmt);
2985 if (lp_nr == 0)
2986 return false;
2988 add_stmt_to_eh_lp (new_stmt, lp_nr);
2989 return true;
2992 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2993 GIMPLE_TRY) that are similar enough to be considered the same. Currently
2994 this only handles handlers consisting of a single call, as that's the
2995 important case for C++: a destructor call for a particular object showing
2996 up in multiple handlers. */
2998 static bool
2999 same_handler_p (gimple_seq oneh, gimple_seq twoh)
3001 gimple_stmt_iterator gsi;
3002 gimple *ones, *twos;
3003 unsigned int ai;
3005 gsi = gsi_start (oneh);
3006 if (!gsi_one_before_end_p (gsi))
3007 return false;
3008 ones = gsi_stmt (gsi);
3010 gsi = gsi_start (twoh);
3011 if (!gsi_one_before_end_p (gsi))
3012 return false;
3013 twos = gsi_stmt (gsi);
3015 if (!is_gimple_call (ones)
3016 || !is_gimple_call (twos)
3017 || gimple_call_lhs (ones)
3018 || gimple_call_lhs (twos)
3019 || gimple_call_chain (ones)
3020 || gimple_call_chain (twos)
3021 || !gimple_call_same_target_p (ones, twos)
3022 || gimple_call_num_args (ones) != gimple_call_num_args (twos))
3023 return false;
3025 for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
3026 if (!operand_equal_p (gimple_call_arg (ones, ai),
3027 gimple_call_arg (twos, ai), 0))
3028 return false;
3030 return true;
3033 /* Optimize
3034 try { A() } finally { try { ~B() } catch { ~A() } }
3035 try { ... } finally { ~A() }
3036 into
3037 try { A() } catch { ~B() }
3038 try { ~B() ... } finally { ~A() }
3040 This occurs frequently in C++, where A is a local variable and B is a
3041 temporary used in the initializer for A. */
3043 static void
3044 optimize_double_finally (gtry *one, gtry *two)
3046 gimple *oneh;
3047 gimple_stmt_iterator gsi;
3048 gimple_seq cleanup;
3050 cleanup = gimple_try_cleanup (one);
3051 gsi = gsi_start (cleanup);
3052 if (!gsi_one_before_end_p (gsi))
3053 return;
3055 oneh = gsi_stmt (gsi);
3056 if (gimple_code (oneh) != GIMPLE_TRY
3057 || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3058 return;
3060 if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3062 gimple_seq seq = gimple_try_eval (oneh);
3064 gimple_try_set_cleanup (one, seq);
3065 gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3066 seq = copy_gimple_seq_and_replace_locals (seq);
3067 gimple_seq_add_seq (&seq, gimple_try_eval (two));
3068 gimple_try_set_eval (two, seq);
3072 /* Perform EH refactoring optimizations that are simpler to do when code
3073 flow has been lowered but EH structures haven't. */
3075 static void
3076 refactor_eh_r (gimple_seq seq)
3078 gimple_stmt_iterator gsi;
3079 gimple *one, *two;
3081 one = NULL;
3082 two = NULL;
3083 gsi = gsi_start (seq);
3084 while (1)
3086 one = two;
3087 if (gsi_end_p (gsi))
3088 two = NULL;
3089 else
3090 two = gsi_stmt (gsi);
3091 if (one && two)
3092 if (gtry *try_one = dyn_cast <gtry *> (one))
3093 if (gtry *try_two = dyn_cast <gtry *> (two))
3094 if (gimple_try_kind (try_one) == GIMPLE_TRY_FINALLY
3095 && gimple_try_kind (try_two) == GIMPLE_TRY_FINALLY)
3096 optimize_double_finally (try_one, try_two);
3097 if (one)
3098 switch (gimple_code (one))
3100 case GIMPLE_TRY:
3101 refactor_eh_r (gimple_try_eval (one));
3102 refactor_eh_r (gimple_try_cleanup (one));
3103 break;
3104 case GIMPLE_CATCH:
3105 refactor_eh_r (gimple_catch_handler (as_a <gcatch *> (one)));
3106 break;
3107 case GIMPLE_EH_FILTER:
3108 refactor_eh_r (gimple_eh_filter_failure (one));
3109 break;
3110 case GIMPLE_EH_ELSE:
3112 geh_else *eh_else_stmt = as_a <geh_else *> (one);
3113 refactor_eh_r (gimple_eh_else_n_body (eh_else_stmt));
3114 refactor_eh_r (gimple_eh_else_e_body (eh_else_stmt));
3116 break;
3117 default:
3118 break;
3120 if (two)
3121 gsi_next (&gsi);
3122 else
3123 break;
3127 namespace {
3129 const pass_data pass_data_refactor_eh =
3131 GIMPLE_PASS, /* type */
3132 "ehopt", /* name */
3133 OPTGROUP_NONE, /* optinfo_flags */
3134 TV_TREE_EH, /* tv_id */
3135 PROP_gimple_lcf, /* properties_required */
3136 0, /* properties_provided */
3137 0, /* properties_destroyed */
3138 0, /* todo_flags_start */
3139 0, /* todo_flags_finish */
3142 class pass_refactor_eh : public gimple_opt_pass
3144 public:
3145 pass_refactor_eh (gcc::context *ctxt)
3146 : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3149 /* opt_pass methods: */
3150 virtual bool gate (function *) { return flag_exceptions != 0; }
3151 virtual unsigned int execute (function *)
3153 refactor_eh_r (gimple_body (current_function_decl));
3154 return 0;
3157 }; // class pass_refactor_eh
3159 } // anon namespace
3161 gimple_opt_pass *
3162 make_pass_refactor_eh (gcc::context *ctxt)
3164 return new pass_refactor_eh (ctxt);
3167 /* At the end of gimple optimization, we can lower RESX. */
3169 static bool
3170 lower_resx (basic_block bb, gresx *stmt,
3171 hash_map<eh_region, tree> *mnt_map)
3173 int lp_nr;
3174 eh_region src_r, dst_r;
3175 gimple_stmt_iterator gsi;
3176 gimple *x;
3177 tree fn, src_nr;
3178 bool ret = false;
3180 lp_nr = lookup_stmt_eh_lp (stmt);
3181 if (lp_nr != 0)
3182 dst_r = get_eh_region_from_lp_number (lp_nr);
3183 else
3184 dst_r = NULL;
3186 src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3187 gsi = gsi_last_bb (bb);
3189 if (src_r == NULL)
3191 /* We can wind up with no source region when pass_cleanup_eh shows
3192 that there are no entries into an eh region and deletes it, but
3193 then the block that contains the resx isn't removed. This can
3194 happen without optimization when the switch statement created by
3195 lower_try_finally_switch isn't simplified to remove the eh case.
3197 Resolve this by expanding the resx node to an abort. */
3199 fn = builtin_decl_implicit (BUILT_IN_TRAP);
3200 x = gimple_build_call (fn, 0);
3201 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3203 while (EDGE_COUNT (bb->succs) > 0)
3204 remove_edge (EDGE_SUCC (bb, 0));
3206 else if (dst_r)
3208 /* When we have a destination region, we resolve this by copying
3209 the excptr and filter values into place, and changing the edge
3210 to immediately after the landing pad. */
3211 edge e;
3213 if (lp_nr < 0)
3215 basic_block new_bb;
3216 tree lab;
3218 /* We are resuming into a MUST_NOT_CALL region. Expand a call to
3219 the failure decl into a new block, if needed. */
3220 gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3222 tree *slot = mnt_map->get (dst_r);
3223 if (slot == NULL)
3225 gimple_stmt_iterator gsi2;
3227 new_bb = create_empty_bb (bb);
3228 new_bb->count = bb->count;
3229 add_bb_to_loop (new_bb, bb->loop_father);
3230 lab = gimple_block_label (new_bb);
3231 gsi2 = gsi_start_bb (new_bb);
3233 fn = dst_r->u.must_not_throw.failure_decl;
3234 x = gimple_build_call (fn, 0);
3235 gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3236 gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3238 mnt_map->put (dst_r, lab);
3240 else
3242 lab = *slot;
3243 new_bb = label_to_block (lab);
3246 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3247 e = make_single_succ_edge (bb, new_bb, EDGE_FALLTHRU);
3249 else
3251 edge_iterator ei;
3252 tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3254 fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3255 src_nr = build_int_cst (integer_type_node, src_r->index);
3256 x = gimple_build_call (fn, 2, dst_nr, src_nr);
3257 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3259 /* Update the flags for the outgoing edge. */
3260 e = single_succ_edge (bb);
3261 gcc_assert (e->flags & EDGE_EH);
3262 e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3263 e->probability = profile_probability::always ();
3265 /* If there are no more EH users of the landing pad, delete it. */
3266 FOR_EACH_EDGE (e, ei, e->dest->preds)
3267 if (e->flags & EDGE_EH)
3268 break;
3269 if (e == NULL)
3271 eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3272 remove_eh_landing_pad (lp);
3276 ret = true;
3278 else
3280 tree var;
3282 /* When we don't have a destination region, this exception escapes
3283 up the call chain. We resolve this by generating a call to the
3284 _Unwind_Resume library function. */
3286 /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3287 with no arguments for C++. Check for that. */
3288 if (src_r->use_cxa_end_cleanup)
3290 fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3291 x = gimple_build_call (fn, 0);
3292 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3294 else
3296 fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3297 src_nr = build_int_cst (integer_type_node, src_r->index);
3298 x = gimple_build_call (fn, 1, src_nr);
3299 var = create_tmp_var (ptr_type_node);
3300 var = make_ssa_name (var, x);
3301 gimple_call_set_lhs (x, var);
3302 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3304 /* When exception handling is delegated to a caller function, we
3305 have to guarantee that shadow memory variables living on stack
3306 will be cleaner before control is given to a parent function. */
3307 if (sanitize_flags_p (SANITIZE_ADDRESS))
3309 tree decl
3310 = builtin_decl_implicit (BUILT_IN_ASAN_HANDLE_NO_RETURN);
3311 gimple *g = gimple_build_call (decl, 0);
3312 gimple_set_location (g, gimple_location (stmt));
3313 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
3316 fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3317 x = gimple_build_call (fn, 1, var);
3318 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3321 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3324 gsi_remove (&gsi, true);
3326 return ret;
3329 namespace {
3331 const pass_data pass_data_lower_resx =
3333 GIMPLE_PASS, /* type */
3334 "resx", /* name */
3335 OPTGROUP_NONE, /* optinfo_flags */
3336 TV_TREE_EH, /* tv_id */
3337 PROP_gimple_lcf, /* properties_required */
3338 0, /* properties_provided */
3339 0, /* properties_destroyed */
3340 0, /* todo_flags_start */
3341 0, /* todo_flags_finish */
3344 class pass_lower_resx : public gimple_opt_pass
3346 public:
3347 pass_lower_resx (gcc::context *ctxt)
3348 : gimple_opt_pass (pass_data_lower_resx, ctxt)
3351 /* opt_pass methods: */
3352 virtual bool gate (function *) { return flag_exceptions != 0; }
3353 virtual unsigned int execute (function *);
3355 }; // class pass_lower_resx
3357 unsigned
3358 pass_lower_resx::execute (function *fun)
3360 basic_block bb;
3361 bool dominance_invalidated = false;
3362 bool any_rewritten = false;
3364 hash_map<eh_region, tree> mnt_map;
3366 FOR_EACH_BB_FN (bb, fun)
3368 gimple *last = last_stmt (bb);
3369 if (last && is_gimple_resx (last))
3371 dominance_invalidated |=
3372 lower_resx (bb, as_a <gresx *> (last), &mnt_map);
3373 any_rewritten = true;
3377 if (dominance_invalidated)
3379 free_dominance_info (CDI_DOMINATORS);
3380 free_dominance_info (CDI_POST_DOMINATORS);
3383 return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3386 } // anon namespace
3388 gimple_opt_pass *
3389 make_pass_lower_resx (gcc::context *ctxt)
3391 return new pass_lower_resx (ctxt);
3394 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3395 external throw. */
3397 static void
3398 optimize_clobbers (basic_block bb)
3400 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3401 bool any_clobbers = false;
3402 bool seen_stack_restore = false;
3403 edge_iterator ei;
3404 edge e;
3406 /* Only optimize anything if the bb contains at least one clobber,
3407 ends with resx (checked by caller), optionally contains some
3408 debug stmts or labels, or at most one __builtin_stack_restore
3409 call, and has an incoming EH edge. */
3410 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3412 gimple *stmt = gsi_stmt (gsi);
3413 if (is_gimple_debug (stmt))
3414 continue;
3415 if (gimple_clobber_p (stmt))
3417 any_clobbers = true;
3418 continue;
3420 if (!seen_stack_restore
3421 && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3423 seen_stack_restore = true;
3424 continue;
3426 if (gimple_code (stmt) == GIMPLE_LABEL)
3427 break;
3428 return;
3430 if (!any_clobbers)
3431 return;
3432 FOR_EACH_EDGE (e, ei, bb->preds)
3433 if (e->flags & EDGE_EH)
3434 break;
3435 if (e == NULL)
3436 return;
3437 gsi = gsi_last_bb (bb);
3438 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3440 gimple *stmt = gsi_stmt (gsi);
3441 if (!gimple_clobber_p (stmt))
3442 continue;
3443 unlink_stmt_vdef (stmt);
3444 gsi_remove (&gsi, true);
3445 release_defs (stmt);
3449 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3450 internal throw to successor BB. */
3452 static int
3453 sink_clobbers (basic_block bb)
3455 edge e;
3456 edge_iterator ei;
3457 gimple_stmt_iterator gsi, dgsi;
3458 basic_block succbb;
3459 bool any_clobbers = false;
3460 unsigned todo = 0;
3462 /* Only optimize if BB has a single EH successor and
3463 all predecessor edges are EH too. */
3464 if (!single_succ_p (bb)
3465 || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3466 return 0;
3468 FOR_EACH_EDGE (e, ei, bb->preds)
3470 if ((e->flags & EDGE_EH) == 0)
3471 return 0;
3474 /* And BB contains only CLOBBER stmts before the final
3475 RESX. */
3476 gsi = gsi_last_bb (bb);
3477 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3479 gimple *stmt = gsi_stmt (gsi);
3480 if (is_gimple_debug (stmt))
3481 continue;
3482 if (gimple_code (stmt) == GIMPLE_LABEL)
3483 break;
3484 if (!gimple_clobber_p (stmt))
3485 return 0;
3486 any_clobbers = true;
3488 if (!any_clobbers)
3489 return 0;
3491 edge succe = single_succ_edge (bb);
3492 succbb = succe->dest;
3494 /* See if there is a virtual PHI node to take an updated virtual
3495 operand from. */
3496 gphi *vphi = NULL;
3497 tree vuse = NULL_TREE;
3498 for (gphi_iterator gpi = gsi_start_phis (succbb);
3499 !gsi_end_p (gpi); gsi_next (&gpi))
3501 tree res = gimple_phi_result (gpi.phi ());
3502 if (virtual_operand_p (res))
3504 vphi = gpi.phi ();
3505 vuse = res;
3506 break;
3510 dgsi = gsi_after_labels (succbb);
3511 gsi = gsi_last_bb (bb);
3512 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3514 gimple *stmt = gsi_stmt (gsi);
3515 tree lhs;
3516 if (is_gimple_debug (stmt))
3517 continue;
3518 if (gimple_code (stmt) == GIMPLE_LABEL)
3519 break;
3520 lhs = gimple_assign_lhs (stmt);
3521 /* Unfortunately we don't have dominance info updated at this
3522 point, so checking if
3523 dominated_by_p (CDI_DOMINATORS, succbb,
3524 gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3525 would be too costly. Thus, avoid sinking any clobbers that
3526 refer to non-(D) SSA_NAMEs. */
3527 if (TREE_CODE (lhs) == MEM_REF
3528 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3529 && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3531 unlink_stmt_vdef (stmt);
3532 gsi_remove (&gsi, true);
3533 release_defs (stmt);
3534 continue;
3537 /* As we do not change stmt order when sinking across a
3538 forwarder edge we can keep virtual operands in place. */
3539 gsi_remove (&gsi, false);
3540 gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3542 /* But adjust virtual operands if we sunk across a PHI node. */
3543 if (vuse)
3545 gimple *use_stmt;
3546 imm_use_iterator iter;
3547 use_operand_p use_p;
3548 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3549 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3550 SET_USE (use_p, gimple_vdef (stmt));
3551 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3553 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3554 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3556 /* Adjust the incoming virtual operand. */
3557 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3558 SET_USE (gimple_vuse_op (stmt), vuse);
3560 /* If there isn't a single predecessor but no virtual PHI node
3561 arrange for virtual operands to be renamed. */
3562 else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3563 && !single_pred_p (succbb))
3565 /* In this case there will be no use of the VDEF of this stmt.
3566 ??? Unless this is a secondary opportunity and we have not
3567 removed unreachable blocks yet, so we cannot assert this.
3568 Which also means we will end up renaming too many times. */
3569 SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3570 mark_virtual_operands_for_renaming (cfun);
3571 todo |= TODO_update_ssa_only_virtuals;
3575 return todo;
3578 /* At the end of inlining, we can lower EH_DISPATCH. Return true when
3579 we have found some duplicate labels and removed some edges. */
3581 static bool
3582 lower_eh_dispatch (basic_block src, geh_dispatch *stmt)
3584 gimple_stmt_iterator gsi;
3585 int region_nr;
3586 eh_region r;
3587 tree filter, fn;
3588 gimple *x;
3589 bool redirected = false;
3591 region_nr = gimple_eh_dispatch_region (stmt);
3592 r = get_eh_region_from_number (region_nr);
3594 gsi = gsi_last_bb (src);
3596 switch (r->type)
3598 case ERT_TRY:
3600 auto_vec<tree> labels;
3601 tree default_label = NULL;
3602 eh_catch c;
3603 edge_iterator ei;
3604 edge e;
3605 hash_set<tree> seen_values;
3607 /* Collect the labels for a switch. Zero the post_landing_pad
3608 field becase we'll no longer have anything keeping these labels
3609 in existence and the optimizer will be free to merge these
3610 blocks at will. */
3611 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3613 tree tp_node, flt_node, lab = c->label;
3614 bool have_label = false;
3616 c->label = NULL;
3617 tp_node = c->type_list;
3618 flt_node = c->filter_list;
3620 if (tp_node == NULL)
3622 default_label = lab;
3623 break;
3627 /* Filter out duplicate labels that arise when this handler
3628 is shadowed by an earlier one. When no labels are
3629 attached to the handler anymore, we remove
3630 the corresponding edge and then we delete unreachable
3631 blocks at the end of this pass. */
3632 if (! seen_values.contains (TREE_VALUE (flt_node)))
3634 tree t = build_case_label (TREE_VALUE (flt_node),
3635 NULL, lab);
3636 labels.safe_push (t);
3637 seen_values.add (TREE_VALUE (flt_node));
3638 have_label = true;
3641 tp_node = TREE_CHAIN (tp_node);
3642 flt_node = TREE_CHAIN (flt_node);
3644 while (tp_node);
3645 if (! have_label)
3647 remove_edge (find_edge (src, label_to_block (lab)));
3648 redirected = true;
3652 /* Clean up the edge flags. */
3653 FOR_EACH_EDGE (e, ei, src->succs)
3655 if (e->flags & EDGE_FALLTHRU)
3657 /* If there was no catch-all, use the fallthru edge. */
3658 if (default_label == NULL)
3659 default_label = gimple_block_label (e->dest);
3660 e->flags &= ~EDGE_FALLTHRU;
3663 gcc_assert (default_label != NULL);
3665 /* Don't generate a switch if there's only a default case.
3666 This is common in the form of try { A; } catch (...) { B; }. */
3667 if (!labels.exists ())
3669 e = single_succ_edge (src);
3670 e->flags |= EDGE_FALLTHRU;
3672 else
3674 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3675 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3676 region_nr));
3677 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3678 filter = make_ssa_name (filter, x);
3679 gimple_call_set_lhs (x, filter);
3680 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3682 /* Turn the default label into a default case. */
3683 default_label = build_case_label (NULL, NULL, default_label);
3684 sort_case_labels (labels);
3686 x = gimple_build_switch (filter, default_label, labels);
3687 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3690 break;
3692 case ERT_ALLOWED_EXCEPTIONS:
3694 edge b_e = BRANCH_EDGE (src);
3695 edge f_e = FALLTHRU_EDGE (src);
3697 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3698 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3699 region_nr));
3700 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3701 filter = make_ssa_name (filter, x);
3702 gimple_call_set_lhs (x, filter);
3703 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3705 r->u.allowed.label = NULL;
3706 x = gimple_build_cond (EQ_EXPR, filter,
3707 build_int_cst (TREE_TYPE (filter),
3708 r->u.allowed.filter),
3709 NULL_TREE, NULL_TREE);
3710 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3712 b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3713 f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3715 break;
3717 default:
3718 gcc_unreachable ();
3721 /* Replace the EH_DISPATCH with the SWITCH or COND generated above. */
3722 gsi_remove (&gsi, true);
3723 return redirected;
3726 namespace {
3728 const pass_data pass_data_lower_eh_dispatch =
3730 GIMPLE_PASS, /* type */
3731 "ehdisp", /* name */
3732 OPTGROUP_NONE, /* optinfo_flags */
3733 TV_TREE_EH, /* tv_id */
3734 PROP_gimple_lcf, /* properties_required */
3735 0, /* properties_provided */
3736 0, /* properties_destroyed */
3737 0, /* todo_flags_start */
3738 0, /* todo_flags_finish */
3741 class pass_lower_eh_dispatch : public gimple_opt_pass
3743 public:
3744 pass_lower_eh_dispatch (gcc::context *ctxt)
3745 : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3748 /* opt_pass methods: */
3749 virtual bool gate (function *fun) { return fun->eh->region_tree != NULL; }
3750 virtual unsigned int execute (function *);
3752 }; // class pass_lower_eh_dispatch
3754 unsigned
3755 pass_lower_eh_dispatch::execute (function *fun)
3757 basic_block bb;
3758 int flags = 0;
3759 bool redirected = false;
3761 assign_filter_values ();
3763 FOR_EACH_BB_FN (bb, fun)
3765 gimple *last = last_stmt (bb);
3766 if (last == NULL)
3767 continue;
3768 if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3770 redirected |= lower_eh_dispatch (bb,
3771 as_a <geh_dispatch *> (last));
3772 flags |= TODO_update_ssa_only_virtuals;
3774 else if (gimple_code (last) == GIMPLE_RESX)
3776 if (stmt_can_throw_external (last))
3777 optimize_clobbers (bb);
3778 else
3779 flags |= sink_clobbers (bb);
3783 if (redirected)
3785 free_dominance_info (CDI_DOMINATORS);
3786 delete_unreachable_blocks ();
3788 return flags;
3791 } // anon namespace
3793 gimple_opt_pass *
3794 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3796 return new pass_lower_eh_dispatch (ctxt);
3799 /* Walk statements, see what regions and, optionally, landing pads
3800 are really referenced.
3802 Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3803 and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3805 Passing NULL for LP_REACHABLE is valid, in this case only reachable
3806 regions are marked.
3808 The caller is responsible for freeing the returned sbitmaps. */
3810 static void
3811 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3813 sbitmap r_reachable, lp_reachable;
3814 basic_block bb;
3815 bool mark_landing_pads = (lp_reachablep != NULL);
3816 gcc_checking_assert (r_reachablep != NULL);
3818 r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3819 bitmap_clear (r_reachable);
3820 *r_reachablep = r_reachable;
3822 if (mark_landing_pads)
3824 lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3825 bitmap_clear (lp_reachable);
3826 *lp_reachablep = lp_reachable;
3828 else
3829 lp_reachable = NULL;
3831 FOR_EACH_BB_FN (bb, cfun)
3833 gimple_stmt_iterator gsi;
3835 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3837 gimple *stmt = gsi_stmt (gsi);
3839 if (mark_landing_pads)
3841 int lp_nr = lookup_stmt_eh_lp (stmt);
3843 /* Negative LP numbers are MUST_NOT_THROW regions which
3844 are not considered BB enders. */
3845 if (lp_nr < 0)
3846 bitmap_set_bit (r_reachable, -lp_nr);
3848 /* Positive LP numbers are real landing pads, and BB enders. */
3849 else if (lp_nr > 0)
3851 gcc_assert (gsi_one_before_end_p (gsi));
3852 eh_region region = get_eh_region_from_lp_number (lp_nr);
3853 bitmap_set_bit (r_reachable, region->index);
3854 bitmap_set_bit (lp_reachable, lp_nr);
3858 /* Avoid removing regions referenced from RESX/EH_DISPATCH. */
3859 switch (gimple_code (stmt))
3861 case GIMPLE_RESX:
3862 bitmap_set_bit (r_reachable,
3863 gimple_resx_region (as_a <gresx *> (stmt)));
3864 break;
3865 case GIMPLE_EH_DISPATCH:
3866 bitmap_set_bit (r_reachable,
3867 gimple_eh_dispatch_region (
3868 as_a <geh_dispatch *> (stmt)));
3869 break;
3870 case GIMPLE_CALL:
3871 if (gimple_call_builtin_p (stmt, BUILT_IN_EH_COPY_VALUES))
3872 for (int i = 0; i < 2; ++i)
3874 tree rt = gimple_call_arg (stmt, i);
3875 HOST_WIDE_INT ri = tree_to_shwi (rt);
3877 gcc_assert (ri == (int)ri);
3878 bitmap_set_bit (r_reachable, ri);
3880 break;
3881 default:
3882 break;
3888 /* Remove unreachable handlers and unreachable landing pads. */
3890 static void
3891 remove_unreachable_handlers (void)
3893 sbitmap r_reachable, lp_reachable;
3894 eh_region region;
3895 eh_landing_pad lp;
3896 unsigned i;
3898 mark_reachable_handlers (&r_reachable, &lp_reachable);
3900 if (dump_file)
3902 fprintf (dump_file, "Before removal of unreachable regions:\n");
3903 dump_eh_tree (dump_file, cfun);
3904 fprintf (dump_file, "Reachable regions: ");
3905 dump_bitmap_file (dump_file, r_reachable);
3906 fprintf (dump_file, "Reachable landing pads: ");
3907 dump_bitmap_file (dump_file, lp_reachable);
3910 if (dump_file)
3912 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3913 if (region && !bitmap_bit_p (r_reachable, region->index))
3914 fprintf (dump_file,
3915 "Removing unreachable region %d\n",
3916 region->index);
3919 remove_unreachable_eh_regions (r_reachable);
3921 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3922 if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3924 if (dump_file)
3925 fprintf (dump_file,
3926 "Removing unreachable landing pad %d\n",
3927 lp->index);
3928 remove_eh_landing_pad (lp);
3931 if (dump_file)
3933 fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3934 dump_eh_tree (dump_file, cfun);
3935 fprintf (dump_file, "\n\n");
3938 sbitmap_free (r_reachable);
3939 sbitmap_free (lp_reachable);
3941 if (flag_checking)
3942 verify_eh_tree (cfun);
3945 /* Remove unreachable handlers if any landing pads have been removed after
3946 last ehcleanup pass (due to gimple_purge_dead_eh_edges). */
3948 void
3949 maybe_remove_unreachable_handlers (void)
3951 eh_landing_pad lp;
3952 unsigned i;
3954 if (cfun->eh == NULL)
3955 return;
3957 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3958 if (lp && lp->post_landing_pad)
3960 if (label_to_block (lp->post_landing_pad) == NULL)
3962 remove_unreachable_handlers ();
3963 return;
3968 /* Remove regions that do not have landing pads. This assumes
3969 that remove_unreachable_handlers has already been run, and
3970 that we've just manipulated the landing pads since then.
3972 Preserve regions with landing pads and regions that prevent
3973 exceptions from propagating further, even if these regions
3974 are not reachable. */
3976 static void
3977 remove_unreachable_handlers_no_lp (void)
3979 eh_region region;
3980 sbitmap r_reachable;
3981 unsigned i;
3983 mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3985 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3987 if (! region)
3988 continue;
3990 if (region->landing_pads != NULL
3991 || region->type == ERT_MUST_NOT_THROW)
3992 bitmap_set_bit (r_reachable, region->index);
3994 if (dump_file
3995 && !bitmap_bit_p (r_reachable, region->index))
3996 fprintf (dump_file,
3997 "Removing unreachable region %d\n",
3998 region->index);
4001 remove_unreachable_eh_regions (r_reachable);
4003 sbitmap_free (r_reachable);
4006 /* Undo critical edge splitting on an EH landing pad. Earlier, we
4007 optimisticaly split all sorts of edges, including EH edges. The
4008 optimization passes in between may not have needed them; if not,
4009 we should undo the split.
4011 Recognize this case by having one EH edge incoming to the BB and
4012 one normal edge outgoing; BB should be empty apart from the
4013 post_landing_pad label.
4015 Note that this is slightly different from the empty handler case
4016 handled by cleanup_empty_eh, in that the actual handler may yet
4017 have actual code but the landing pad has been separated from the
4018 handler. As such, cleanup_empty_eh relies on this transformation
4019 having been done first. */
4021 static bool
4022 unsplit_eh (eh_landing_pad lp)
4024 basic_block bb = label_to_block (lp->post_landing_pad);
4025 gimple_stmt_iterator gsi;
4026 edge e_in, e_out;
4028 /* Quickly check the edge counts on BB for singularity. */
4029 if (!single_pred_p (bb) || !single_succ_p (bb))
4030 return false;
4031 e_in = single_pred_edge (bb);
4032 e_out = single_succ_edge (bb);
4034 /* Input edge must be EH and output edge must be normal. */
4035 if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4036 return false;
4038 /* The block must be empty except for the labels and debug insns. */
4039 gsi = gsi_after_labels (bb);
4040 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4041 gsi_next_nondebug (&gsi);
4042 if (!gsi_end_p (gsi))
4043 return false;
4045 /* The destination block must not already have a landing pad
4046 for a different region. */
4047 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4049 glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4050 tree lab;
4051 int lp_nr;
4053 if (!label_stmt)
4054 break;
4055 lab = gimple_label_label (label_stmt);
4056 lp_nr = EH_LANDING_PAD_NR (lab);
4057 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4058 return false;
4061 /* The new destination block must not already be a destination of
4062 the source block, lest we merge fallthru and eh edges and get
4063 all sorts of confused. */
4064 if (find_edge (e_in->src, e_out->dest))
4065 return false;
4067 /* ??? We can get degenerate phis due to cfg cleanups. I would have
4068 thought this should have been cleaned up by a phicprop pass, but
4069 that doesn't appear to handle virtuals. Propagate by hand. */
4070 if (!gimple_seq_empty_p (phi_nodes (bb)))
4072 for (gphi_iterator gpi = gsi_start_phis (bb); !gsi_end_p (gpi); )
4074 gimple *use_stmt;
4075 gphi *phi = gpi.phi ();
4076 tree lhs = gimple_phi_result (phi);
4077 tree rhs = gimple_phi_arg_def (phi, 0);
4078 use_operand_p use_p;
4079 imm_use_iterator iter;
4081 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4083 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4084 SET_USE (use_p, rhs);
4087 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4088 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4090 remove_phi_node (&gpi, true);
4094 if (dump_file && (dump_flags & TDF_DETAILS))
4095 fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4096 lp->index, e_out->dest->index);
4098 /* Redirect the edge. Since redirect_eh_edge_1 expects to be moving
4099 a successor edge, humor it. But do the real CFG change with the
4100 predecessor of E_OUT in order to preserve the ordering of arguments
4101 to the PHI nodes in E_OUT->DEST. */
4102 redirect_eh_edge_1 (e_in, e_out->dest, false);
4103 redirect_edge_pred (e_out, e_in->src);
4104 e_out->flags = e_in->flags;
4105 e_out->probability = e_in->probability;
4106 remove_edge (e_in);
4108 return true;
4111 /* Examine each landing pad block and see if it matches unsplit_eh. */
4113 static bool
4114 unsplit_all_eh (void)
4116 bool changed = false;
4117 eh_landing_pad lp;
4118 int i;
4120 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4121 if (lp)
4122 changed |= unsplit_eh (lp);
4124 return changed;
4127 /* A subroutine of cleanup_empty_eh. Redirect all EH edges incoming
4128 to OLD_BB to NEW_BB; return true on success, false on failure.
4130 OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4131 PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4132 Virtual PHIs may be deleted and marked for renaming. */
4134 static bool
4135 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4136 edge old_bb_out, bool change_region)
4138 gphi_iterator ngsi, ogsi;
4139 edge_iterator ei;
4140 edge e;
4141 bitmap ophi_handled;
4143 /* The destination block must not be a regular successor for any
4144 of the preds of the landing pad. Thus, avoid turning
4145 <..>
4146 | \ EH
4147 | <..>
4149 <..>
4150 into
4151 <..>
4152 | | EH
4153 <..>
4154 which CFG verification would choke on. See PR45172 and PR51089. */
4155 FOR_EACH_EDGE (e, ei, old_bb->preds)
4156 if (find_edge (e->src, new_bb))
4157 return false;
4159 FOR_EACH_EDGE (e, ei, old_bb->preds)
4160 redirect_edge_var_map_clear (e);
4162 ophi_handled = BITMAP_ALLOC (NULL);
4164 /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4165 for the edges we're going to move. */
4166 for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4168 gphi *ophi, *nphi = ngsi.phi ();
4169 tree nresult, nop;
4171 nresult = gimple_phi_result (nphi);
4172 nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4174 /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4175 the source ssa_name. */
4176 ophi = NULL;
4177 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4179 ophi = ogsi.phi ();
4180 if (gimple_phi_result (ophi) == nop)
4181 break;
4182 ophi = NULL;
4185 /* If we did find the corresponding PHI, copy those inputs. */
4186 if (ophi)
4188 /* If NOP is used somewhere else beyond phis in new_bb, give up. */
4189 if (!has_single_use (nop))
4191 imm_use_iterator imm_iter;
4192 use_operand_p use_p;
4194 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4196 if (!gimple_debug_bind_p (USE_STMT (use_p))
4197 && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4198 || gimple_bb (USE_STMT (use_p)) != new_bb))
4199 goto fail;
4202 bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4203 FOR_EACH_EDGE (e, ei, old_bb->preds)
4205 location_t oloc;
4206 tree oop;
4208 if ((e->flags & EDGE_EH) == 0)
4209 continue;
4210 oop = gimple_phi_arg_def (ophi, e->dest_idx);
4211 oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4212 redirect_edge_var_map_add (e, nresult, oop, oloc);
4215 /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4216 from the fact that OLD_BB is tree_empty_eh_handler_p that the
4217 variable is unchanged from input to the block and we can simply
4218 re-use the input to NEW_BB from the OLD_BB_OUT edge. */
4219 else
4221 location_t nloc
4222 = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4223 FOR_EACH_EDGE (e, ei, old_bb->preds)
4224 redirect_edge_var_map_add (e, nresult, nop, nloc);
4228 /* Second, verify that all PHIs from OLD_BB have been handled. If not,
4229 we don't know what values from the other edges into NEW_BB to use. */
4230 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4232 gphi *ophi = ogsi.phi ();
4233 tree oresult = gimple_phi_result (ophi);
4234 if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4235 goto fail;
4238 /* Finally, move the edges and update the PHIs. */
4239 for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4240 if (e->flags & EDGE_EH)
4242 /* ??? CFG manipluation routines do not try to update loop
4243 form on edge redirection. Do so manually here for now. */
4244 /* If we redirect a loop entry or latch edge that will either create
4245 a multiple entry loop or rotate the loop. If the loops merge
4246 we may have created a loop with multiple latches.
4247 All of this isn't easily fixed thus cancel the affected loop
4248 and mark the other loop as possibly having multiple latches. */
4249 if (e->dest == e->dest->loop_father->header)
4251 mark_loop_for_removal (e->dest->loop_father);
4252 new_bb->loop_father->latch = NULL;
4253 loops_state_set (LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4255 redirect_eh_edge_1 (e, new_bb, change_region);
4256 redirect_edge_succ (e, new_bb);
4257 flush_pending_stmts (e);
4259 else
4260 ei_next (&ei);
4262 BITMAP_FREE (ophi_handled);
4263 return true;
4265 fail:
4266 FOR_EACH_EDGE (e, ei, old_bb->preds)
4267 redirect_edge_var_map_clear (e);
4268 BITMAP_FREE (ophi_handled);
4269 return false;
4272 /* A subroutine of cleanup_empty_eh. Move a landing pad LP from its
4273 old region to NEW_REGION at BB. */
4275 static void
4276 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4277 eh_landing_pad lp, eh_region new_region)
4279 gimple_stmt_iterator gsi;
4280 eh_landing_pad *pp;
4282 for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4283 continue;
4284 *pp = lp->next_lp;
4286 lp->region = new_region;
4287 lp->next_lp = new_region->landing_pads;
4288 new_region->landing_pads = lp;
4290 /* Delete the RESX that was matched within the empty handler block. */
4291 gsi = gsi_last_bb (bb);
4292 unlink_stmt_vdef (gsi_stmt (gsi));
4293 gsi_remove (&gsi, true);
4295 /* Clean up E_OUT for the fallthru. */
4296 e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
4297 e_out->probability = profile_probability::always ();
4300 /* A subroutine of cleanup_empty_eh. Handle more complex cases of
4301 unsplitting than unsplit_eh was prepared to handle, e.g. when
4302 multiple incoming edges and phis are involved. */
4304 static bool
4305 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4307 gimple_stmt_iterator gsi;
4308 tree lab;
4310 /* We really ought not have totally lost everything following
4311 a landing pad label. Given that BB is empty, there had better
4312 be a successor. */
4313 gcc_assert (e_out != NULL);
4315 /* The destination block must not already have a landing pad
4316 for a different region. */
4317 lab = NULL;
4318 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4320 glabel *stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4321 int lp_nr;
4323 if (!stmt)
4324 break;
4325 lab = gimple_label_label (stmt);
4326 lp_nr = EH_LANDING_PAD_NR (lab);
4327 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4328 return false;
4331 /* Attempt to move the PHIs into the successor block. */
4332 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4334 if (dump_file && (dump_flags & TDF_DETAILS))
4335 fprintf (dump_file,
4336 "Unsplit EH landing pad %d to block %i "
4337 "(via cleanup_empty_eh).\n",
4338 lp->index, e_out->dest->index);
4339 return true;
4342 return false;
4345 /* Return true if edge E_FIRST is part of an empty infinite loop
4346 or leads to such a loop through a series of single successor
4347 empty bbs. */
4349 static bool
4350 infinite_empty_loop_p (edge e_first)
4352 bool inf_loop = false;
4353 edge e;
4355 if (e_first->dest == e_first->src)
4356 return true;
4358 e_first->src->aux = (void *) 1;
4359 for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4361 gimple_stmt_iterator gsi;
4362 if (e->dest->aux)
4364 inf_loop = true;
4365 break;
4367 e->dest->aux = (void *) 1;
4368 gsi = gsi_after_labels (e->dest);
4369 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4370 gsi_next_nondebug (&gsi);
4371 if (!gsi_end_p (gsi))
4372 break;
4374 e_first->src->aux = NULL;
4375 for (e = e_first; e->dest->aux; e = single_succ_edge (e->dest))
4376 e->dest->aux = NULL;
4378 return inf_loop;
4381 /* Examine the block associated with LP to determine if it's an empty
4382 handler for its EH region. If so, attempt to redirect EH edges to
4383 an outer region. Return true the CFG was updated in any way. This
4384 is similar to jump forwarding, just across EH edges. */
4386 static bool
4387 cleanup_empty_eh (eh_landing_pad lp)
4389 basic_block bb = label_to_block (lp->post_landing_pad);
4390 gimple_stmt_iterator gsi;
4391 gimple *resx;
4392 eh_region new_region;
4393 edge_iterator ei;
4394 edge e, e_out;
4395 bool has_non_eh_pred;
4396 bool ret = false;
4397 int new_lp_nr;
4399 /* There can be zero or one edges out of BB. This is the quickest test. */
4400 switch (EDGE_COUNT (bb->succs))
4402 case 0:
4403 e_out = NULL;
4404 break;
4405 case 1:
4406 e_out = single_succ_edge (bb);
4407 break;
4408 default:
4409 return false;
4412 gsi = gsi_last_nondebug_bb (bb);
4413 resx = gsi_stmt (gsi);
4414 if (resx && is_gimple_resx (resx))
4416 if (stmt_can_throw_external (resx))
4417 optimize_clobbers (bb);
4418 else if (sink_clobbers (bb))
4419 ret = true;
4422 gsi = gsi_after_labels (bb);
4424 /* Make sure to skip debug statements. */
4425 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4426 gsi_next_nondebug (&gsi);
4428 /* If the block is totally empty, look for more unsplitting cases. */
4429 if (gsi_end_p (gsi))
4431 /* For the degenerate case of an infinite loop bail out.
4432 If bb has no successors and is totally empty, which can happen e.g.
4433 because of incorrect noreturn attribute, bail out too. */
4434 if (e_out == NULL
4435 || infinite_empty_loop_p (e_out))
4436 return ret;
4438 return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4441 /* The block should consist only of a single RESX statement, modulo a
4442 preceding call to __builtin_stack_restore if there is no outgoing
4443 edge, since the call can be eliminated in this case. */
4444 resx = gsi_stmt (gsi);
4445 if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4447 gsi_next_nondebug (&gsi);
4448 resx = gsi_stmt (gsi);
4450 if (!is_gimple_resx (resx))
4451 return ret;
4452 gcc_assert (gsi_one_nondebug_before_end_p (gsi));
4454 /* Determine if there are non-EH edges, or resx edges into the handler. */
4455 has_non_eh_pred = false;
4456 FOR_EACH_EDGE (e, ei, bb->preds)
4457 if (!(e->flags & EDGE_EH))
4458 has_non_eh_pred = true;
4460 /* Find the handler that's outer of the empty handler by looking at
4461 where the RESX instruction was vectored. */
4462 new_lp_nr = lookup_stmt_eh_lp (resx);
4463 new_region = get_eh_region_from_lp_number (new_lp_nr);
4465 /* If there's no destination region within the current function,
4466 redirection is trivial via removing the throwing statements from
4467 the EH region, removing the EH edges, and allowing the block
4468 to go unreachable. */
4469 if (new_region == NULL)
4471 gcc_assert (e_out == NULL);
4472 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4473 if (e->flags & EDGE_EH)
4475 gimple *stmt = last_stmt (e->src);
4476 remove_stmt_from_eh_lp (stmt);
4477 remove_edge (e);
4479 else
4480 ei_next (&ei);
4481 goto succeed;
4484 /* If the destination region is a MUST_NOT_THROW, allow the runtime
4485 to handle the abort and allow the blocks to go unreachable. */
4486 if (new_region->type == ERT_MUST_NOT_THROW)
4488 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4489 if (e->flags & EDGE_EH)
4491 gimple *stmt = last_stmt (e->src);
4492 remove_stmt_from_eh_lp (stmt);
4493 add_stmt_to_eh_lp (stmt, new_lp_nr);
4494 remove_edge (e);
4496 else
4497 ei_next (&ei);
4498 goto succeed;
4501 /* Try to redirect the EH edges and merge the PHIs into the destination
4502 landing pad block. If the merge succeeds, we'll already have redirected
4503 all the EH edges. The handler itself will go unreachable if there were
4504 no normal edges. */
4505 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4506 goto succeed;
4508 /* Finally, if all input edges are EH edges, then we can (potentially)
4509 reduce the number of transfers from the runtime by moving the landing
4510 pad from the original region to the new region. This is a win when
4511 we remove the last CLEANUP region along a particular exception
4512 propagation path. Since nothing changes except for the region with
4513 which the landing pad is associated, the PHI nodes do not need to be
4514 adjusted at all. */
4515 if (!has_non_eh_pred)
4517 cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4518 if (dump_file && (dump_flags & TDF_DETAILS))
4519 fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4520 lp->index, new_region->index);
4522 /* ??? The CFG didn't change, but we may have rendered the
4523 old EH region unreachable. Trigger a cleanup there. */
4524 return true;
4527 return ret;
4529 succeed:
4530 if (dump_file && (dump_flags & TDF_DETAILS))
4531 fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4532 remove_eh_landing_pad (lp);
4533 return true;
4536 /* Do a post-order traversal of the EH region tree. Examine each
4537 post_landing_pad block and see if we can eliminate it as empty. */
4539 static bool
4540 cleanup_all_empty_eh (void)
4542 bool changed = false;
4543 eh_landing_pad lp;
4544 int i;
4546 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4547 if (lp)
4548 changed |= cleanup_empty_eh (lp);
4550 return changed;
4553 /* Perform cleanups and lowering of exception handling
4554 1) cleanups regions with handlers doing nothing are optimized out
4555 2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4556 3) Info about regions that are containing instructions, and regions
4557 reachable via local EH edges is collected
4558 4) Eh tree is pruned for regions no longer necessary.
4560 TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4561 Unify those that have the same failure decl and locus.
4564 static unsigned int
4565 execute_cleanup_eh_1 (void)
4567 /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4568 looking up unreachable landing pads. */
4569 remove_unreachable_handlers ();
4571 /* Watch out for the region tree vanishing due to all unreachable. */
4572 if (cfun->eh->region_tree)
4574 bool changed = false;
4576 if (optimize)
4577 changed |= unsplit_all_eh ();
4578 changed |= cleanup_all_empty_eh ();
4580 if (changed)
4582 free_dominance_info (CDI_DOMINATORS);
4583 free_dominance_info (CDI_POST_DOMINATORS);
4585 /* We delayed all basic block deletion, as we may have performed
4586 cleanups on EH edges while non-EH edges were still present. */
4587 delete_unreachable_blocks ();
4589 /* We manipulated the landing pads. Remove any region that no
4590 longer has a landing pad. */
4591 remove_unreachable_handlers_no_lp ();
4593 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4597 return 0;
4600 namespace {
4602 const pass_data pass_data_cleanup_eh =
4604 GIMPLE_PASS, /* type */
4605 "ehcleanup", /* name */
4606 OPTGROUP_NONE, /* optinfo_flags */
4607 TV_TREE_EH, /* tv_id */
4608 PROP_gimple_lcf, /* properties_required */
4609 0, /* properties_provided */
4610 0, /* properties_destroyed */
4611 0, /* todo_flags_start */
4612 0, /* todo_flags_finish */
4615 class pass_cleanup_eh : public gimple_opt_pass
4617 public:
4618 pass_cleanup_eh (gcc::context *ctxt)
4619 : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4622 /* opt_pass methods: */
4623 opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4624 virtual bool gate (function *fun)
4626 return fun->eh != NULL && fun->eh->region_tree != NULL;
4629 virtual unsigned int execute (function *);
4631 }; // class pass_cleanup_eh
4633 unsigned int
4634 pass_cleanup_eh::execute (function *fun)
4636 int ret = execute_cleanup_eh_1 ();
4638 /* If the function no longer needs an EH personality routine
4639 clear it. This exposes cross-language inlining opportunities
4640 and avoids references to a never defined personality routine. */
4641 if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4642 && function_needs_eh_personality (fun) != eh_personality_lang)
4643 DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4645 return ret;
4648 } // anon namespace
4650 gimple_opt_pass *
4651 make_pass_cleanup_eh (gcc::context *ctxt)
4653 return new pass_cleanup_eh (ctxt);
4656 /* Verify that BB containing STMT as the last statement, has precisely the
4657 edge that make_eh_edges would create. */
4659 DEBUG_FUNCTION bool
4660 verify_eh_edges (gimple *stmt)
4662 basic_block bb = gimple_bb (stmt);
4663 eh_landing_pad lp = NULL;
4664 int lp_nr;
4665 edge_iterator ei;
4666 edge e, eh_edge;
4668 lp_nr = lookup_stmt_eh_lp (stmt);
4669 if (lp_nr > 0)
4670 lp = get_eh_landing_pad_from_number (lp_nr);
4672 eh_edge = NULL;
4673 FOR_EACH_EDGE (e, ei, bb->succs)
4675 if (e->flags & EDGE_EH)
4677 if (eh_edge)
4679 error ("BB %i has multiple EH edges", bb->index);
4680 return true;
4682 else
4683 eh_edge = e;
4687 if (lp == NULL)
4689 if (eh_edge)
4691 error ("BB %i can not throw but has an EH edge", bb->index);
4692 return true;
4694 return false;
4697 if (!stmt_could_throw_p (stmt))
4699 error ("BB %i last statement has incorrectly set lp", bb->index);
4700 return true;
4703 if (eh_edge == NULL)
4705 error ("BB %i is missing an EH edge", bb->index);
4706 return true;
4709 if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4711 error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4712 return true;
4715 return false;
4718 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically. */
4720 DEBUG_FUNCTION bool
4721 verify_eh_dispatch_edge (geh_dispatch *stmt)
4723 eh_region r;
4724 eh_catch c;
4725 basic_block src, dst;
4726 bool want_fallthru = true;
4727 edge_iterator ei;
4728 edge e, fall_edge;
4730 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4731 src = gimple_bb (stmt);
4733 FOR_EACH_EDGE (e, ei, src->succs)
4734 gcc_assert (e->aux == NULL);
4736 switch (r->type)
4738 case ERT_TRY:
4739 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4741 dst = label_to_block (c->label);
4742 e = find_edge (src, dst);
4743 if (e == NULL)
4745 error ("BB %i is missing an edge", src->index);
4746 return true;
4748 e->aux = (void *)e;
4750 /* A catch-all handler doesn't have a fallthru. */
4751 if (c->type_list == NULL)
4753 want_fallthru = false;
4754 break;
4757 break;
4759 case ERT_ALLOWED_EXCEPTIONS:
4760 dst = label_to_block (r->u.allowed.label);
4761 e = find_edge (src, dst);
4762 if (e == NULL)
4764 error ("BB %i is missing an edge", src->index);
4765 return true;
4767 e->aux = (void *)e;
4768 break;
4770 default:
4771 gcc_unreachable ();
4774 fall_edge = NULL;
4775 FOR_EACH_EDGE (e, ei, src->succs)
4777 if (e->flags & EDGE_FALLTHRU)
4779 if (fall_edge != NULL)
4781 error ("BB %i too many fallthru edges", src->index);
4782 return true;
4784 fall_edge = e;
4786 else if (e->aux)
4787 e->aux = NULL;
4788 else
4790 error ("BB %i has incorrect edge", src->index);
4791 return true;
4794 if ((fall_edge != NULL) ^ want_fallthru)
4796 error ("BB %i has incorrect fallthru edge", src->index);
4797 return true;
4800 return false;