gcc/ChangeLog:
[official-gcc.git] / gcc / tree-eh.c
blob938197992ceb386592496cf63dcd55db1efa59bd
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_seq_add_stmt (&tf->top_p_seq, x);
1421 tmp = build_int_cst (integer_type_node, fallthru_index);
1422 last_case = build_case_label (tmp, NULL,
1423 create_artificial_label (tf_loc));
1424 case_label_vec.quick_push (last_case);
1425 last_case_index++;
1427 x = gimple_build_label (CASE_LABEL (last_case));
1428 gimple_seq_add_stmt (&switch_body, x);
1430 tmp = lower_try_finally_fallthru_label (tf);
1431 x = gimple_build_goto (tmp);
1432 gimple_set_location (x, tf_loc);
1433 gimple_seq_add_stmt (&switch_body, x);
1436 /* For EH_ELSE, emit the exception path (plus resx) now, then
1437 subsequently we only need consider the normal path. */
1438 if (eh_else)
1440 if (tf->may_throw)
1442 finally = gimple_eh_else_e_body (eh_else);
1443 lower_eh_constructs_1 (state, &finally);
1445 emit_post_landing_pad (&eh_seq, tf->region);
1446 gimple_seq_add_seq (&eh_seq, finally);
1447 emit_resx (&eh_seq, tf->region);
1450 finally = gimple_eh_else_n_body (eh_else);
1452 else if (tf->may_throw)
1454 emit_post_landing_pad (&eh_seq, tf->region);
1456 x = gimple_build_assign (finally_tmp,
1457 build_int_cst (integer_type_node, eh_index));
1458 gimple_seq_add_stmt (&eh_seq, x);
1460 x = gimple_build_goto (finally_label);
1461 gimple_set_location (x, tf_loc);
1462 gimple_seq_add_stmt (&eh_seq, x);
1464 tmp = build_int_cst (integer_type_node, eh_index);
1465 last_case = build_case_label (tmp, NULL,
1466 create_artificial_label (tf_loc));
1467 case_label_vec.quick_push (last_case);
1468 last_case_index++;
1470 x = gimple_build_label (CASE_LABEL (last_case));
1471 gimple_seq_add_stmt (&eh_seq, x);
1472 emit_resx (&eh_seq, tf->region);
1475 x = gimple_build_label (finally_label);
1476 gimple_seq_add_stmt (&tf->top_p_seq, x);
1478 lower_eh_constructs_1 (state, &finally);
1479 gimple_seq_add_seq (&tf->top_p_seq, finally);
1481 /* Redirect each incoming goto edge. */
1482 q = tf->goto_queue;
1483 qe = q + tf->goto_queue_active;
1484 j = last_case_index + tf->may_return;
1485 /* Prepare the assignments to finally_tmp that are executed upon the
1486 entrance through a particular edge. */
1487 for (; q < qe; ++q)
1489 gimple_seq mod = NULL;
1490 int switch_id;
1491 unsigned int case_index;
1493 if (q->index < 0)
1495 x = gimple_build_assign (finally_tmp,
1496 build_int_cst (integer_type_node,
1497 return_index));
1498 gimple_seq_add_stmt (&mod, x);
1499 do_return_redirection (q, finally_label, mod);
1500 switch_id = return_index;
1502 else
1504 x = gimple_build_assign (finally_tmp,
1505 build_int_cst (integer_type_node, q->index));
1506 gimple_seq_add_stmt (&mod, x);
1507 do_goto_redirection (q, finally_label, mod, tf);
1508 switch_id = q->index;
1511 case_index = j + q->index;
1512 if (case_label_vec.length () <= case_index || !case_label_vec[case_index])
1514 tree case_lab;
1515 tmp = build_int_cst (integer_type_node, switch_id);
1516 case_lab = build_case_label (tmp, NULL,
1517 create_artificial_label (tf_loc));
1518 /* We store the cont_stmt in the pointer map, so that we can recover
1519 it in the loop below. */
1520 if (!cont_map)
1521 cont_map = new hash_map<tree, gimple *>;
1522 cont_map->put (case_lab, q->cont_stmt);
1523 case_label_vec.quick_push (case_lab);
1526 for (j = last_case_index; j < last_case_index + nlabels; j++)
1528 gimple *cont_stmt;
1530 last_case = case_label_vec[j];
1532 gcc_assert (last_case);
1533 gcc_assert (cont_map);
1535 cont_stmt = *cont_map->get (last_case);
1537 x = gimple_build_label (CASE_LABEL (last_case));
1538 gimple_seq_add_stmt (&switch_body, x);
1539 gimple_seq_add_stmt (&switch_body, cont_stmt);
1540 maybe_record_in_goto_queue (state, cont_stmt);
1542 if (cont_map)
1543 delete cont_map;
1545 replace_goto_queue (tf);
1547 /* Make sure that the last case is the default label, as one is required.
1548 Then sort the labels, which is also required in GIMPLE. */
1549 CASE_LOW (last_case) = NULL;
1550 tree tem = case_label_vec.pop ();
1551 gcc_assert (tem == last_case);
1552 sort_case_labels (case_label_vec);
1554 /* Build the switch statement, setting last_case to be the default
1555 label. */
1556 switch_stmt = gimple_build_switch (finally_tmp, last_case,
1557 case_label_vec);
1558 gimple_set_location (switch_stmt, finally_loc);
1560 /* Need to link SWITCH_STMT after running replace_goto_queue
1561 due to not wanting to process the same goto stmts twice. */
1562 gimple_seq_add_stmt (&tf->top_p_seq, switch_stmt);
1563 gimple_seq_add_seq (&tf->top_p_seq, switch_body);
1566 /* Decide whether or not we are going to duplicate the finally block.
1567 There are several considerations.
1569 Second, we'd like to prevent egregious code growth. One way to
1570 do this is to estimate the size of the finally block, multiply
1571 that by the number of copies we'd need to make, and compare against
1572 the estimate of the size of the switch machinery we'd have to add. */
1574 static bool
1575 decide_copy_try_finally (int ndests, bool may_throw, gimple_seq finally)
1577 int f_estimate, sw_estimate;
1578 geh_else *eh_else;
1580 /* If there's an EH_ELSE involved, the exception path is separate
1581 and really doesn't come into play for this computation. */
1582 eh_else = get_eh_else (finally);
1583 if (eh_else)
1585 ndests -= may_throw;
1586 finally = gimple_eh_else_n_body (eh_else);
1589 if (!optimize)
1591 gimple_stmt_iterator gsi;
1593 if (ndests == 1)
1594 return true;
1596 for (gsi = gsi_start (finally); !gsi_end_p (gsi); gsi_next (&gsi))
1598 /* Duplicate __builtin_stack_restore in the hope of eliminating it
1599 on the EH paths and, consequently, useless cleanups. */
1600 gimple *stmt = gsi_stmt (gsi);
1601 if (!is_gimple_debug (stmt)
1602 && !gimple_clobber_p (stmt)
1603 && !gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
1604 return false;
1606 return true;
1609 /* Finally estimate N times, plus N gotos. */
1610 f_estimate = estimate_num_insns_seq (finally, &eni_size_weights);
1611 f_estimate = (f_estimate + 1) * ndests;
1613 /* Switch statement (cost 10), N variable assignments, N gotos. */
1614 sw_estimate = 10 + 2 * ndests;
1616 /* Optimize for size clearly wants our best guess. */
1617 if (optimize_function_for_size_p (cfun))
1618 return f_estimate < sw_estimate;
1620 /* ??? These numbers are completely made up so far. */
1621 if (optimize > 1)
1622 return f_estimate < 100 || f_estimate < sw_estimate * 2;
1623 else
1624 return f_estimate < 40 || f_estimate * 2 < sw_estimate * 3;
1627 /* REG is the enclosing region for a possible cleanup region, or the region
1628 itself. Returns TRUE if such a region would be unreachable.
1630 Cleanup regions within a must-not-throw region aren't actually reachable
1631 even if there are throwing stmts within them, because the personality
1632 routine will call terminate before unwinding. */
1634 static bool
1635 cleanup_is_dead_in (eh_region reg)
1637 while (reg && reg->type == ERT_CLEANUP)
1638 reg = reg->outer;
1639 return (reg && reg->type == ERT_MUST_NOT_THROW);
1642 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_FINALLY nodes
1643 to a sequence of labels and blocks, plus the exception region trees
1644 that record all the magic. This is complicated by the need to
1645 arrange for the FINALLY block to be executed on all exits. */
1647 static gimple_seq
1648 lower_try_finally (struct leh_state *state, gtry *tp)
1650 struct leh_tf_state this_tf;
1651 struct leh_state this_state;
1652 int ndests;
1653 gimple_seq old_eh_seq;
1655 /* Process the try block. */
1657 memset (&this_tf, 0, sizeof (this_tf));
1658 this_tf.try_finally_expr = tp;
1659 this_tf.top_p = tp;
1660 this_tf.outer = state;
1661 if (using_eh_for_cleanups_p () && !cleanup_is_dead_in (state->cur_region))
1663 this_tf.region = gen_eh_region_cleanup (state->cur_region);
1664 this_state.cur_region = this_tf.region;
1666 else
1668 this_tf.region = NULL;
1669 this_state.cur_region = state->cur_region;
1672 this_state.ehp_region = state->ehp_region;
1673 this_state.tf = &this_tf;
1675 old_eh_seq = eh_seq;
1676 eh_seq = NULL;
1678 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1680 /* Determine if the try block is escaped through the bottom. */
1681 this_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1683 /* Determine if any exceptions are possible within the try block. */
1684 if (this_tf.region)
1685 this_tf.may_throw = eh_region_may_contain_throw (this_tf.region);
1686 if (this_tf.may_throw)
1687 honor_protect_cleanup_actions (state, &this_state, &this_tf);
1689 /* Determine how many edges (still) reach the finally block. Or rather,
1690 how many destinations are reached by the finally block. Use this to
1691 determine how we process the finally block itself. */
1693 ndests = this_tf.dest_array.length ();
1694 ndests += this_tf.may_fallthru;
1695 ndests += this_tf.may_return;
1696 ndests += this_tf.may_throw;
1698 /* If the FINALLY block is not reachable, dike it out. */
1699 if (ndests == 0)
1701 gimple_seq_add_seq (&this_tf.top_p_seq, gimple_try_eval (tp));
1702 gimple_try_set_cleanup (tp, NULL);
1704 /* If the finally block doesn't fall through, then any destination
1705 we might try to impose there isn't reached either. There may be
1706 some minor amount of cleanup and redirection still needed. */
1707 else if (!gimple_seq_may_fallthru (gimple_try_cleanup (tp)))
1708 lower_try_finally_nofallthru (state, &this_tf);
1710 /* We can easily special-case redirection to a single destination. */
1711 else if (ndests == 1)
1712 lower_try_finally_onedest (state, &this_tf);
1713 else if (decide_copy_try_finally (ndests, this_tf.may_throw,
1714 gimple_try_cleanup (tp)))
1715 lower_try_finally_copy (state, &this_tf);
1716 else
1717 lower_try_finally_switch (state, &this_tf);
1719 /* If someone requested we add a label at the end of the transformed
1720 block, do so. */
1721 if (this_tf.fallthru_label)
1723 /* This must be reached only if ndests == 0. */
1724 gimple *x = gimple_build_label (this_tf.fallthru_label);
1725 gimple_seq_add_stmt (&this_tf.top_p_seq, x);
1728 this_tf.dest_array.release ();
1729 free (this_tf.goto_queue);
1730 if (this_tf.goto_queue_map)
1731 delete this_tf.goto_queue_map;
1733 /* If there was an old (aka outer) eh_seq, append the current eh_seq.
1734 If there was no old eh_seq, then the append is trivially already done. */
1735 if (old_eh_seq)
1737 if (eh_seq == NULL)
1738 eh_seq = old_eh_seq;
1739 else
1741 gimple_seq new_eh_seq = eh_seq;
1742 eh_seq = old_eh_seq;
1743 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1747 return this_tf.top_p_seq;
1750 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY_CATCH with a
1751 list of GIMPLE_CATCH to a sequence of labels and blocks, plus the
1752 exception region trees that records all the magic. */
1754 static gimple_seq
1755 lower_catch (struct leh_state *state, gtry *tp)
1757 eh_region try_region = NULL;
1758 struct leh_state this_state = *state;
1759 gimple_stmt_iterator gsi;
1760 tree out_label;
1761 gimple_seq new_seq, cleanup;
1762 gimple *x;
1763 location_t try_catch_loc = gimple_location (tp);
1765 if (flag_exceptions)
1767 try_region = gen_eh_region_try (state->cur_region);
1768 this_state.cur_region = try_region;
1771 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1773 if (!eh_region_may_contain_throw (try_region))
1774 return gimple_try_eval (tp);
1776 new_seq = NULL;
1777 emit_eh_dispatch (&new_seq, try_region);
1778 emit_resx (&new_seq, try_region);
1780 this_state.cur_region = state->cur_region;
1781 this_state.ehp_region = try_region;
1783 /* Add eh_seq from lowering EH in the cleanup sequence after the cleanup
1784 itself, so that e.g. for coverage purposes the nested cleanups don't
1785 appear before the cleanup body. See PR64634 for details. */
1786 gimple_seq old_eh_seq = eh_seq;
1787 eh_seq = NULL;
1789 out_label = NULL;
1790 cleanup = gimple_try_cleanup (tp);
1791 for (gsi = gsi_start (cleanup);
1792 !gsi_end_p (gsi);
1793 gsi_next (&gsi))
1795 eh_catch c;
1796 gcatch *catch_stmt;
1797 gimple_seq handler;
1799 catch_stmt = as_a <gcatch *> (gsi_stmt (gsi));
1800 c = gen_eh_region_catch (try_region, gimple_catch_types (catch_stmt));
1802 handler = gimple_catch_handler (catch_stmt);
1803 lower_eh_constructs_1 (&this_state, &handler);
1805 c->label = create_artificial_label (UNKNOWN_LOCATION);
1806 x = gimple_build_label (c->label);
1807 gimple_seq_add_stmt (&new_seq, x);
1809 gimple_seq_add_seq (&new_seq, handler);
1811 if (gimple_seq_may_fallthru (new_seq))
1813 if (!out_label)
1814 out_label = create_artificial_label (try_catch_loc);
1816 x = gimple_build_goto (out_label);
1817 gimple_seq_add_stmt (&new_seq, x);
1819 if (!c->type_list)
1820 break;
1823 gimple_try_set_cleanup (tp, new_seq);
1825 gimple_seq new_eh_seq = eh_seq;
1826 eh_seq = old_eh_seq;
1827 gimple_seq ret_seq = frob_into_branch_around (tp, try_region, out_label);
1828 gimple_seq_add_seq (&eh_seq, new_eh_seq);
1829 return ret_seq;
1832 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with a
1833 GIMPLE_EH_FILTER to a sequence of labels and blocks, plus the exception
1834 region trees that record all the magic. */
1836 static gimple_seq
1837 lower_eh_filter (struct leh_state *state, gtry *tp)
1839 struct leh_state this_state = *state;
1840 eh_region this_region = NULL;
1841 gimple *inner, *x;
1842 gimple_seq new_seq;
1844 inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1846 if (flag_exceptions)
1848 this_region = gen_eh_region_allowed (state->cur_region,
1849 gimple_eh_filter_types (inner));
1850 this_state.cur_region = this_region;
1853 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1855 if (!eh_region_may_contain_throw (this_region))
1856 return gimple_try_eval (tp);
1858 new_seq = NULL;
1859 this_state.cur_region = state->cur_region;
1860 this_state.ehp_region = this_region;
1862 emit_eh_dispatch (&new_seq, this_region);
1863 emit_resx (&new_seq, this_region);
1865 this_region->u.allowed.label = create_artificial_label (UNKNOWN_LOCATION);
1866 x = gimple_build_label (this_region->u.allowed.label);
1867 gimple_seq_add_stmt (&new_seq, x);
1869 lower_eh_constructs_1 (&this_state, gimple_eh_filter_failure_ptr (inner));
1870 gimple_seq_add_seq (&new_seq, gimple_eh_filter_failure (inner));
1872 gimple_try_set_cleanup (tp, new_seq);
1874 return frob_into_branch_around (tp, this_region, NULL);
1877 /* A subroutine of lower_eh_constructs_1. Lower a GIMPLE_TRY with
1878 an GIMPLE_EH_MUST_NOT_THROW to a sequence of labels and blocks,
1879 plus the exception region trees that record all the magic. */
1881 static gimple_seq
1882 lower_eh_must_not_throw (struct leh_state *state, gtry *tp)
1884 struct leh_state this_state = *state;
1886 if (flag_exceptions)
1888 gimple *inner = gimple_seq_first_stmt (gimple_try_cleanup (tp));
1889 eh_region this_region;
1891 this_region = gen_eh_region_must_not_throw (state->cur_region);
1892 this_region->u.must_not_throw.failure_decl
1893 = gimple_eh_must_not_throw_fndecl (
1894 as_a <geh_mnt *> (inner));
1895 this_region->u.must_not_throw.failure_loc
1896 = LOCATION_LOCUS (gimple_location (tp));
1898 /* In order to get mangling applied to this decl, we must mark it
1899 used now. Otherwise, pass_ipa_free_lang_data won't think it
1900 needs to happen. */
1901 TREE_USED (this_region->u.must_not_throw.failure_decl) = 1;
1903 this_state.cur_region = this_region;
1906 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1908 return gimple_try_eval (tp);
1911 /* Implement a cleanup expression. This is similar to try-finally,
1912 except that we only execute the cleanup block for exception edges. */
1914 static gimple_seq
1915 lower_cleanup (struct leh_state *state, gtry *tp)
1917 struct leh_state this_state = *state;
1918 eh_region this_region = NULL;
1919 struct leh_tf_state fake_tf;
1920 gimple_seq result;
1921 bool cleanup_dead = cleanup_is_dead_in (state->cur_region);
1923 if (flag_exceptions && !cleanup_dead)
1925 this_region = gen_eh_region_cleanup (state->cur_region);
1926 this_state.cur_region = this_region;
1929 lower_eh_constructs_1 (&this_state, gimple_try_eval_ptr (tp));
1931 if (cleanup_dead || !eh_region_may_contain_throw (this_region))
1932 return gimple_try_eval (tp);
1934 /* Build enough of a try-finally state so that we can reuse
1935 honor_protect_cleanup_actions. */
1936 memset (&fake_tf, 0, sizeof (fake_tf));
1937 fake_tf.top_p = fake_tf.try_finally_expr = tp;
1938 fake_tf.outer = state;
1939 fake_tf.region = this_region;
1940 fake_tf.may_fallthru = gimple_seq_may_fallthru (gimple_try_eval (tp));
1941 fake_tf.may_throw = true;
1943 honor_protect_cleanup_actions (state, NULL, &fake_tf);
1945 if (fake_tf.may_throw)
1947 /* In this case honor_protect_cleanup_actions had nothing to do,
1948 and we should process this normally. */
1949 lower_eh_constructs_1 (state, gimple_try_cleanup_ptr (tp));
1950 result = frob_into_branch_around (tp, this_region,
1951 fake_tf.fallthru_label);
1953 else
1955 /* In this case honor_protect_cleanup_actions did nearly all of
1956 the work. All we have left is to append the fallthru_label. */
1958 result = gimple_try_eval (tp);
1959 if (fake_tf.fallthru_label)
1961 gimple *x = gimple_build_label (fake_tf.fallthru_label);
1962 gimple_seq_add_stmt (&result, x);
1965 return result;
1968 /* Main loop for lowering eh constructs. Also moves gsi to the next
1969 statement. */
1971 static void
1972 lower_eh_constructs_2 (struct leh_state *state, gimple_stmt_iterator *gsi)
1974 gimple_seq replace;
1975 gimple *x;
1976 gimple *stmt = gsi_stmt (*gsi);
1978 switch (gimple_code (stmt))
1980 case GIMPLE_CALL:
1982 tree fndecl = gimple_call_fndecl (stmt);
1983 tree rhs, lhs;
1985 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
1986 switch (DECL_FUNCTION_CODE (fndecl))
1988 case BUILT_IN_EH_POINTER:
1989 /* The front end may have generated a call to
1990 __builtin_eh_pointer (0) within a catch region. Replace
1991 this zero argument with the current catch region number. */
1992 if (state->ehp_region)
1994 tree nr = build_int_cst (integer_type_node,
1995 state->ehp_region->index);
1996 gimple_call_set_arg (stmt, 0, nr);
1998 else
2000 /* The user has dome something silly. Remove it. */
2001 rhs = null_pointer_node;
2002 goto do_replace;
2004 break;
2006 case BUILT_IN_EH_FILTER:
2007 /* ??? This should never appear, but since it's a builtin it
2008 is accessible to abuse by users. Just remove it and
2009 replace the use with the arbitrary value zero. */
2010 rhs = build_int_cst (TREE_TYPE (TREE_TYPE (fndecl)), 0);
2011 do_replace:
2012 lhs = gimple_call_lhs (stmt);
2013 x = gimple_build_assign (lhs, rhs);
2014 gsi_insert_before (gsi, x, GSI_SAME_STMT);
2015 /* FALLTHRU */
2017 case BUILT_IN_EH_COPY_VALUES:
2018 /* Likewise this should not appear. Remove it. */
2019 gsi_remove (gsi, true);
2020 return;
2022 default:
2023 break;
2026 /* FALLTHRU */
2028 case GIMPLE_ASSIGN:
2029 /* If the stmt can throw use a new temporary for the assignment
2030 to a LHS. This makes sure the old value of the LHS is
2031 available on the EH edge. Only do so for statements that
2032 potentially fall through (no noreturn calls e.g.), otherwise
2033 this new assignment might create fake fallthru regions. */
2034 if (stmt_could_throw_p (stmt)
2035 && gimple_has_lhs (stmt)
2036 && gimple_stmt_may_fallthru (stmt)
2037 && !tree_could_throw_p (gimple_get_lhs (stmt))
2038 && is_gimple_reg_type (TREE_TYPE (gimple_get_lhs (stmt))))
2040 tree lhs = gimple_get_lhs (stmt);
2041 tree tmp = create_tmp_var (TREE_TYPE (lhs));
2042 gimple *s = gimple_build_assign (lhs, tmp);
2043 gimple_set_location (s, gimple_location (stmt));
2044 gimple_set_block (s, gimple_block (stmt));
2045 gimple_set_lhs (stmt, tmp);
2046 if (TREE_CODE (TREE_TYPE (tmp)) == COMPLEX_TYPE
2047 || TREE_CODE (TREE_TYPE (tmp)) == VECTOR_TYPE)
2048 DECL_GIMPLE_REG_P (tmp) = 1;
2049 gsi_insert_after (gsi, s, GSI_SAME_STMT);
2051 /* Look for things that can throw exceptions, and record them. */
2052 if (state->cur_region && stmt_could_throw_p (stmt))
2054 record_stmt_eh_region (state->cur_region, stmt);
2055 note_eh_region_may_contain_throw (state->cur_region);
2057 break;
2059 case GIMPLE_COND:
2060 case GIMPLE_GOTO:
2061 case GIMPLE_RETURN:
2062 maybe_record_in_goto_queue (state, stmt);
2063 break;
2065 case GIMPLE_SWITCH:
2066 verify_norecord_switch_expr (state, as_a <gswitch *> (stmt));
2067 break;
2069 case GIMPLE_TRY:
2071 gtry *try_stmt = as_a <gtry *> (stmt);
2072 if (gimple_try_kind (try_stmt) == GIMPLE_TRY_FINALLY)
2073 replace = lower_try_finally (state, try_stmt);
2074 else
2076 x = gimple_seq_first_stmt (gimple_try_cleanup (try_stmt));
2077 if (!x)
2079 replace = gimple_try_eval (try_stmt);
2080 lower_eh_constructs_1 (state, &replace);
2082 else
2083 switch (gimple_code (x))
2085 case GIMPLE_CATCH:
2086 replace = lower_catch (state, try_stmt);
2087 break;
2088 case GIMPLE_EH_FILTER:
2089 replace = lower_eh_filter (state, try_stmt);
2090 break;
2091 case GIMPLE_EH_MUST_NOT_THROW:
2092 replace = lower_eh_must_not_throw (state, try_stmt);
2093 break;
2094 case GIMPLE_EH_ELSE:
2095 /* This code is only valid with GIMPLE_TRY_FINALLY. */
2096 gcc_unreachable ();
2097 default:
2098 replace = lower_cleanup (state, try_stmt);
2099 break;
2104 /* Remove the old stmt and insert the transformed sequence
2105 instead. */
2106 gsi_insert_seq_before (gsi, replace, GSI_SAME_STMT);
2107 gsi_remove (gsi, true);
2109 /* Return since we don't want gsi_next () */
2110 return;
2112 case GIMPLE_EH_ELSE:
2113 /* We should be eliminating this in lower_try_finally et al. */
2114 gcc_unreachable ();
2116 default:
2117 /* A type, a decl, or some kind of statement that we're not
2118 interested in. Don't walk them. */
2119 break;
2122 gsi_next (gsi);
2125 /* A helper to unwrap a gimple_seq and feed stmts to lower_eh_constructs_2. */
2127 static void
2128 lower_eh_constructs_1 (struct leh_state *state, gimple_seq *pseq)
2130 gimple_stmt_iterator gsi;
2131 for (gsi = gsi_start (*pseq); !gsi_end_p (gsi);)
2132 lower_eh_constructs_2 (state, &gsi);
2135 namespace {
2137 const pass_data pass_data_lower_eh =
2139 GIMPLE_PASS, /* type */
2140 "eh", /* name */
2141 OPTGROUP_NONE, /* optinfo_flags */
2142 TV_TREE_EH, /* tv_id */
2143 PROP_gimple_lcf, /* properties_required */
2144 PROP_gimple_leh, /* properties_provided */
2145 0, /* properties_destroyed */
2146 0, /* todo_flags_start */
2147 0, /* todo_flags_finish */
2150 class pass_lower_eh : public gimple_opt_pass
2152 public:
2153 pass_lower_eh (gcc::context *ctxt)
2154 : gimple_opt_pass (pass_data_lower_eh, ctxt)
2157 /* opt_pass methods: */
2158 virtual unsigned int execute (function *);
2160 }; // class pass_lower_eh
2162 unsigned int
2163 pass_lower_eh::execute (function *fun)
2165 struct leh_state null_state;
2166 gimple_seq bodyp;
2168 bodyp = gimple_body (current_function_decl);
2169 if (bodyp == NULL)
2170 return 0;
2172 finally_tree = new hash_table<finally_tree_hasher> (31);
2173 eh_region_may_contain_throw_map = BITMAP_ALLOC (NULL);
2174 memset (&null_state, 0, sizeof (null_state));
2176 collect_finally_tree_1 (bodyp, NULL);
2177 lower_eh_constructs_1 (&null_state, &bodyp);
2178 gimple_set_body (current_function_decl, bodyp);
2180 /* We assume there's a return statement, or something, at the end of
2181 the function, and thus ploping the EH sequence afterward won't
2182 change anything. */
2183 gcc_assert (!gimple_seq_may_fallthru (bodyp));
2184 gimple_seq_add_seq (&bodyp, eh_seq);
2186 /* We assume that since BODYP already existed, adding EH_SEQ to it
2187 didn't change its value, and we don't have to re-set the function. */
2188 gcc_assert (bodyp == gimple_body (current_function_decl));
2190 delete finally_tree;
2191 finally_tree = NULL;
2192 BITMAP_FREE (eh_region_may_contain_throw_map);
2193 eh_seq = NULL;
2195 /* If this function needs a language specific EH personality routine
2196 and the frontend didn't already set one do so now. */
2197 if (function_needs_eh_personality (fun) == eh_personality_lang
2198 && !DECL_FUNCTION_PERSONALITY (current_function_decl))
2199 DECL_FUNCTION_PERSONALITY (current_function_decl)
2200 = lang_hooks.eh_personality ();
2202 return 0;
2205 } // anon namespace
2207 gimple_opt_pass *
2208 make_pass_lower_eh (gcc::context *ctxt)
2210 return new pass_lower_eh (ctxt);
2213 /* Create the multiple edges from an EH_DISPATCH statement to all of
2214 the possible handlers for its EH region. Return true if there's
2215 no fallthru edge; false if there is. */
2217 bool
2218 make_eh_dispatch_edges (geh_dispatch *stmt)
2220 eh_region r;
2221 eh_catch c;
2222 basic_block src, dst;
2224 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2225 src = gimple_bb (stmt);
2227 switch (r->type)
2229 case ERT_TRY:
2230 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2232 dst = label_to_block (c->label);
2233 make_edge (src, dst, 0);
2235 /* A catch-all handler doesn't have a fallthru. */
2236 if (c->type_list == NULL)
2237 return false;
2239 break;
2241 case ERT_ALLOWED_EXCEPTIONS:
2242 dst = label_to_block (r->u.allowed.label);
2243 make_edge (src, dst, 0);
2244 break;
2246 default:
2247 gcc_unreachable ();
2250 return true;
2253 /* Create the single EH edge from STMT to its nearest landing pad,
2254 if there is such a landing pad within the current function. */
2256 void
2257 make_eh_edges (gimple *stmt)
2259 basic_block src, dst;
2260 eh_landing_pad lp;
2261 int lp_nr;
2263 lp_nr = lookup_stmt_eh_lp (stmt);
2264 if (lp_nr <= 0)
2265 return;
2267 lp = get_eh_landing_pad_from_number (lp_nr);
2268 gcc_assert (lp != NULL);
2270 src = gimple_bb (stmt);
2271 dst = label_to_block (lp->post_landing_pad);
2272 make_edge (src, dst, EDGE_EH);
2275 /* Do the work in redirecting EDGE_IN to NEW_BB within the EH region tree;
2276 do not actually perform the final edge redirection.
2278 CHANGE_REGION is true when we're being called from cleanup_empty_eh and
2279 we intend to change the destination EH region as well; this means
2280 EH_LANDING_PAD_NR must already be set on the destination block label.
2281 If false, we're being called from generic cfg manipulation code and we
2282 should preserve our place within the region tree. */
2284 static void
2285 redirect_eh_edge_1 (edge edge_in, basic_block new_bb, bool change_region)
2287 eh_landing_pad old_lp, new_lp;
2288 basic_block old_bb;
2289 gimple *throw_stmt;
2290 int old_lp_nr, new_lp_nr;
2291 tree old_label, new_label;
2292 edge_iterator ei;
2293 edge e;
2295 old_bb = edge_in->dest;
2296 old_label = gimple_block_label (old_bb);
2297 old_lp_nr = EH_LANDING_PAD_NR (old_label);
2298 gcc_assert (old_lp_nr > 0);
2299 old_lp = get_eh_landing_pad_from_number (old_lp_nr);
2301 throw_stmt = last_stmt (edge_in->src);
2302 gcc_assert (lookup_stmt_eh_lp (throw_stmt) == old_lp_nr);
2304 new_label = gimple_block_label (new_bb);
2306 /* Look for an existing region that might be using NEW_BB already. */
2307 new_lp_nr = EH_LANDING_PAD_NR (new_label);
2308 if (new_lp_nr)
2310 new_lp = get_eh_landing_pad_from_number (new_lp_nr);
2311 gcc_assert (new_lp);
2313 /* Unless CHANGE_REGION is true, the new and old landing pad
2314 had better be associated with the same EH region. */
2315 gcc_assert (change_region || new_lp->region == old_lp->region);
2317 else
2319 new_lp = NULL;
2320 gcc_assert (!change_region);
2323 /* Notice when we redirect the last EH edge away from OLD_BB. */
2324 FOR_EACH_EDGE (e, ei, old_bb->preds)
2325 if (e != edge_in && (e->flags & EDGE_EH))
2326 break;
2328 if (new_lp)
2330 /* NEW_LP already exists. If there are still edges into OLD_LP,
2331 there's nothing to do with the EH tree. If there are no more
2332 edges into OLD_LP, then we want to remove OLD_LP as it is unused.
2333 If CHANGE_REGION is true, then our caller is expecting to remove
2334 the landing pad. */
2335 if (e == NULL && !change_region)
2336 remove_eh_landing_pad (old_lp);
2338 else
2340 /* No correct landing pad exists. If there are no more edges
2341 into OLD_LP, then we can simply re-use the existing landing pad.
2342 Otherwise, we have to create a new landing pad. */
2343 if (e == NULL)
2345 EH_LANDING_PAD_NR (old_lp->post_landing_pad) = 0;
2346 new_lp = old_lp;
2348 else
2349 new_lp = gen_eh_landing_pad (old_lp->region);
2350 new_lp->post_landing_pad = new_label;
2351 EH_LANDING_PAD_NR (new_label) = new_lp->index;
2354 /* Maybe move the throwing statement to the new region. */
2355 if (old_lp != new_lp)
2357 remove_stmt_from_eh_lp (throw_stmt);
2358 add_stmt_to_eh_lp (throw_stmt, new_lp->index);
2362 /* Redirect EH edge E to NEW_BB. */
2364 edge
2365 redirect_eh_edge (edge edge_in, basic_block new_bb)
2367 redirect_eh_edge_1 (edge_in, new_bb, false);
2368 return ssa_redirect_edge (edge_in, new_bb);
2371 /* This is a subroutine of gimple_redirect_edge_and_branch. Update the
2372 labels for redirecting a non-fallthru EH_DISPATCH edge E to NEW_BB.
2373 The actual edge update will happen in the caller. */
2375 void
2376 redirect_eh_dispatch_edge (geh_dispatch *stmt, edge e, basic_block new_bb)
2378 tree new_lab = gimple_block_label (new_bb);
2379 bool any_changed = false;
2380 basic_block old_bb;
2381 eh_region r;
2382 eh_catch c;
2384 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
2385 switch (r->type)
2387 case ERT_TRY:
2388 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
2390 old_bb = label_to_block (c->label);
2391 if (old_bb == e->dest)
2393 c->label = new_lab;
2394 any_changed = true;
2397 break;
2399 case ERT_ALLOWED_EXCEPTIONS:
2400 old_bb = label_to_block (r->u.allowed.label);
2401 gcc_assert (old_bb == e->dest);
2402 r->u.allowed.label = new_lab;
2403 any_changed = true;
2404 break;
2406 default:
2407 gcc_unreachable ();
2410 gcc_assert (any_changed);
2413 /* Helper function for operation_could_trap_p and stmt_could_throw_p. */
2415 bool
2416 operation_could_trap_helper_p (enum tree_code op,
2417 bool fp_operation,
2418 bool honor_trapv,
2419 bool honor_nans,
2420 bool honor_snans,
2421 tree divisor,
2422 bool *handled)
2424 *handled = true;
2425 switch (op)
2427 case TRUNC_DIV_EXPR:
2428 case CEIL_DIV_EXPR:
2429 case FLOOR_DIV_EXPR:
2430 case ROUND_DIV_EXPR:
2431 case EXACT_DIV_EXPR:
2432 case CEIL_MOD_EXPR:
2433 case FLOOR_MOD_EXPR:
2434 case ROUND_MOD_EXPR:
2435 case TRUNC_MOD_EXPR:
2436 case RDIV_EXPR:
2437 if (honor_snans || honor_trapv)
2438 return true;
2439 if (fp_operation)
2440 return flag_trapping_math;
2441 if (!TREE_CONSTANT (divisor) || integer_zerop (divisor))
2442 return true;
2443 return false;
2445 case LT_EXPR:
2446 case LE_EXPR:
2447 case GT_EXPR:
2448 case GE_EXPR:
2449 case LTGT_EXPR:
2450 /* Some floating point comparisons may trap. */
2451 return honor_nans;
2453 case EQ_EXPR:
2454 case NE_EXPR:
2455 case UNORDERED_EXPR:
2456 case ORDERED_EXPR:
2457 case UNLT_EXPR:
2458 case UNLE_EXPR:
2459 case UNGT_EXPR:
2460 case UNGE_EXPR:
2461 case UNEQ_EXPR:
2462 return honor_snans;
2464 case NEGATE_EXPR:
2465 case ABS_EXPR:
2466 case CONJ_EXPR:
2467 /* These operations don't trap with floating point. */
2468 if (honor_trapv)
2469 return true;
2470 return false;
2472 case PLUS_EXPR:
2473 case MINUS_EXPR:
2474 case MULT_EXPR:
2475 /* Any floating arithmetic may trap. */
2476 if (fp_operation && flag_trapping_math)
2477 return true;
2478 if (honor_trapv)
2479 return true;
2480 return false;
2482 case COMPLEX_EXPR:
2483 case CONSTRUCTOR:
2484 /* Constructing an object cannot trap. */
2485 return false;
2487 default:
2488 /* Any floating arithmetic may trap. */
2489 if (fp_operation && flag_trapping_math)
2490 return true;
2492 *handled = false;
2493 return false;
2497 /* Return true if operation OP may trap. FP_OPERATION is true if OP is applied
2498 on floating-point values. HONOR_TRAPV is true if OP is applied on integer
2499 type operands that may trap. If OP is a division operator, DIVISOR contains
2500 the value of the divisor. */
2502 bool
2503 operation_could_trap_p (enum tree_code op, bool fp_operation, bool honor_trapv,
2504 tree divisor)
2506 bool honor_nans = (fp_operation && flag_trapping_math
2507 && !flag_finite_math_only);
2508 bool honor_snans = fp_operation && flag_signaling_nans != 0;
2509 bool handled;
2511 if (TREE_CODE_CLASS (op) != tcc_comparison
2512 && TREE_CODE_CLASS (op) != tcc_unary
2513 && TREE_CODE_CLASS (op) != tcc_binary
2514 && op != FMA_EXPR)
2515 return false;
2517 return operation_could_trap_helper_p (op, fp_operation, honor_trapv,
2518 honor_nans, honor_snans, divisor,
2519 &handled);
2523 /* Returns true if it is possible to prove that the index of
2524 an array access REF (an ARRAY_REF expression) falls into the
2525 array bounds. */
2527 static bool
2528 in_array_bounds_p (tree ref)
2530 tree idx = TREE_OPERAND (ref, 1);
2531 tree min, max;
2533 if (TREE_CODE (idx) != INTEGER_CST)
2534 return false;
2536 min = array_ref_low_bound (ref);
2537 max = array_ref_up_bound (ref);
2538 if (!min
2539 || !max
2540 || TREE_CODE (min) != INTEGER_CST
2541 || TREE_CODE (max) != INTEGER_CST)
2542 return false;
2544 if (tree_int_cst_lt (idx, min)
2545 || tree_int_cst_lt (max, idx))
2546 return false;
2548 return true;
2551 /* Returns true if it is possible to prove that the range of
2552 an array access REF (an ARRAY_RANGE_REF expression) falls
2553 into the array bounds. */
2555 static bool
2556 range_in_array_bounds_p (tree ref)
2558 tree domain_type = TYPE_DOMAIN (TREE_TYPE (ref));
2559 tree range_min, range_max, min, max;
2561 range_min = TYPE_MIN_VALUE (domain_type);
2562 range_max = TYPE_MAX_VALUE (domain_type);
2563 if (!range_min
2564 || !range_max
2565 || TREE_CODE (range_min) != INTEGER_CST
2566 || TREE_CODE (range_max) != INTEGER_CST)
2567 return false;
2569 min = array_ref_low_bound (ref);
2570 max = array_ref_up_bound (ref);
2571 if (!min
2572 || !max
2573 || TREE_CODE (min) != INTEGER_CST
2574 || TREE_CODE (max) != INTEGER_CST)
2575 return false;
2577 if (tree_int_cst_lt (range_min, min)
2578 || tree_int_cst_lt (max, range_max))
2579 return false;
2581 return true;
2584 /* Return true if EXPR can trap, as in dereferencing an invalid pointer
2585 location or floating point arithmetic. C.f. the rtl version, may_trap_p.
2586 This routine expects only GIMPLE lhs or rhs input. */
2588 bool
2589 tree_could_trap_p (tree expr)
2591 enum tree_code code;
2592 bool fp_operation = false;
2593 bool honor_trapv = false;
2594 tree t, base, div = NULL_TREE;
2596 if (!expr)
2597 return false;
2599 code = TREE_CODE (expr);
2600 t = TREE_TYPE (expr);
2602 if (t)
2604 if (COMPARISON_CLASS_P (expr))
2605 fp_operation = FLOAT_TYPE_P (TREE_TYPE (TREE_OPERAND (expr, 0)));
2606 else
2607 fp_operation = FLOAT_TYPE_P (t);
2608 honor_trapv = INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t);
2611 if (TREE_CODE_CLASS (code) == tcc_binary)
2612 div = TREE_OPERAND (expr, 1);
2613 if (operation_could_trap_p (code, fp_operation, honor_trapv, div))
2614 return true;
2616 restart:
2617 switch (code)
2619 case COMPONENT_REF:
2620 case REALPART_EXPR:
2621 case IMAGPART_EXPR:
2622 case BIT_FIELD_REF:
2623 case VIEW_CONVERT_EXPR:
2624 case WITH_SIZE_EXPR:
2625 expr = TREE_OPERAND (expr, 0);
2626 code = TREE_CODE (expr);
2627 goto restart;
2629 case ARRAY_RANGE_REF:
2630 base = TREE_OPERAND (expr, 0);
2631 if (tree_could_trap_p (base))
2632 return true;
2633 if (TREE_THIS_NOTRAP (expr))
2634 return false;
2635 return !range_in_array_bounds_p (expr);
2637 case ARRAY_REF:
2638 base = TREE_OPERAND (expr, 0);
2639 if (tree_could_trap_p (base))
2640 return true;
2641 if (TREE_THIS_NOTRAP (expr))
2642 return false;
2643 return !in_array_bounds_p (expr);
2645 case TARGET_MEM_REF:
2646 case MEM_REF:
2647 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR
2648 && tree_could_trap_p (TREE_OPERAND (TREE_OPERAND (expr, 0), 0)))
2649 return true;
2650 if (TREE_THIS_NOTRAP (expr))
2651 return false;
2652 /* We cannot prove that the access is in-bounds when we have
2653 variable-index TARGET_MEM_REFs. */
2654 if (code == TARGET_MEM_REF
2655 && (TMR_INDEX (expr) || TMR_INDEX2 (expr)))
2656 return true;
2657 if (TREE_CODE (TREE_OPERAND (expr, 0)) == ADDR_EXPR)
2659 tree base = TREE_OPERAND (TREE_OPERAND (expr, 0), 0);
2660 offset_int off = mem_ref_offset (expr);
2661 if (wi::neg_p (off, SIGNED))
2662 return true;
2663 if (TREE_CODE (base) == STRING_CST)
2664 return wi::leu_p (TREE_STRING_LENGTH (base), off);
2665 else if (DECL_SIZE_UNIT (base) == NULL_TREE
2666 || TREE_CODE (DECL_SIZE_UNIT (base)) != INTEGER_CST
2667 || wi::leu_p (wi::to_offset (DECL_SIZE_UNIT (base)), off))
2668 return true;
2669 /* Now we are sure the first byte of the access is inside
2670 the object. */
2671 return false;
2673 return true;
2675 case INDIRECT_REF:
2676 return !TREE_THIS_NOTRAP (expr);
2678 case ASM_EXPR:
2679 return TREE_THIS_VOLATILE (expr);
2681 case CALL_EXPR:
2682 t = get_callee_fndecl (expr);
2683 /* Assume that calls to weak functions may trap. */
2684 if (!t || !DECL_P (t))
2685 return true;
2686 if (DECL_WEAK (t))
2687 return tree_could_trap_p (t);
2688 return false;
2690 case FUNCTION_DECL:
2691 /* Assume that accesses to weak functions may trap, unless we know
2692 they are certainly defined in current TU or in some other
2693 LTO partition. */
2694 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2696 cgraph_node *node = cgraph_node::get (expr);
2697 if (node)
2698 node = node->function_symbol ();
2699 return !(node && node->in_other_partition);
2701 return false;
2703 case VAR_DECL:
2704 /* Assume that accesses to weak vars may trap, unless we know
2705 they are certainly defined in current TU or in some other
2706 LTO partition. */
2707 if (DECL_WEAK (expr) && !DECL_COMDAT (expr) && DECL_EXTERNAL (expr))
2709 varpool_node *node = varpool_node::get (expr);
2710 if (node)
2711 node = node->ultimate_alias_target ();
2712 return !(node && node->in_other_partition);
2714 return false;
2716 default:
2717 return false;
2722 /* Helper for stmt_could_throw_p. Return true if STMT (assumed to be a
2723 an assignment or a conditional) may throw. */
2725 static bool
2726 stmt_could_throw_1_p (gassign *stmt)
2728 enum tree_code code = gimple_assign_rhs_code (stmt);
2729 bool honor_nans = false;
2730 bool honor_snans = false;
2731 bool fp_operation = false;
2732 bool honor_trapv = false;
2733 tree t;
2734 size_t i;
2735 bool handled, ret;
2737 if (TREE_CODE_CLASS (code) == tcc_comparison
2738 || TREE_CODE_CLASS (code) == tcc_unary
2739 || TREE_CODE_CLASS (code) == tcc_binary
2740 || code == FMA_EXPR)
2742 if (TREE_CODE_CLASS (code) == tcc_comparison)
2743 t = TREE_TYPE (gimple_assign_rhs1 (stmt));
2744 else
2745 t = gimple_expr_type (stmt);
2746 fp_operation = FLOAT_TYPE_P (t);
2747 if (fp_operation)
2749 honor_nans = flag_trapping_math && !flag_finite_math_only;
2750 honor_snans = flag_signaling_nans != 0;
2752 else if (INTEGRAL_TYPE_P (t) && TYPE_OVERFLOW_TRAPS (t))
2753 honor_trapv = true;
2756 /* First check the LHS. */
2757 if (tree_could_trap_p (gimple_assign_lhs (stmt)))
2758 return true;
2760 /* Check if the main expression may trap. */
2761 ret = operation_could_trap_helper_p (code, fp_operation, honor_trapv,
2762 honor_nans, honor_snans,
2763 gimple_assign_rhs2 (stmt),
2764 &handled);
2765 if (handled)
2766 return ret;
2768 /* If the expression does not trap, see if any of the individual operands may
2769 trap. */
2770 for (i = 1; i < gimple_num_ops (stmt); i++)
2771 if (tree_could_trap_p (gimple_op (stmt, i)))
2772 return true;
2774 return false;
2778 /* Return true if statement STMT could throw an exception. */
2780 bool
2781 stmt_could_throw_p (gimple *stmt)
2783 if (!flag_exceptions)
2784 return false;
2786 /* The only statements that can throw an exception are assignments,
2787 conditionals, calls, resx, and asms. */
2788 switch (gimple_code (stmt))
2790 case GIMPLE_RESX:
2791 return true;
2793 case GIMPLE_CALL:
2794 return !gimple_call_nothrow_p (as_a <gcall *> (stmt));
2796 case GIMPLE_COND:
2798 if (!cfun->can_throw_non_call_exceptions)
2799 return false;
2800 gcond *cond = as_a <gcond *> (stmt);
2801 tree lhs = gimple_cond_lhs (cond);
2802 return operation_could_trap_p (gimple_cond_code (cond),
2803 FLOAT_TYPE_P (TREE_TYPE (lhs)),
2804 false, NULL_TREE);
2807 case GIMPLE_ASSIGN:
2808 if (!cfun->can_throw_non_call_exceptions
2809 || gimple_clobber_p (stmt))
2810 return false;
2811 return stmt_could_throw_1_p (as_a <gassign *> (stmt));
2813 case GIMPLE_ASM:
2814 if (!cfun->can_throw_non_call_exceptions)
2815 return false;
2816 return gimple_asm_volatile_p (as_a <gasm *> (stmt));
2818 default:
2819 return false;
2824 /* Return true if expression T could throw an exception. */
2826 bool
2827 tree_could_throw_p (tree t)
2829 if (!flag_exceptions)
2830 return false;
2831 if (TREE_CODE (t) == MODIFY_EXPR)
2833 if (cfun->can_throw_non_call_exceptions
2834 && tree_could_trap_p (TREE_OPERAND (t, 0)))
2835 return true;
2836 t = TREE_OPERAND (t, 1);
2839 if (TREE_CODE (t) == WITH_SIZE_EXPR)
2840 t = TREE_OPERAND (t, 0);
2841 if (TREE_CODE (t) == CALL_EXPR)
2842 return (call_expr_flags (t) & ECF_NOTHROW) == 0;
2843 if (cfun->can_throw_non_call_exceptions)
2844 return tree_could_trap_p (t);
2845 return false;
2848 /* Return true if STMT can throw an exception that is not caught within
2849 the current function (CFUN). */
2851 bool
2852 stmt_can_throw_external (gimple *stmt)
2854 int lp_nr;
2856 if (!stmt_could_throw_p (stmt))
2857 return false;
2859 lp_nr = lookup_stmt_eh_lp (stmt);
2860 return lp_nr == 0;
2863 /* Return true if STMT can throw an exception that is caught within
2864 the current function (CFUN). */
2866 bool
2867 stmt_can_throw_internal (gimple *stmt)
2869 int lp_nr;
2871 if (!stmt_could_throw_p (stmt))
2872 return false;
2874 lp_nr = lookup_stmt_eh_lp (stmt);
2875 return lp_nr > 0;
2878 /* Given a statement STMT in IFUN, if STMT can no longer throw, then
2879 remove any entry it might have from the EH table. Return true if
2880 any change was made. */
2882 bool
2883 maybe_clean_eh_stmt_fn (struct function *ifun, gimple *stmt)
2885 if (stmt_could_throw_p (stmt))
2886 return false;
2887 return remove_stmt_from_eh_lp_fn (ifun, stmt);
2890 /* Likewise, but always use the current function. */
2892 bool
2893 maybe_clean_eh_stmt (gimple *stmt)
2895 return maybe_clean_eh_stmt_fn (cfun, stmt);
2898 /* Given a statement OLD_STMT and a new statement NEW_STMT that has replaced
2899 OLD_STMT in the function, remove OLD_STMT from the EH table and put NEW_STMT
2900 in the table if it should be in there. Return TRUE if a replacement was
2901 done that my require an EH edge purge. */
2903 bool
2904 maybe_clean_or_replace_eh_stmt (gimple *old_stmt, gimple *new_stmt)
2906 int lp_nr = lookup_stmt_eh_lp (old_stmt);
2908 if (lp_nr != 0)
2910 bool new_stmt_could_throw = stmt_could_throw_p (new_stmt);
2912 if (new_stmt == old_stmt && new_stmt_could_throw)
2913 return false;
2915 remove_stmt_from_eh_lp (old_stmt);
2916 if (new_stmt_could_throw)
2918 add_stmt_to_eh_lp (new_stmt, lp_nr);
2919 return false;
2921 else
2922 return true;
2925 return false;
2928 /* Given a statement OLD_STMT in OLD_FUN and a duplicate statement NEW_STMT
2929 in NEW_FUN, copy the EH table data from OLD_STMT to NEW_STMT. The MAP
2930 operand is the return value of duplicate_eh_regions. */
2932 bool
2933 maybe_duplicate_eh_stmt_fn (struct function *new_fun, gimple *new_stmt,
2934 struct function *old_fun, gimple *old_stmt,
2935 hash_map<void *, void *> *map,
2936 int default_lp_nr)
2938 int old_lp_nr, new_lp_nr;
2940 if (!stmt_could_throw_p (new_stmt))
2941 return false;
2943 old_lp_nr = lookup_stmt_eh_lp_fn (old_fun, old_stmt);
2944 if (old_lp_nr == 0)
2946 if (default_lp_nr == 0)
2947 return false;
2948 new_lp_nr = default_lp_nr;
2950 else if (old_lp_nr > 0)
2952 eh_landing_pad old_lp, new_lp;
2954 old_lp = (*old_fun->eh->lp_array)[old_lp_nr];
2955 new_lp = static_cast<eh_landing_pad> (*map->get (old_lp));
2956 new_lp_nr = new_lp->index;
2958 else
2960 eh_region old_r, new_r;
2962 old_r = (*old_fun->eh->region_array)[-old_lp_nr];
2963 new_r = static_cast<eh_region> (*map->get (old_r));
2964 new_lp_nr = -new_r->index;
2967 add_stmt_to_eh_lp_fn (new_fun, new_stmt, new_lp_nr);
2968 return true;
2971 /* Similar, but both OLD_STMT and NEW_STMT are within the current function,
2972 and thus no remapping is required. */
2974 bool
2975 maybe_duplicate_eh_stmt (gimple *new_stmt, gimple *old_stmt)
2977 int lp_nr;
2979 if (!stmt_could_throw_p (new_stmt))
2980 return false;
2982 lp_nr = lookup_stmt_eh_lp (old_stmt);
2983 if (lp_nr == 0)
2984 return false;
2986 add_stmt_to_eh_lp (new_stmt, lp_nr);
2987 return true;
2990 /* Returns TRUE if oneh and twoh are exception handlers (gimple_try_cleanup of
2991 GIMPLE_TRY) that are similar enough to be considered the same. Currently
2992 this only handles handlers consisting of a single call, as that's the
2993 important case for C++: a destructor call for a particular object showing
2994 up in multiple handlers. */
2996 static bool
2997 same_handler_p (gimple_seq oneh, gimple_seq twoh)
2999 gimple_stmt_iterator gsi;
3000 gimple *ones, *twos;
3001 unsigned int ai;
3003 gsi = gsi_start (oneh);
3004 if (!gsi_one_before_end_p (gsi))
3005 return false;
3006 ones = gsi_stmt (gsi);
3008 gsi = gsi_start (twoh);
3009 if (!gsi_one_before_end_p (gsi))
3010 return false;
3011 twos = gsi_stmt (gsi);
3013 if (!is_gimple_call (ones)
3014 || !is_gimple_call (twos)
3015 || gimple_call_lhs (ones)
3016 || gimple_call_lhs (twos)
3017 || gimple_call_chain (ones)
3018 || gimple_call_chain (twos)
3019 || !gimple_call_same_target_p (ones, twos)
3020 || gimple_call_num_args (ones) != gimple_call_num_args (twos))
3021 return false;
3023 for (ai = 0; ai < gimple_call_num_args (ones); ++ai)
3024 if (!operand_equal_p (gimple_call_arg (ones, ai),
3025 gimple_call_arg (twos, ai), 0))
3026 return false;
3028 return true;
3031 /* Optimize
3032 try { A() } finally { try { ~B() } catch { ~A() } }
3033 try { ... } finally { ~A() }
3034 into
3035 try { A() } catch { ~B() }
3036 try { ~B() ... } finally { ~A() }
3038 This occurs frequently in C++, where A is a local variable and B is a
3039 temporary used in the initializer for A. */
3041 static void
3042 optimize_double_finally (gtry *one, gtry *two)
3044 gimple *oneh;
3045 gimple_stmt_iterator gsi;
3046 gimple_seq cleanup;
3048 cleanup = gimple_try_cleanup (one);
3049 gsi = gsi_start (cleanup);
3050 if (!gsi_one_before_end_p (gsi))
3051 return;
3053 oneh = gsi_stmt (gsi);
3054 if (gimple_code (oneh) != GIMPLE_TRY
3055 || gimple_try_kind (oneh) != GIMPLE_TRY_CATCH)
3056 return;
3058 if (same_handler_p (gimple_try_cleanup (oneh), gimple_try_cleanup (two)))
3060 gimple_seq seq = gimple_try_eval (oneh);
3062 gimple_try_set_cleanup (one, seq);
3063 gimple_try_set_kind (one, GIMPLE_TRY_CATCH);
3064 seq = copy_gimple_seq_and_replace_locals (seq);
3065 gimple_seq_add_seq (&seq, gimple_try_eval (two));
3066 gimple_try_set_eval (two, seq);
3070 /* Perform EH refactoring optimizations that are simpler to do when code
3071 flow has been lowered but EH structures haven't. */
3073 static void
3074 refactor_eh_r (gimple_seq seq)
3076 gimple_stmt_iterator gsi;
3077 gimple *one, *two;
3079 one = NULL;
3080 two = NULL;
3081 gsi = gsi_start (seq);
3082 while (1)
3084 one = two;
3085 if (gsi_end_p (gsi))
3086 two = NULL;
3087 else
3088 two = gsi_stmt (gsi);
3089 if (one && two)
3090 if (gtry *try_one = dyn_cast <gtry *> (one))
3091 if (gtry *try_two = dyn_cast <gtry *> (two))
3092 if (gimple_try_kind (try_one) == GIMPLE_TRY_FINALLY
3093 && gimple_try_kind (try_two) == GIMPLE_TRY_FINALLY)
3094 optimize_double_finally (try_one, try_two);
3095 if (one)
3096 switch (gimple_code (one))
3098 case GIMPLE_TRY:
3099 refactor_eh_r (gimple_try_eval (one));
3100 refactor_eh_r (gimple_try_cleanup (one));
3101 break;
3102 case GIMPLE_CATCH:
3103 refactor_eh_r (gimple_catch_handler (as_a <gcatch *> (one)));
3104 break;
3105 case GIMPLE_EH_FILTER:
3106 refactor_eh_r (gimple_eh_filter_failure (one));
3107 break;
3108 case GIMPLE_EH_ELSE:
3110 geh_else *eh_else_stmt = as_a <geh_else *> (one);
3111 refactor_eh_r (gimple_eh_else_n_body (eh_else_stmt));
3112 refactor_eh_r (gimple_eh_else_e_body (eh_else_stmt));
3114 break;
3115 default:
3116 break;
3118 if (two)
3119 gsi_next (&gsi);
3120 else
3121 break;
3125 namespace {
3127 const pass_data pass_data_refactor_eh =
3129 GIMPLE_PASS, /* type */
3130 "ehopt", /* name */
3131 OPTGROUP_NONE, /* optinfo_flags */
3132 TV_TREE_EH, /* tv_id */
3133 PROP_gimple_lcf, /* properties_required */
3134 0, /* properties_provided */
3135 0, /* properties_destroyed */
3136 0, /* todo_flags_start */
3137 0, /* todo_flags_finish */
3140 class pass_refactor_eh : public gimple_opt_pass
3142 public:
3143 pass_refactor_eh (gcc::context *ctxt)
3144 : gimple_opt_pass (pass_data_refactor_eh, ctxt)
3147 /* opt_pass methods: */
3148 virtual bool gate (function *) { return flag_exceptions != 0; }
3149 virtual unsigned int execute (function *)
3151 refactor_eh_r (gimple_body (current_function_decl));
3152 return 0;
3155 }; // class pass_refactor_eh
3157 } // anon namespace
3159 gimple_opt_pass *
3160 make_pass_refactor_eh (gcc::context *ctxt)
3162 return new pass_refactor_eh (ctxt);
3165 /* At the end of gimple optimization, we can lower RESX. */
3167 static bool
3168 lower_resx (basic_block bb, gresx *stmt,
3169 hash_map<eh_region, tree> *mnt_map)
3171 int lp_nr;
3172 eh_region src_r, dst_r;
3173 gimple_stmt_iterator gsi;
3174 gimple *x;
3175 tree fn, src_nr;
3176 bool ret = false;
3178 lp_nr = lookup_stmt_eh_lp (stmt);
3179 if (lp_nr != 0)
3180 dst_r = get_eh_region_from_lp_number (lp_nr);
3181 else
3182 dst_r = NULL;
3184 src_r = get_eh_region_from_number (gimple_resx_region (stmt));
3185 gsi = gsi_last_bb (bb);
3187 if (src_r == NULL)
3189 /* We can wind up with no source region when pass_cleanup_eh shows
3190 that there are no entries into an eh region and deletes it, but
3191 then the block that contains the resx isn't removed. This can
3192 happen without optimization when the switch statement created by
3193 lower_try_finally_switch isn't simplified to remove the eh case.
3195 Resolve this by expanding the resx node to an abort. */
3197 fn = builtin_decl_implicit (BUILT_IN_TRAP);
3198 x = gimple_build_call (fn, 0);
3199 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3201 while (EDGE_COUNT (bb->succs) > 0)
3202 remove_edge (EDGE_SUCC (bb, 0));
3204 else if (dst_r)
3206 /* When we have a destination region, we resolve this by copying
3207 the excptr and filter values into place, and changing the edge
3208 to immediately after the landing pad. */
3209 edge e;
3211 if (lp_nr < 0)
3213 basic_block new_bb;
3214 tree lab;
3216 /* We are resuming into a MUST_NOT_CALL region. Expand a call to
3217 the failure decl into a new block, if needed. */
3218 gcc_assert (dst_r->type == ERT_MUST_NOT_THROW);
3220 tree *slot = mnt_map->get (dst_r);
3221 if (slot == NULL)
3223 gimple_stmt_iterator gsi2;
3225 new_bb = create_empty_bb (bb);
3226 add_bb_to_loop (new_bb, bb->loop_father);
3227 lab = gimple_block_label (new_bb);
3228 gsi2 = gsi_start_bb (new_bb);
3230 fn = dst_r->u.must_not_throw.failure_decl;
3231 x = gimple_build_call (fn, 0);
3232 gimple_set_location (x, dst_r->u.must_not_throw.failure_loc);
3233 gsi_insert_after (&gsi2, x, GSI_CONTINUE_LINKING);
3235 mnt_map->put (dst_r, lab);
3237 else
3239 lab = *slot;
3240 new_bb = label_to_block (lab);
3243 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3244 e = make_single_succ_edge (bb, new_bb, EDGE_FALLTHRU);
3246 else
3248 edge_iterator ei;
3249 tree dst_nr = build_int_cst (integer_type_node, dst_r->index);
3251 fn = builtin_decl_implicit (BUILT_IN_EH_COPY_VALUES);
3252 src_nr = build_int_cst (integer_type_node, src_r->index);
3253 x = gimple_build_call (fn, 2, dst_nr, src_nr);
3254 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3256 /* Update the flags for the outgoing edge. */
3257 e = single_succ_edge (bb);
3258 gcc_assert (e->flags & EDGE_EH);
3259 e->flags = (e->flags & ~EDGE_EH) | EDGE_FALLTHRU;
3260 e->probability = profile_probability::always ();
3261 e->count = bb->count;
3263 /* If there are no more EH users of the landing pad, delete it. */
3264 FOR_EACH_EDGE (e, ei, e->dest->preds)
3265 if (e->flags & EDGE_EH)
3266 break;
3267 if (e == NULL)
3269 eh_landing_pad lp = get_eh_landing_pad_from_number (lp_nr);
3270 remove_eh_landing_pad (lp);
3274 ret = true;
3276 else
3278 tree var;
3280 /* When we don't have a destination region, this exception escapes
3281 up the call chain. We resolve this by generating a call to the
3282 _Unwind_Resume library function. */
3284 /* The ARM EABI redefines _Unwind_Resume as __cxa_end_cleanup
3285 with no arguments for C++. Check for that. */
3286 if (src_r->use_cxa_end_cleanup)
3288 fn = builtin_decl_implicit (BUILT_IN_CXA_END_CLEANUP);
3289 x = gimple_build_call (fn, 0);
3290 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3292 else
3294 fn = builtin_decl_implicit (BUILT_IN_EH_POINTER);
3295 src_nr = build_int_cst (integer_type_node, src_r->index);
3296 x = gimple_build_call (fn, 1, src_nr);
3297 var = create_tmp_var (ptr_type_node);
3298 var = make_ssa_name (var, x);
3299 gimple_call_set_lhs (x, var);
3300 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3302 /* When exception handling is delegated to a caller function, we
3303 have to guarantee that shadow memory variables living on stack
3304 will be cleaner before control is given to a parent function. */
3305 if (sanitize_flags_p (SANITIZE_ADDRESS))
3307 tree decl
3308 = builtin_decl_implicit (BUILT_IN_ASAN_HANDLE_NO_RETURN);
3309 gimple *g = gimple_build_call (decl, 0);
3310 gimple_set_location (g, gimple_location (stmt));
3311 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
3314 fn = builtin_decl_implicit (BUILT_IN_UNWIND_RESUME);
3315 x = gimple_build_call (fn, 1, var);
3316 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3319 gcc_assert (EDGE_COUNT (bb->succs) == 0);
3322 gsi_remove (&gsi, true);
3324 return ret;
3327 namespace {
3329 const pass_data pass_data_lower_resx =
3331 GIMPLE_PASS, /* type */
3332 "resx", /* name */
3333 OPTGROUP_NONE, /* optinfo_flags */
3334 TV_TREE_EH, /* tv_id */
3335 PROP_gimple_lcf, /* properties_required */
3336 0, /* properties_provided */
3337 0, /* properties_destroyed */
3338 0, /* todo_flags_start */
3339 0, /* todo_flags_finish */
3342 class pass_lower_resx : public gimple_opt_pass
3344 public:
3345 pass_lower_resx (gcc::context *ctxt)
3346 : gimple_opt_pass (pass_data_lower_resx, ctxt)
3349 /* opt_pass methods: */
3350 virtual bool gate (function *) { return flag_exceptions != 0; }
3351 virtual unsigned int execute (function *);
3353 }; // class pass_lower_resx
3355 unsigned
3356 pass_lower_resx::execute (function *fun)
3358 basic_block bb;
3359 bool dominance_invalidated = false;
3360 bool any_rewritten = false;
3362 hash_map<eh_region, tree> mnt_map;
3364 FOR_EACH_BB_FN (bb, fun)
3366 gimple *last = last_stmt (bb);
3367 if (last && is_gimple_resx (last))
3369 dominance_invalidated |=
3370 lower_resx (bb, as_a <gresx *> (last), &mnt_map);
3371 any_rewritten = true;
3375 if (dominance_invalidated)
3377 free_dominance_info (CDI_DOMINATORS);
3378 free_dominance_info (CDI_POST_DOMINATORS);
3381 return any_rewritten ? TODO_update_ssa_only_virtuals : 0;
3384 } // anon namespace
3386 gimple_opt_pass *
3387 make_pass_lower_resx (gcc::context *ctxt)
3389 return new pass_lower_resx (ctxt);
3392 /* Try to optimize var = {v} {CLOBBER} stmts followed just by
3393 external throw. */
3395 static void
3396 optimize_clobbers (basic_block bb)
3398 gimple_stmt_iterator gsi = gsi_last_bb (bb);
3399 bool any_clobbers = false;
3400 bool seen_stack_restore = false;
3401 edge_iterator ei;
3402 edge e;
3404 /* Only optimize anything if the bb contains at least one clobber,
3405 ends with resx (checked by caller), optionally contains some
3406 debug stmts or labels, or at most one __builtin_stack_restore
3407 call, and has an incoming EH edge. */
3408 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3410 gimple *stmt = gsi_stmt (gsi);
3411 if (is_gimple_debug (stmt))
3412 continue;
3413 if (gimple_clobber_p (stmt))
3415 any_clobbers = true;
3416 continue;
3418 if (!seen_stack_restore
3419 && gimple_call_builtin_p (stmt, BUILT_IN_STACK_RESTORE))
3421 seen_stack_restore = true;
3422 continue;
3424 if (gimple_code (stmt) == GIMPLE_LABEL)
3425 break;
3426 return;
3428 if (!any_clobbers)
3429 return;
3430 FOR_EACH_EDGE (e, ei, bb->preds)
3431 if (e->flags & EDGE_EH)
3432 break;
3433 if (e == NULL)
3434 return;
3435 gsi = gsi_last_bb (bb);
3436 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3438 gimple *stmt = gsi_stmt (gsi);
3439 if (!gimple_clobber_p (stmt))
3440 continue;
3441 unlink_stmt_vdef (stmt);
3442 gsi_remove (&gsi, true);
3443 release_defs (stmt);
3447 /* Try to sink var = {v} {CLOBBER} stmts followed just by
3448 internal throw to successor BB. */
3450 static int
3451 sink_clobbers (basic_block bb)
3453 edge e;
3454 edge_iterator ei;
3455 gimple_stmt_iterator gsi, dgsi;
3456 basic_block succbb;
3457 bool any_clobbers = false;
3458 unsigned todo = 0;
3460 /* Only optimize if BB has a single EH successor and
3461 all predecessor edges are EH too. */
3462 if (!single_succ_p (bb)
3463 || (single_succ_edge (bb)->flags & EDGE_EH) == 0)
3464 return 0;
3466 FOR_EACH_EDGE (e, ei, bb->preds)
3468 if ((e->flags & EDGE_EH) == 0)
3469 return 0;
3472 /* And BB contains only CLOBBER stmts before the final
3473 RESX. */
3474 gsi = gsi_last_bb (bb);
3475 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3477 gimple *stmt = gsi_stmt (gsi);
3478 if (is_gimple_debug (stmt))
3479 continue;
3480 if (gimple_code (stmt) == GIMPLE_LABEL)
3481 break;
3482 if (!gimple_clobber_p (stmt))
3483 return 0;
3484 any_clobbers = true;
3486 if (!any_clobbers)
3487 return 0;
3489 edge succe = single_succ_edge (bb);
3490 succbb = succe->dest;
3492 /* See if there is a virtual PHI node to take an updated virtual
3493 operand from. */
3494 gphi *vphi = NULL;
3495 tree vuse = NULL_TREE;
3496 for (gphi_iterator gpi = gsi_start_phis (succbb);
3497 !gsi_end_p (gpi); gsi_next (&gpi))
3499 tree res = gimple_phi_result (gpi.phi ());
3500 if (virtual_operand_p (res))
3502 vphi = gpi.phi ();
3503 vuse = res;
3504 break;
3508 dgsi = gsi_after_labels (succbb);
3509 gsi = gsi_last_bb (bb);
3510 for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
3512 gimple *stmt = gsi_stmt (gsi);
3513 tree lhs;
3514 if (is_gimple_debug (stmt))
3515 continue;
3516 if (gimple_code (stmt) == GIMPLE_LABEL)
3517 break;
3518 lhs = gimple_assign_lhs (stmt);
3519 /* Unfortunately we don't have dominance info updated at this
3520 point, so checking if
3521 dominated_by_p (CDI_DOMINATORS, succbb,
3522 gimple_bb (SSA_NAME_DEF_STMT (TREE_OPERAND (lhs, 0)))
3523 would be too costly. Thus, avoid sinking any clobbers that
3524 refer to non-(D) SSA_NAMEs. */
3525 if (TREE_CODE (lhs) == MEM_REF
3526 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
3527 && !SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0)))
3529 unlink_stmt_vdef (stmt);
3530 gsi_remove (&gsi, true);
3531 release_defs (stmt);
3532 continue;
3535 /* As we do not change stmt order when sinking across a
3536 forwarder edge we can keep virtual operands in place. */
3537 gsi_remove (&gsi, false);
3538 gsi_insert_before (&dgsi, stmt, GSI_NEW_STMT);
3540 /* But adjust virtual operands if we sunk across a PHI node. */
3541 if (vuse)
3543 gimple *use_stmt;
3544 imm_use_iterator iter;
3545 use_operand_p use_p;
3546 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vuse)
3547 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
3548 SET_USE (use_p, gimple_vdef (stmt));
3549 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse))
3551 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_vdef (stmt)) = 1;
3552 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 0;
3554 /* Adjust the incoming virtual operand. */
3555 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (vphi, succe), gimple_vuse (stmt));
3556 SET_USE (gimple_vuse_op (stmt), vuse);
3558 /* If there isn't a single predecessor but no virtual PHI node
3559 arrange for virtual operands to be renamed. */
3560 else if (gimple_vuse_op (stmt) != NULL_USE_OPERAND_P
3561 && !single_pred_p (succbb))
3563 /* In this case there will be no use of the VDEF of this stmt.
3564 ??? Unless this is a secondary opportunity and we have not
3565 removed unreachable blocks yet, so we cannot assert this.
3566 Which also means we will end up renaming too many times. */
3567 SET_USE (gimple_vuse_op (stmt), gimple_vop (cfun));
3568 mark_virtual_operands_for_renaming (cfun);
3569 todo |= TODO_update_ssa_only_virtuals;
3573 return todo;
3576 /* At the end of inlining, we can lower EH_DISPATCH. Return true when
3577 we have found some duplicate labels and removed some edges. */
3579 static bool
3580 lower_eh_dispatch (basic_block src, geh_dispatch *stmt)
3582 gimple_stmt_iterator gsi;
3583 int region_nr;
3584 eh_region r;
3585 tree filter, fn;
3586 gimple *x;
3587 bool redirected = false;
3589 region_nr = gimple_eh_dispatch_region (stmt);
3590 r = get_eh_region_from_number (region_nr);
3592 gsi = gsi_last_bb (src);
3594 switch (r->type)
3596 case ERT_TRY:
3598 auto_vec<tree> labels;
3599 tree default_label = NULL;
3600 eh_catch c;
3601 edge_iterator ei;
3602 edge e;
3603 hash_set<tree> seen_values;
3605 /* Collect the labels for a switch. Zero the post_landing_pad
3606 field becase we'll no longer have anything keeping these labels
3607 in existence and the optimizer will be free to merge these
3608 blocks at will. */
3609 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
3611 tree tp_node, flt_node, lab = c->label;
3612 bool have_label = false;
3614 c->label = NULL;
3615 tp_node = c->type_list;
3616 flt_node = c->filter_list;
3618 if (tp_node == NULL)
3620 default_label = lab;
3621 break;
3625 /* Filter out duplicate labels that arise when this handler
3626 is shadowed by an earlier one. When no labels are
3627 attached to the handler anymore, we remove
3628 the corresponding edge and then we delete unreachable
3629 blocks at the end of this pass. */
3630 if (! seen_values.contains (TREE_VALUE (flt_node)))
3632 tree t = build_case_label (TREE_VALUE (flt_node),
3633 NULL, lab);
3634 labels.safe_push (t);
3635 seen_values.add (TREE_VALUE (flt_node));
3636 have_label = true;
3639 tp_node = TREE_CHAIN (tp_node);
3640 flt_node = TREE_CHAIN (flt_node);
3642 while (tp_node);
3643 if (! have_label)
3645 remove_edge (find_edge (src, label_to_block (lab)));
3646 redirected = true;
3650 /* Clean up the edge flags. */
3651 FOR_EACH_EDGE (e, ei, src->succs)
3653 if (e->flags & EDGE_FALLTHRU)
3655 /* If there was no catch-all, use the fallthru edge. */
3656 if (default_label == NULL)
3657 default_label = gimple_block_label (e->dest);
3658 e->flags &= ~EDGE_FALLTHRU;
3661 gcc_assert (default_label != NULL);
3663 /* Don't generate a switch if there's only a default case.
3664 This is common in the form of try { A; } catch (...) { B; }. */
3665 if (!labels.exists ())
3667 e = single_succ_edge (src);
3668 e->flags |= EDGE_FALLTHRU;
3670 else
3672 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3673 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3674 region_nr));
3675 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3676 filter = make_ssa_name (filter, x);
3677 gimple_call_set_lhs (x, filter);
3678 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3680 /* Turn the default label into a default case. */
3681 default_label = build_case_label (NULL, NULL, default_label);
3682 sort_case_labels (labels);
3684 x = gimple_build_switch (filter, default_label, labels);
3685 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3688 break;
3690 case ERT_ALLOWED_EXCEPTIONS:
3692 edge b_e = BRANCH_EDGE (src);
3693 edge f_e = FALLTHRU_EDGE (src);
3695 fn = builtin_decl_implicit (BUILT_IN_EH_FILTER);
3696 x = gimple_build_call (fn, 1, build_int_cst (integer_type_node,
3697 region_nr));
3698 filter = create_tmp_var (TREE_TYPE (TREE_TYPE (fn)));
3699 filter = make_ssa_name (filter, x);
3700 gimple_call_set_lhs (x, filter);
3701 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3703 r->u.allowed.label = NULL;
3704 x = gimple_build_cond (EQ_EXPR, filter,
3705 build_int_cst (TREE_TYPE (filter),
3706 r->u.allowed.filter),
3707 NULL_TREE, NULL_TREE);
3708 gsi_insert_before (&gsi, x, GSI_SAME_STMT);
3710 b_e->flags = b_e->flags | EDGE_TRUE_VALUE;
3711 f_e->flags = (f_e->flags & ~EDGE_FALLTHRU) | EDGE_FALSE_VALUE;
3713 break;
3715 default:
3716 gcc_unreachable ();
3719 /* Replace the EH_DISPATCH with the SWITCH or COND generated above. */
3720 gsi_remove (&gsi, true);
3721 return redirected;
3724 namespace {
3726 const pass_data pass_data_lower_eh_dispatch =
3728 GIMPLE_PASS, /* type */
3729 "ehdisp", /* name */
3730 OPTGROUP_NONE, /* optinfo_flags */
3731 TV_TREE_EH, /* tv_id */
3732 PROP_gimple_lcf, /* properties_required */
3733 0, /* properties_provided */
3734 0, /* properties_destroyed */
3735 0, /* todo_flags_start */
3736 0, /* todo_flags_finish */
3739 class pass_lower_eh_dispatch : public gimple_opt_pass
3741 public:
3742 pass_lower_eh_dispatch (gcc::context *ctxt)
3743 : gimple_opt_pass (pass_data_lower_eh_dispatch, ctxt)
3746 /* opt_pass methods: */
3747 virtual bool gate (function *fun) { return fun->eh->region_tree != NULL; }
3748 virtual unsigned int execute (function *);
3750 }; // class pass_lower_eh_dispatch
3752 unsigned
3753 pass_lower_eh_dispatch::execute (function *fun)
3755 basic_block bb;
3756 int flags = 0;
3757 bool redirected = false;
3759 assign_filter_values ();
3761 FOR_EACH_BB_FN (bb, fun)
3763 gimple *last = last_stmt (bb);
3764 if (last == NULL)
3765 continue;
3766 if (gimple_code (last) == GIMPLE_EH_DISPATCH)
3768 redirected |= lower_eh_dispatch (bb,
3769 as_a <geh_dispatch *> (last));
3770 flags |= TODO_update_ssa_only_virtuals;
3772 else if (gimple_code (last) == GIMPLE_RESX)
3774 if (stmt_can_throw_external (last))
3775 optimize_clobbers (bb);
3776 else
3777 flags |= sink_clobbers (bb);
3781 if (redirected)
3782 delete_unreachable_blocks ();
3783 return flags;
3786 } // anon namespace
3788 gimple_opt_pass *
3789 make_pass_lower_eh_dispatch (gcc::context *ctxt)
3791 return new pass_lower_eh_dispatch (ctxt);
3794 /* Walk statements, see what regions and, optionally, landing pads
3795 are really referenced.
3797 Returns in R_REACHABLEP an sbitmap with bits set for reachable regions,
3798 and in LP_REACHABLE an sbitmap with bits set for reachable landing pads.
3800 Passing NULL for LP_REACHABLE is valid, in this case only reachable
3801 regions are marked.
3803 The caller is responsible for freeing the returned sbitmaps. */
3805 static void
3806 mark_reachable_handlers (sbitmap *r_reachablep, sbitmap *lp_reachablep)
3808 sbitmap r_reachable, lp_reachable;
3809 basic_block bb;
3810 bool mark_landing_pads = (lp_reachablep != NULL);
3811 gcc_checking_assert (r_reachablep != NULL);
3813 r_reachable = sbitmap_alloc (cfun->eh->region_array->length ());
3814 bitmap_clear (r_reachable);
3815 *r_reachablep = r_reachable;
3817 if (mark_landing_pads)
3819 lp_reachable = sbitmap_alloc (cfun->eh->lp_array->length ());
3820 bitmap_clear (lp_reachable);
3821 *lp_reachablep = lp_reachable;
3823 else
3824 lp_reachable = NULL;
3826 FOR_EACH_BB_FN (bb, cfun)
3828 gimple_stmt_iterator gsi;
3830 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3832 gimple *stmt = gsi_stmt (gsi);
3834 if (mark_landing_pads)
3836 int lp_nr = lookup_stmt_eh_lp (stmt);
3838 /* Negative LP numbers are MUST_NOT_THROW regions which
3839 are not considered BB enders. */
3840 if (lp_nr < 0)
3841 bitmap_set_bit (r_reachable, -lp_nr);
3843 /* Positive LP numbers are real landing pads, and BB enders. */
3844 else if (lp_nr > 0)
3846 gcc_assert (gsi_one_before_end_p (gsi));
3847 eh_region region = get_eh_region_from_lp_number (lp_nr);
3848 bitmap_set_bit (r_reachable, region->index);
3849 bitmap_set_bit (lp_reachable, lp_nr);
3853 /* Avoid removing regions referenced from RESX/EH_DISPATCH. */
3854 switch (gimple_code (stmt))
3856 case GIMPLE_RESX:
3857 bitmap_set_bit (r_reachable,
3858 gimple_resx_region (as_a <gresx *> (stmt)));
3859 break;
3860 case GIMPLE_EH_DISPATCH:
3861 bitmap_set_bit (r_reachable,
3862 gimple_eh_dispatch_region (
3863 as_a <geh_dispatch *> (stmt)));
3864 break;
3865 case GIMPLE_CALL:
3866 if (gimple_call_builtin_p (stmt, BUILT_IN_EH_COPY_VALUES))
3867 for (int i = 0; i < 2; ++i)
3869 tree rt = gimple_call_arg (stmt, i);
3870 HOST_WIDE_INT ri = tree_to_shwi (rt);
3872 gcc_assert (ri == (int)ri);
3873 bitmap_set_bit (r_reachable, ri);
3875 break;
3876 default:
3877 break;
3883 /* Remove unreachable handlers and unreachable landing pads. */
3885 static void
3886 remove_unreachable_handlers (void)
3888 sbitmap r_reachable, lp_reachable;
3889 eh_region region;
3890 eh_landing_pad lp;
3891 unsigned i;
3893 mark_reachable_handlers (&r_reachable, &lp_reachable);
3895 if (dump_file)
3897 fprintf (dump_file, "Before removal of unreachable regions:\n");
3898 dump_eh_tree (dump_file, cfun);
3899 fprintf (dump_file, "Reachable regions: ");
3900 dump_bitmap_file (dump_file, r_reachable);
3901 fprintf (dump_file, "Reachable landing pads: ");
3902 dump_bitmap_file (dump_file, lp_reachable);
3905 if (dump_file)
3907 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3908 if (region && !bitmap_bit_p (r_reachable, region->index))
3909 fprintf (dump_file,
3910 "Removing unreachable region %d\n",
3911 region->index);
3914 remove_unreachable_eh_regions (r_reachable);
3916 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3917 if (lp && !bitmap_bit_p (lp_reachable, lp->index))
3919 if (dump_file)
3920 fprintf (dump_file,
3921 "Removing unreachable landing pad %d\n",
3922 lp->index);
3923 remove_eh_landing_pad (lp);
3926 if (dump_file)
3928 fprintf (dump_file, "\n\nAfter removal of unreachable regions:\n");
3929 dump_eh_tree (dump_file, cfun);
3930 fprintf (dump_file, "\n\n");
3933 sbitmap_free (r_reachable);
3934 sbitmap_free (lp_reachable);
3936 if (flag_checking)
3937 verify_eh_tree (cfun);
3940 /* Remove unreachable handlers if any landing pads have been removed after
3941 last ehcleanup pass (due to gimple_purge_dead_eh_edges). */
3943 void
3944 maybe_remove_unreachable_handlers (void)
3946 eh_landing_pad lp;
3947 unsigned i;
3949 if (cfun->eh == NULL)
3950 return;
3952 FOR_EACH_VEC_SAFE_ELT (cfun->eh->lp_array, i, lp)
3953 if (lp && lp->post_landing_pad)
3955 if (label_to_block (lp->post_landing_pad) == NULL)
3957 remove_unreachable_handlers ();
3958 return;
3963 /* Remove regions that do not have landing pads. This assumes
3964 that remove_unreachable_handlers has already been run, and
3965 that we've just manipulated the landing pads since then.
3967 Preserve regions with landing pads and regions that prevent
3968 exceptions from propagating further, even if these regions
3969 are not reachable. */
3971 static void
3972 remove_unreachable_handlers_no_lp (void)
3974 eh_region region;
3975 sbitmap r_reachable;
3976 unsigned i;
3978 mark_reachable_handlers (&r_reachable, /*lp_reachablep=*/NULL);
3980 FOR_EACH_VEC_SAFE_ELT (cfun->eh->region_array, i, region)
3982 if (! region)
3983 continue;
3985 if (region->landing_pads != NULL
3986 || region->type == ERT_MUST_NOT_THROW)
3987 bitmap_set_bit (r_reachable, region->index);
3989 if (dump_file
3990 && !bitmap_bit_p (r_reachable, region->index))
3991 fprintf (dump_file,
3992 "Removing unreachable region %d\n",
3993 region->index);
3996 remove_unreachable_eh_regions (r_reachable);
3998 sbitmap_free (r_reachable);
4001 /* Undo critical edge splitting on an EH landing pad. Earlier, we
4002 optimisticaly split all sorts of edges, including EH edges. The
4003 optimization passes in between may not have needed them; if not,
4004 we should undo the split.
4006 Recognize this case by having one EH edge incoming to the BB and
4007 one normal edge outgoing; BB should be empty apart from the
4008 post_landing_pad label.
4010 Note that this is slightly different from the empty handler case
4011 handled by cleanup_empty_eh, in that the actual handler may yet
4012 have actual code but the landing pad has been separated from the
4013 handler. As such, cleanup_empty_eh relies on this transformation
4014 having been done first. */
4016 static bool
4017 unsplit_eh (eh_landing_pad lp)
4019 basic_block bb = label_to_block (lp->post_landing_pad);
4020 gimple_stmt_iterator gsi;
4021 edge e_in, e_out;
4023 /* Quickly check the edge counts on BB for singularity. */
4024 if (!single_pred_p (bb) || !single_succ_p (bb))
4025 return false;
4026 e_in = single_pred_edge (bb);
4027 e_out = single_succ_edge (bb);
4029 /* Input edge must be EH and output edge must be normal. */
4030 if ((e_in->flags & EDGE_EH) == 0 || (e_out->flags & EDGE_EH) != 0)
4031 return false;
4033 /* The block must be empty except for the labels and debug insns. */
4034 gsi = gsi_after_labels (bb);
4035 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4036 gsi_next_nondebug (&gsi);
4037 if (!gsi_end_p (gsi))
4038 return false;
4040 /* The destination block must not already have a landing pad
4041 for a different region. */
4042 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4044 glabel *label_stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4045 tree lab;
4046 int lp_nr;
4048 if (!label_stmt)
4049 break;
4050 lab = gimple_label_label (label_stmt);
4051 lp_nr = EH_LANDING_PAD_NR (lab);
4052 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4053 return false;
4056 /* The new destination block must not already be a destination of
4057 the source block, lest we merge fallthru and eh edges and get
4058 all sorts of confused. */
4059 if (find_edge (e_in->src, e_out->dest))
4060 return false;
4062 /* ??? We can get degenerate phis due to cfg cleanups. I would have
4063 thought this should have been cleaned up by a phicprop pass, but
4064 that doesn't appear to handle virtuals. Propagate by hand. */
4065 if (!gimple_seq_empty_p (phi_nodes (bb)))
4067 for (gphi_iterator gpi = gsi_start_phis (bb); !gsi_end_p (gpi); )
4069 gimple *use_stmt;
4070 gphi *phi = gpi.phi ();
4071 tree lhs = gimple_phi_result (phi);
4072 tree rhs = gimple_phi_arg_def (phi, 0);
4073 use_operand_p use_p;
4074 imm_use_iterator iter;
4076 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4078 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
4079 SET_USE (use_p, rhs);
4082 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
4083 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs) = 1;
4085 remove_phi_node (&gpi, true);
4089 if (dump_file && (dump_flags & TDF_DETAILS))
4090 fprintf (dump_file, "Unsplit EH landing pad %d to block %i.\n",
4091 lp->index, e_out->dest->index);
4093 /* Redirect the edge. Since redirect_eh_edge_1 expects to be moving
4094 a successor edge, humor it. But do the real CFG change with the
4095 predecessor of E_OUT in order to preserve the ordering of arguments
4096 to the PHI nodes in E_OUT->DEST. */
4097 redirect_eh_edge_1 (e_in, e_out->dest, false);
4098 redirect_edge_pred (e_out, e_in->src);
4099 e_out->flags = e_in->flags;
4100 e_out->probability = e_in->probability;
4101 e_out->count = e_in->count;
4102 remove_edge (e_in);
4104 return true;
4107 /* Examine each landing pad block and see if it matches unsplit_eh. */
4109 static bool
4110 unsplit_all_eh (void)
4112 bool changed = false;
4113 eh_landing_pad lp;
4114 int i;
4116 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4117 if (lp)
4118 changed |= unsplit_eh (lp);
4120 return changed;
4123 /* A subroutine of cleanup_empty_eh. Redirect all EH edges incoming
4124 to OLD_BB to NEW_BB; return true on success, false on failure.
4126 OLD_BB_OUT is the edge into NEW_BB from OLD_BB, so if we miss any
4127 PHI variables from OLD_BB we can pick them up from OLD_BB_OUT.
4128 Virtual PHIs may be deleted and marked for renaming. */
4130 static bool
4131 cleanup_empty_eh_merge_phis (basic_block new_bb, basic_block old_bb,
4132 edge old_bb_out, bool change_region)
4134 gphi_iterator ngsi, ogsi;
4135 edge_iterator ei;
4136 edge e;
4137 bitmap ophi_handled;
4139 /* The destination block must not be a regular successor for any
4140 of the preds of the landing pad. Thus, avoid turning
4141 <..>
4142 | \ EH
4143 | <..>
4145 <..>
4146 into
4147 <..>
4148 | | EH
4149 <..>
4150 which CFG verification would choke on. See PR45172 and PR51089. */
4151 FOR_EACH_EDGE (e, ei, old_bb->preds)
4152 if (find_edge (e->src, new_bb))
4153 return false;
4155 FOR_EACH_EDGE (e, ei, old_bb->preds)
4156 redirect_edge_var_map_clear (e);
4158 ophi_handled = BITMAP_ALLOC (NULL);
4160 /* First, iterate through the PHIs on NEW_BB and set up the edge_var_map
4161 for the edges we're going to move. */
4162 for (ngsi = gsi_start_phis (new_bb); !gsi_end_p (ngsi); gsi_next (&ngsi))
4164 gphi *ophi, *nphi = ngsi.phi ();
4165 tree nresult, nop;
4167 nresult = gimple_phi_result (nphi);
4168 nop = gimple_phi_arg_def (nphi, old_bb_out->dest_idx);
4170 /* Find the corresponding PHI in OLD_BB so we can forward-propagate
4171 the source ssa_name. */
4172 ophi = NULL;
4173 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4175 ophi = ogsi.phi ();
4176 if (gimple_phi_result (ophi) == nop)
4177 break;
4178 ophi = NULL;
4181 /* If we did find the corresponding PHI, copy those inputs. */
4182 if (ophi)
4184 /* If NOP is used somewhere else beyond phis in new_bb, give up. */
4185 if (!has_single_use (nop))
4187 imm_use_iterator imm_iter;
4188 use_operand_p use_p;
4190 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, nop)
4192 if (!gimple_debug_bind_p (USE_STMT (use_p))
4193 && (gimple_code (USE_STMT (use_p)) != GIMPLE_PHI
4194 || gimple_bb (USE_STMT (use_p)) != new_bb))
4195 goto fail;
4198 bitmap_set_bit (ophi_handled, SSA_NAME_VERSION (nop));
4199 FOR_EACH_EDGE (e, ei, old_bb->preds)
4201 location_t oloc;
4202 tree oop;
4204 if ((e->flags & EDGE_EH) == 0)
4205 continue;
4206 oop = gimple_phi_arg_def (ophi, e->dest_idx);
4207 oloc = gimple_phi_arg_location (ophi, e->dest_idx);
4208 redirect_edge_var_map_add (e, nresult, oop, oloc);
4211 /* If we didn't find the PHI, if it's a real variable or a VOP, we know
4212 from the fact that OLD_BB is tree_empty_eh_handler_p that the
4213 variable is unchanged from input to the block and we can simply
4214 re-use the input to NEW_BB from the OLD_BB_OUT edge. */
4215 else
4217 location_t nloc
4218 = gimple_phi_arg_location (nphi, old_bb_out->dest_idx);
4219 FOR_EACH_EDGE (e, ei, old_bb->preds)
4220 redirect_edge_var_map_add (e, nresult, nop, nloc);
4224 /* Second, verify that all PHIs from OLD_BB have been handled. If not,
4225 we don't know what values from the other edges into NEW_BB to use. */
4226 for (ogsi = gsi_start_phis (old_bb); !gsi_end_p (ogsi); gsi_next (&ogsi))
4228 gphi *ophi = ogsi.phi ();
4229 tree oresult = gimple_phi_result (ophi);
4230 if (!bitmap_bit_p (ophi_handled, SSA_NAME_VERSION (oresult)))
4231 goto fail;
4234 /* Finally, move the edges and update the PHIs. */
4235 for (ei = ei_start (old_bb->preds); (e = ei_safe_edge (ei)); )
4236 if (e->flags & EDGE_EH)
4238 /* ??? CFG manipluation routines do not try to update loop
4239 form on edge redirection. Do so manually here for now. */
4240 /* If we redirect a loop entry or latch edge that will either create
4241 a multiple entry loop or rotate the loop. If the loops merge
4242 we may have created a loop with multiple latches.
4243 All of this isn't easily fixed thus cancel the affected loop
4244 and mark the other loop as possibly having multiple latches. */
4245 if (e->dest == e->dest->loop_father->header)
4247 mark_loop_for_removal (e->dest->loop_father);
4248 new_bb->loop_father->latch = NULL;
4249 loops_state_set (LOOPS_MAY_HAVE_MULTIPLE_LATCHES);
4251 redirect_eh_edge_1 (e, new_bb, change_region);
4252 redirect_edge_succ (e, new_bb);
4253 flush_pending_stmts (e);
4255 else
4256 ei_next (&ei);
4258 BITMAP_FREE (ophi_handled);
4259 return true;
4261 fail:
4262 FOR_EACH_EDGE (e, ei, old_bb->preds)
4263 redirect_edge_var_map_clear (e);
4264 BITMAP_FREE (ophi_handled);
4265 return false;
4268 /* A subroutine of cleanup_empty_eh. Move a landing pad LP from its
4269 old region to NEW_REGION at BB. */
4271 static void
4272 cleanup_empty_eh_move_lp (basic_block bb, edge e_out,
4273 eh_landing_pad lp, eh_region new_region)
4275 gimple_stmt_iterator gsi;
4276 eh_landing_pad *pp;
4278 for (pp = &lp->region->landing_pads; *pp != lp; pp = &(*pp)->next_lp)
4279 continue;
4280 *pp = lp->next_lp;
4282 lp->region = new_region;
4283 lp->next_lp = new_region->landing_pads;
4284 new_region->landing_pads = lp;
4286 /* Delete the RESX that was matched within the empty handler block. */
4287 gsi = gsi_last_bb (bb);
4288 unlink_stmt_vdef (gsi_stmt (gsi));
4289 gsi_remove (&gsi, true);
4291 /* Clean up E_OUT for the fallthru. */
4292 e_out->flags = (e_out->flags & ~EDGE_EH) | EDGE_FALLTHRU;
4293 e_out->probability = profile_probability::always ();
4294 e_out->count = e_out->src->count;
4297 /* A subroutine of cleanup_empty_eh. Handle more complex cases of
4298 unsplitting than unsplit_eh was prepared to handle, e.g. when
4299 multiple incoming edges and phis are involved. */
4301 static bool
4302 cleanup_empty_eh_unsplit (basic_block bb, edge e_out, eh_landing_pad lp)
4304 gimple_stmt_iterator gsi;
4305 tree lab;
4307 /* We really ought not have totally lost everything following
4308 a landing pad label. Given that BB is empty, there had better
4309 be a successor. */
4310 gcc_assert (e_out != NULL);
4312 /* The destination block must not already have a landing pad
4313 for a different region. */
4314 lab = NULL;
4315 for (gsi = gsi_start_bb (e_out->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4317 glabel *stmt = dyn_cast <glabel *> (gsi_stmt (gsi));
4318 int lp_nr;
4320 if (!stmt)
4321 break;
4322 lab = gimple_label_label (stmt);
4323 lp_nr = EH_LANDING_PAD_NR (lab);
4324 if (lp_nr && get_eh_region_from_lp_number (lp_nr) != lp->region)
4325 return false;
4328 /* Attempt to move the PHIs into the successor block. */
4329 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, false))
4331 if (dump_file && (dump_flags & TDF_DETAILS))
4332 fprintf (dump_file,
4333 "Unsplit EH landing pad %d to block %i "
4334 "(via cleanup_empty_eh).\n",
4335 lp->index, e_out->dest->index);
4336 return true;
4339 return false;
4342 /* Return true if edge E_FIRST is part of an empty infinite loop
4343 or leads to such a loop through a series of single successor
4344 empty bbs. */
4346 static bool
4347 infinite_empty_loop_p (edge e_first)
4349 bool inf_loop = false;
4350 edge e;
4352 if (e_first->dest == e_first->src)
4353 return true;
4355 e_first->src->aux = (void *) 1;
4356 for (e = e_first; single_succ_p (e->dest); e = single_succ_edge (e->dest))
4358 gimple_stmt_iterator gsi;
4359 if (e->dest->aux)
4361 inf_loop = true;
4362 break;
4364 e->dest->aux = (void *) 1;
4365 gsi = gsi_after_labels (e->dest);
4366 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4367 gsi_next_nondebug (&gsi);
4368 if (!gsi_end_p (gsi))
4369 break;
4371 e_first->src->aux = NULL;
4372 for (e = e_first; e->dest->aux; e = single_succ_edge (e->dest))
4373 e->dest->aux = NULL;
4375 return inf_loop;
4378 /* Examine the block associated with LP to determine if it's an empty
4379 handler for its EH region. If so, attempt to redirect EH edges to
4380 an outer region. Return true the CFG was updated in any way. This
4381 is similar to jump forwarding, just across EH edges. */
4383 static bool
4384 cleanup_empty_eh (eh_landing_pad lp)
4386 basic_block bb = label_to_block (lp->post_landing_pad);
4387 gimple_stmt_iterator gsi;
4388 gimple *resx;
4389 eh_region new_region;
4390 edge_iterator ei;
4391 edge e, e_out;
4392 bool has_non_eh_pred;
4393 bool ret = false;
4394 int new_lp_nr;
4396 /* There can be zero or one edges out of BB. This is the quickest test. */
4397 switch (EDGE_COUNT (bb->succs))
4399 case 0:
4400 e_out = NULL;
4401 break;
4402 case 1:
4403 e_out = single_succ_edge (bb);
4404 break;
4405 default:
4406 return false;
4409 gsi = gsi_last_nondebug_bb (bb);
4410 resx = gsi_stmt (gsi);
4411 if (resx && is_gimple_resx (resx))
4413 if (stmt_can_throw_external (resx))
4414 optimize_clobbers (bb);
4415 else if (sink_clobbers (bb))
4416 ret = true;
4419 gsi = gsi_after_labels (bb);
4421 /* Make sure to skip debug statements. */
4422 if (!gsi_end_p (gsi) && is_gimple_debug (gsi_stmt (gsi)))
4423 gsi_next_nondebug (&gsi);
4425 /* If the block is totally empty, look for more unsplitting cases. */
4426 if (gsi_end_p (gsi))
4428 /* For the degenerate case of an infinite loop bail out.
4429 If bb has no successors and is totally empty, which can happen e.g.
4430 because of incorrect noreturn attribute, bail out too. */
4431 if (e_out == NULL
4432 || infinite_empty_loop_p (e_out))
4433 return ret;
4435 return ret | cleanup_empty_eh_unsplit (bb, e_out, lp);
4438 /* The block should consist only of a single RESX statement, modulo a
4439 preceding call to __builtin_stack_restore if there is no outgoing
4440 edge, since the call can be eliminated in this case. */
4441 resx = gsi_stmt (gsi);
4442 if (!e_out && gimple_call_builtin_p (resx, BUILT_IN_STACK_RESTORE))
4444 gsi_next_nondebug (&gsi);
4445 resx = gsi_stmt (gsi);
4447 if (!is_gimple_resx (resx))
4448 return ret;
4449 gcc_assert (gsi_one_nondebug_before_end_p (gsi));
4451 /* Determine if there are non-EH edges, or resx edges into the handler. */
4452 has_non_eh_pred = false;
4453 FOR_EACH_EDGE (e, ei, bb->preds)
4454 if (!(e->flags & EDGE_EH))
4455 has_non_eh_pred = true;
4457 /* Find the handler that's outer of the empty handler by looking at
4458 where the RESX instruction was vectored. */
4459 new_lp_nr = lookup_stmt_eh_lp (resx);
4460 new_region = get_eh_region_from_lp_number (new_lp_nr);
4462 /* If there's no destination region within the current function,
4463 redirection is trivial via removing the throwing statements from
4464 the EH region, removing the EH edges, and allowing the block
4465 to go unreachable. */
4466 if (new_region == NULL)
4468 gcc_assert (e_out == NULL);
4469 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4470 if (e->flags & EDGE_EH)
4472 gimple *stmt = last_stmt (e->src);
4473 remove_stmt_from_eh_lp (stmt);
4474 remove_edge (e);
4476 else
4477 ei_next (&ei);
4478 goto succeed;
4481 /* If the destination region is a MUST_NOT_THROW, allow the runtime
4482 to handle the abort and allow the blocks to go unreachable. */
4483 if (new_region->type == ERT_MUST_NOT_THROW)
4485 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
4486 if (e->flags & EDGE_EH)
4488 gimple *stmt = last_stmt (e->src);
4489 remove_stmt_from_eh_lp (stmt);
4490 add_stmt_to_eh_lp (stmt, new_lp_nr);
4491 remove_edge (e);
4493 else
4494 ei_next (&ei);
4495 goto succeed;
4498 /* Try to redirect the EH edges and merge the PHIs into the destination
4499 landing pad block. If the merge succeeds, we'll already have redirected
4500 all the EH edges. The handler itself will go unreachable if there were
4501 no normal edges. */
4502 if (cleanup_empty_eh_merge_phis (e_out->dest, bb, e_out, true))
4503 goto succeed;
4505 /* Finally, if all input edges are EH edges, then we can (potentially)
4506 reduce the number of transfers from the runtime by moving the landing
4507 pad from the original region to the new region. This is a win when
4508 we remove the last CLEANUP region along a particular exception
4509 propagation path. Since nothing changes except for the region with
4510 which the landing pad is associated, the PHI nodes do not need to be
4511 adjusted at all. */
4512 if (!has_non_eh_pred)
4514 cleanup_empty_eh_move_lp (bb, e_out, lp, new_region);
4515 if (dump_file && (dump_flags & TDF_DETAILS))
4516 fprintf (dump_file, "Empty EH handler %i moved to EH region %i.\n",
4517 lp->index, new_region->index);
4519 /* ??? The CFG didn't change, but we may have rendered the
4520 old EH region unreachable. Trigger a cleanup there. */
4521 return true;
4524 return ret;
4526 succeed:
4527 if (dump_file && (dump_flags & TDF_DETAILS))
4528 fprintf (dump_file, "Empty EH handler %i removed.\n", lp->index);
4529 remove_eh_landing_pad (lp);
4530 return true;
4533 /* Do a post-order traversal of the EH region tree. Examine each
4534 post_landing_pad block and see if we can eliminate it as empty. */
4536 static bool
4537 cleanup_all_empty_eh (void)
4539 bool changed = false;
4540 eh_landing_pad lp;
4541 int i;
4543 for (i = 1; vec_safe_iterate (cfun->eh->lp_array, i, &lp); ++i)
4544 if (lp)
4545 changed |= cleanup_empty_eh (lp);
4547 return changed;
4550 /* Perform cleanups and lowering of exception handling
4551 1) cleanups regions with handlers doing nothing are optimized out
4552 2) MUST_NOT_THROW regions that became dead because of 1) are optimized out
4553 3) Info about regions that are containing instructions, and regions
4554 reachable via local EH edges is collected
4555 4) Eh tree is pruned for regions no longer necessary.
4557 TODO: Push MUST_NOT_THROW regions to the root of the EH tree.
4558 Unify those that have the same failure decl and locus.
4561 static unsigned int
4562 execute_cleanup_eh_1 (void)
4564 /* Do this first: unsplit_all_eh and cleanup_all_empty_eh can die
4565 looking up unreachable landing pads. */
4566 remove_unreachable_handlers ();
4568 /* Watch out for the region tree vanishing due to all unreachable. */
4569 if (cfun->eh->region_tree)
4571 bool changed = false;
4573 if (optimize)
4574 changed |= unsplit_all_eh ();
4575 changed |= cleanup_all_empty_eh ();
4577 if (changed)
4579 free_dominance_info (CDI_DOMINATORS);
4580 free_dominance_info (CDI_POST_DOMINATORS);
4582 /* We delayed all basic block deletion, as we may have performed
4583 cleanups on EH edges while non-EH edges were still present. */
4584 delete_unreachable_blocks ();
4586 /* We manipulated the landing pads. Remove any region that no
4587 longer has a landing pad. */
4588 remove_unreachable_handlers_no_lp ();
4590 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4594 return 0;
4597 namespace {
4599 const pass_data pass_data_cleanup_eh =
4601 GIMPLE_PASS, /* type */
4602 "ehcleanup", /* name */
4603 OPTGROUP_NONE, /* optinfo_flags */
4604 TV_TREE_EH, /* tv_id */
4605 PROP_gimple_lcf, /* properties_required */
4606 0, /* properties_provided */
4607 0, /* properties_destroyed */
4608 0, /* todo_flags_start */
4609 0, /* todo_flags_finish */
4612 class pass_cleanup_eh : public gimple_opt_pass
4614 public:
4615 pass_cleanup_eh (gcc::context *ctxt)
4616 : gimple_opt_pass (pass_data_cleanup_eh, ctxt)
4619 /* opt_pass methods: */
4620 opt_pass * clone () { return new pass_cleanup_eh (m_ctxt); }
4621 virtual bool gate (function *fun)
4623 return fun->eh != NULL && fun->eh->region_tree != NULL;
4626 virtual unsigned int execute (function *);
4628 }; // class pass_cleanup_eh
4630 unsigned int
4631 pass_cleanup_eh::execute (function *fun)
4633 int ret = execute_cleanup_eh_1 ();
4635 /* If the function no longer needs an EH personality routine
4636 clear it. This exposes cross-language inlining opportunities
4637 and avoids references to a never defined personality routine. */
4638 if (DECL_FUNCTION_PERSONALITY (current_function_decl)
4639 && function_needs_eh_personality (fun) != eh_personality_lang)
4640 DECL_FUNCTION_PERSONALITY (current_function_decl) = NULL_TREE;
4642 return ret;
4645 } // anon namespace
4647 gimple_opt_pass *
4648 make_pass_cleanup_eh (gcc::context *ctxt)
4650 return new pass_cleanup_eh (ctxt);
4653 /* Verify that BB containing STMT as the last statement, has precisely the
4654 edge that make_eh_edges would create. */
4656 DEBUG_FUNCTION bool
4657 verify_eh_edges (gimple *stmt)
4659 basic_block bb = gimple_bb (stmt);
4660 eh_landing_pad lp = NULL;
4661 int lp_nr;
4662 edge_iterator ei;
4663 edge e, eh_edge;
4665 lp_nr = lookup_stmt_eh_lp (stmt);
4666 if (lp_nr > 0)
4667 lp = get_eh_landing_pad_from_number (lp_nr);
4669 eh_edge = NULL;
4670 FOR_EACH_EDGE (e, ei, bb->succs)
4672 if (e->flags & EDGE_EH)
4674 if (eh_edge)
4676 error ("BB %i has multiple EH edges", bb->index);
4677 return true;
4679 else
4680 eh_edge = e;
4684 if (lp == NULL)
4686 if (eh_edge)
4688 error ("BB %i can not throw but has an EH edge", bb->index);
4689 return true;
4691 return false;
4694 if (!stmt_could_throw_p (stmt))
4696 error ("BB %i last statement has incorrectly set lp", bb->index);
4697 return true;
4700 if (eh_edge == NULL)
4702 error ("BB %i is missing an EH edge", bb->index);
4703 return true;
4706 if (eh_edge->dest != label_to_block (lp->post_landing_pad))
4708 error ("Incorrect EH edge %i->%i", bb->index, eh_edge->dest->index);
4709 return true;
4712 return false;
4715 /* Similarly, but handle GIMPLE_EH_DISPATCH specifically. */
4717 DEBUG_FUNCTION bool
4718 verify_eh_dispatch_edge (geh_dispatch *stmt)
4720 eh_region r;
4721 eh_catch c;
4722 basic_block src, dst;
4723 bool want_fallthru = true;
4724 edge_iterator ei;
4725 edge e, fall_edge;
4727 r = get_eh_region_from_number (gimple_eh_dispatch_region (stmt));
4728 src = gimple_bb (stmt);
4730 FOR_EACH_EDGE (e, ei, src->succs)
4731 gcc_assert (e->aux == NULL);
4733 switch (r->type)
4735 case ERT_TRY:
4736 for (c = r->u.eh_try.first_catch; c ; c = c->next_catch)
4738 dst = label_to_block (c->label);
4739 e = find_edge (src, dst);
4740 if (e == NULL)
4742 error ("BB %i is missing an edge", src->index);
4743 return true;
4745 e->aux = (void *)e;
4747 /* A catch-all handler doesn't have a fallthru. */
4748 if (c->type_list == NULL)
4750 want_fallthru = false;
4751 break;
4754 break;
4756 case ERT_ALLOWED_EXCEPTIONS:
4757 dst = label_to_block (r->u.allowed.label);
4758 e = find_edge (src, dst);
4759 if (e == NULL)
4761 error ("BB %i is missing an edge", src->index);
4762 return true;
4764 e->aux = (void *)e;
4765 break;
4767 default:
4768 gcc_unreachable ();
4771 fall_edge = NULL;
4772 FOR_EACH_EDGE (e, ei, src->succs)
4774 if (e->flags & EDGE_FALLTHRU)
4776 if (fall_edge != NULL)
4778 error ("BB %i too many fallthru edges", src->index);
4779 return true;
4781 fall_edge = e;
4783 else if (e->aux)
4784 e->aux = NULL;
4785 else
4787 error ("BB %i has incorrect edge", src->index);
4788 return true;
4791 if ((fall_edge != NULL) ^ want_fallthru)
4793 error ("BB %i has incorrect fallthru edge", src->index);
4794 return true;
4797 return false;