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